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
|
# Copyright 2009 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
# We like global!
# pylint: disable-msg=W0603,W0702
"""Layers used by Canonical tests.
Layers are the mechanism used by the Zope3 test runner to efficiently
provide environments for tests and are documented in the lib/zope/testing.
Note that every Layer should define all of setUp, tearDown, testSetUp
and testTearDown. If you don't do this, a base class' method will be called
instead probably breaking something.
Preferred style is to not use the 'cls' argument to Layer class methods,
as this is unambguious.
TODO: Make the Zope3 test runner handle multiple layers per test instead
of one, forcing us to attempt to make some sort of layer tree.
-- StuartBishop 20060619
"""
__metaclass__ = type
__all__ = [
'AppServerLayer',
'BaseLayer',
'BaseWindmillLayer',
'DatabaseFunctionalLayer',
'DatabaseLayer',
'ExperimentalLaunchpadZopelessLayer',
'FunctionalLayer',
'GoogleLaunchpadFunctionalLayer',
'GoogleServiceLayer',
'LaunchpadFunctionalLayer',
'LaunchpadLayer',
'LaunchpadScriptLayer',
'LaunchpadTestSetup',
'LaunchpadZopelessLayer',
'LayerInvariantError',
'LayerIsolationError',
'LibrarianLayer',
'PageTestLayer',
'TwistedAppServerLayer',
'TwistedLaunchpadZopelessLayer',
'TwistedLayer',
'YUITestLayer',
'ZopelessAppServerLayer',
'ZopelessDatabaseLayer',
'ZopelessLayer',
'disconnect_stores',
'reconnect_stores',
]
from cProfile import Profile
import datetime
import errno
import gc
import logging
import os
import signal
import socket
import subprocess
import sys
import tempfile
from textwrap import dedent
import threading
import time
from unittest import (
TestCase,
TestResult,
)
from urllib import urlopen
from fixtures import (
Fixture,
MonkeyPatch,
)
from lazr.restful.utils import safe_hasattr
import psycopg2
from storm.zope.interfaces import IZStorm
import transaction
from windmill.bin.admin_lib import (
start_windmill,
teardown as windmill_teardown,
)
import wsgi_intercept
from wsgi_intercept import httplib2_intercept
from zope.app.publication.httpfactory import chooseClasses
import zope.app.testing.functional
from zope.app.testing.functional import (
FunctionalTestSetup,
ZopePublication,
)
from zope.component import (
getUtility,
globalregistry,
provideUtility,
)
from zope.component.interfaces import ComponentLookupError
import zope.publisher.publish
from zope.security.management import getSecurityPolicy
from zope.security.simplepolicies import PermissiveSecurityPolicy
from zope.server.logger.pythonlogger import PythonLogger
from zope.testing.testrunner.runner import FakeInputContinueGenerator
from canonical.config import (
CanonicalConfig,
config,
dbconfig,
)
from canonical.config.fixture import (
ConfigFixture,
ConfigUseFixture,
)
from canonical.database.revision import (
confirm_dbrevision,
confirm_dbrevision_on_startup,
)
from canonical.database.sqlbase import (
cursor,
session_store,
ZopelessTransactionManager,
)
from canonical.launchpad.interfaces.mailbox import IMailBox
from canonical.launchpad.scripts import execute_zcml_for_scripts
from canonical.launchpad.webapp.interfaces import (
DEFAULT_FLAVOR,
IOpenLaunchBag,
IStoreSelector,
MAIN_STORE,
)
from canonical.launchpad.webapp.servers import (
LaunchpadAccessLogger,
register_launchpad_request_publication_factories,
)
import canonical.launchpad.webapp.session
from canonical.launchpad.webapp.vhosts import allvhosts
from canonical.lazr import pidfile
from canonical.lazr.testing.layers import MockRootFolder
from canonical.lazr.timeout import (
get_default_timeout_function,
set_default_timeout_function,
)
from canonical.librarian.testing.server import LibrarianServerFixture
from canonical.lp import initZopeless
from canonical.testing import reset_logging
from canonical.testing.profiled import profiled
from canonical.testing.smtpd import SMTPController
from lp.services.googlesearch.tests.googleserviceharness import (
GoogleServiceTestSetup,
)
from lp.services.mail.mailbox import TestMailBox
import lp.services.mail.stub
from lp.services.memcache.client import memcache_client_factory
from lp.services.osutils import kill_by_pidfile
from lp.services.rabbit.testing.server import RabbitServer
from lp.testing import (
ANONYMOUS,
is_logged_in,
login,
logout,
)
from lp.testing.pgsql import PgTestSetup
orig__call__ = zope.app.testing.functional.HTTPCaller.__call__
COMMA = ','
WAIT_INTERVAL = datetime.timedelta(seconds=180)
def set_up_functional_test():
return FunctionalTestSetup('zcml/ftesting.zcml')
class LayerError(Exception):
pass
class LayerInvariantError(LayerError):
"""Layer self checks have detected a fault. Invariant has been violated.
This indicates the Layer infrastructure has messed up. The test run
should be aborted.
"""
pass
class LayerIsolationError(LayerError):
"""Test isolation has been broken, probably by the test we just ran.
This generally indicates a test has screwed up by not resetting
something correctly to the default state.
The test suite should abort if it cannot clean up the mess as further
test failures may well be spurious.
"""
def is_ca_available():
"""Returns true if the component architecture has been loaded"""
try:
getUtility(IOpenLaunchBag)
except ComponentLookupError:
return False
else:
return True
def disconnect_stores():
"""Disconnect Storm stores."""
zstorm = getUtility(IZStorm)
stores = [
store for name, store in zstorm.iterstores() if name != 'session']
# If we have any stores, abort the transaction and close them.
if stores:
for store in stores:
zstorm.remove(store)
transaction.abort()
for store in stores:
store.close()
def reconnect_stores(database_config_section='launchpad'):
"""Reconnect Storm stores, resetting the dbconfig to its defaults.
After reconnecting, the database revision will be checked to make
sure the right data is available.
"""
disconnect_stores()
dbconfig.setConfigSection(database_config_section)
main_store = getUtility(IStoreSelector).get(MAIN_STORE, DEFAULT_FLAVOR)
assert main_store is not None, 'Failed to reconnect'
# Confirm the database has the right patchlevel
confirm_dbrevision(cursor())
# Confirm that SQLOS is again talking to the database (it connects
# as soon as SQLBase._connection is accessed
r = main_store.execute('SELECT count(*) FROM LaunchpadDatabaseRevision')
assert r.get_one()[0] > 0, 'Storm is not talking to the database'
assert session_store() is not None, 'Failed to reconnect'
def wait_children(seconds=120):
"""Wait for all children to exit.
:param seconds: Maximum number of seconds to wait. If None, wait
forever.
"""
now = datetime.datetime.now
if seconds is None:
until = None
else:
until = now() + datetime.timedelta(seconds=seconds)
while True:
try:
os.waitpid(-1, os.WNOHANG)
except OSError, error:
if error.errno != errno.ECHILD:
raise
break
if until is not None and now() > until:
break
class BaseLayer:
"""Base layer.
All out layers should subclass Base, as this is where we will put
test isolation checks to ensure that tests to not leave global
resources in a mess.
XXX: StuartBishop 2006-07-12: Unit tests (tests with no layer) will not
get these checks. The Z3 test runner should be updated so that a layer
can be specified to use for unit tests.
"""
# Set to True when we are running tests in this layer.
isSetUp = False
# The name of this test - this is the same output that the testrunner
# displays. It is probably unique, but not guaranteed to be so.
test_name = None
# A flag to disable a check for threads still running after test
# completion. This is hopefully a temporary measure; see the comment
# in tearTestDown.
disable_thread_check = False
# A flag to make services like Librarian and Memcached to persist
# between test runs. This flag is set in setUp() by looking at the
# LP_PERSISTENT_TEST_SERVICES environment variable.
persist_test_services = False
# Things we need to cleanup.
fixture = None
# ConfigFixtures for the configs generated for this layer. Set to None
# if the layer is not setUp, or if persistent tests services are in use.
config_fixture = None
appserver_config_fixture = None
# The config names that are generated for this layer. Set to None when
# the layer is not setUp.
config_name = None
appserver_config_name = None
@classmethod
def make_config(cls, config_name, clone_from, attr_name):
"""Create a temporary config and link it into the layer cleanup."""
cfg_fixture = ConfigFixture(config_name, clone_from)
cls.fixture.addCleanup(cfg_fixture.cleanUp)
cfg_fixture.setUp()
cls.fixture.addCleanup(setattr, cls, attr_name, None)
setattr(cls, attr_name, cfg_fixture)
@classmethod
@profiled
def setUp(cls):
# Set the default appserver config instance name.
# May be changed as required eg when running parallel tests.
cls.appserver_config_name = 'testrunner-appserver'
BaseLayer.isSetUp = True
cls.fixture = Fixture()
cls.fixture.setUp()
cls.fixture.addCleanup(setattr, cls, 'fixture', None)
BaseLayer.persist_test_services = (
os.environ.get('LP_PERSISTENT_TEST_SERVICES') is not None)
# We can only do unique test allocation and parallelisation if
# LP_PERSISTENT_TEST_SERVICES is off.
if not BaseLayer.persist_test_services:
test_instance = str(os.getpid())
os.environ['LP_TEST_INSTANCE'] = test_instance
cls.fixture.addCleanup(os.environ.pop, 'LP_TEST_INSTANCE', '')
# Kill any Memcached or Librarian left running from a previous
# test run, or from the parent test process if the current
# layer is being run in a subprocess. No need to be polite
# about killing memcached - just do it quickly.
kill_by_pidfile(MemcachedLayer.getPidFile(), num_polls=0)
config_name = 'testrunner_%s' % test_instance
cls.make_config(config_name, 'testrunner', 'config_fixture')
app_config_name = 'testrunner-appserver_%s' % test_instance
cls.make_config(
app_config_name, 'testrunner-appserver',
'appserver_config_fixture')
cls.appserver_config_name = app_config_name
else:
config_name = 'testrunner'
app_config_name = 'testrunner-appserver'
cls.config_name = config_name
cls.fixture.addCleanup(setattr, cls, 'config_name', None)
cls.appserver_config_name = app_config_name
cls.fixture.addCleanup(setattr, cls, 'appserver_config_name', None)
use_fixture = ConfigUseFixture(config_name)
cls.fixture.addCleanup(use_fixture.cleanUp)
use_fixture.setUp()
# Kill any database left lying around from a previous test run.
db_fixture = LaunchpadTestSetup()
try:
db_fixture.connect().close()
except psycopg2.Error:
# We assume this means 'no test database exists.'
pass
else:
db_fixture.dropDb()
@classmethod
@profiled
def tearDown(cls):
cls.fixture.cleanUp()
BaseLayer.isSetUp = False
@classmethod
@profiled
def testSetUp(cls):
# Store currently running threads so we can detect if a test
# leaves new threads running.
BaseLayer._threads = threading.enumerate()
BaseLayer.check()
BaseLayer.original_working_directory = os.getcwd()
# Tests and test infrastruture sometimes needs to know the test
# name. The testrunner doesn't provide this, so we have to do
# some snooping.
import inspect
frame = inspect.currentframe()
try:
while frame.f_code.co_name != 'startTest':
frame = frame.f_back
BaseLayer.test_name = str(frame.f_locals['test'])
finally:
del frame # As per no-leak stack inspection in Python reference.
@classmethod
@profiled
def testTearDown(cls):
# Get our current working directory, handling the case where it no
# longer exists (!).
try:
cwd = os.getcwd()
except OSError:
cwd = None
# Handle a changed working directory. If the test succeeded,
# add an error. Then restore the working directory so the test
# run can continue.
if cwd != BaseLayer.original_working_directory:
BaseLayer.flagTestIsolationFailure(
"Test failed to restore working directory.")
os.chdir(BaseLayer.original_working_directory)
BaseLayer.original_working_directory = None
reset_logging()
del lp.services.mail.stub.test_emails[:]
BaseLayer.test_name = None
BaseLayer.check()
def new_live_threads():
return [
thread for thread in threading.enumerate()
if thread not in BaseLayer._threads and thread.isAlive()]
if BaseLayer.disable_thread_check:
new_threads = None
else:
for loop in range(0, 100):
# Check for tests that leave live threads around early.
# A live thread may be the cause of other failures, such as
# uncollectable garbage.
new_threads = new_live_threads()
has_live_threads = False
for new_thread in new_threads:
new_thread.join(0.1)
if new_thread.isAlive():
has_live_threads = True
if has_live_threads:
# Trigger full garbage collection that might be
# blocking threads from exiting.
gc.collect()
else:
break
new_threads = new_live_threads()
if new_threads:
# BaseLayer.disable_thread_check is a mechanism to stop
# tests that leave threads behind from failing. Its use
# should only ever be temporary.
if BaseLayer.disable_thread_check:
print (
"ERROR DISABLED: "
"Test left new live threads: %s") % repr(new_threads)
else:
BaseLayer.flagTestIsolationFailure(
"Test left new live threads: %s" % repr(new_threads))
BaseLayer.disable_thread_check = False
del BaseLayer._threads
if signal.getsignal(signal.SIGCHLD) != signal.SIG_DFL:
BaseLayer.flagTestIsolationFailure(
"Test left SIGCHLD handler.")
# Objects with __del__ methods cannot participate in refence cycles.
# Fail tests with memory leaks now rather than when Launchpad crashes
# due to a leak because someone ignored the warnings.
if gc.garbage:
del gc.garbage[:]
gc.collect() # Expensive, so only do if there might be garbage.
if gc.garbage:
BaseLayer.flagTestIsolationFailure(
"Test left uncollectable garbage\n"
"%s (referenced from %s)"
% (gc.garbage, gc.get_referrers(*gc.garbage)))
@classmethod
@profiled
def check(cls):
"""Check that the environment is working as expected.
We check here so we can detect tests that, for example,
initialize the Zopeless or Functional environments and
are using the incorrect layer.
"""
if FunctionalLayer.isSetUp and ZopelessLayer.isSetUp:
raise LayerInvariantError(
"Both Zopefull and Zopeless CA environments setup")
# Detect a test that causes the component architecture to be loaded.
# This breaks test isolation, as it cannot be torn down.
if (is_ca_available()
and not FunctionalLayer.isSetUp
and not ZopelessLayer.isSetUp):
raise LayerIsolationError(
"Component architecture should not be loaded by tests. "
"This should only be loaded by the Layer.")
# Detect a test that installed the Zopeless database adapter
# but failed to unregister it. This could be done automatically,
# but it is better for the tear down to be explicit.
if ZopelessTransactionManager._installed is not None:
raise LayerIsolationError(
"Zopeless environment was setup and not torn down.")
# Detect a test that forgot to reset the default socket timeout.
# This safety belt is cheap and protects us from very nasty
# intermittent test failures: see bug #140068 for an example.
if socket.getdefaulttimeout() is not None:
raise LayerIsolationError(
"Test didn't reset the socket default timeout.")
@classmethod
def flagTestIsolationFailure(cls, message):
"""Handle a breakdown in test isolation.
If the test that broke isolation thinks it succeeded,
add an error. If the test failed, don't add a notification
as the isolation breakdown is probably just fallout.
The layer that detected the isolation failure still needs to
repair the damage, or in the worst case abort the test run.
"""
test_result = BaseLayer.getCurrentTestResult()
if test_result.wasSuccessful():
test_case = BaseLayer.getCurrentTestCase()
try:
raise LayerIsolationError(message)
except LayerIsolationError:
test_result.addError(test_case, sys.exc_info())
@classmethod
def getCurrentTestResult(cls):
"""Return the TestResult currently in play."""
import inspect
frame = inspect.currentframe()
try:
while True:
f_self = frame.f_locals.get('self', None)
if isinstance(f_self, TestResult):
return frame.f_locals['self']
frame = frame.f_back
finally:
del frame # As per no-leak stack inspection in Python reference.
@classmethod
def getCurrentTestCase(cls):
"""Return the test currently in play."""
import inspect
frame = inspect.currentframe()
try:
while True:
f_self = frame.f_locals.get('self', None)
if isinstance(f_self, TestCase):
return f_self
f_test = frame.f_locals.get('test', None)
if isinstance(f_test, TestCase):
return f_test
frame = frame.f_back
return frame.f_locals['test']
finally:
del frame # As per no-leak stack inspection in Python reference.
@classmethod
def appserver_config(cls):
"""Return a config suitable for AppServer tests."""
return CanonicalConfig(cls.appserver_config_name)
@classmethod
def appserver_root_url(cls, facet='mainsite', ensureSlash=False):
"""Return the correct app server root url for the given facet."""
return cls.appserver_config().appserver_root_url(
facet, ensureSlash)
class MemcachedLayer(BaseLayer):
"""Provides tests access to a memcached.
Most tests needing memcache access will actually need to use
ZopelessLayer, FunctionalLayer or sublayer as they will be accessing
memcached using a utility.
"""
_reset_between_tests = True
# A memcache.Client instance.
client = None
# A subprocess.Popen instance if this process spawned the test
# memcached.
_memcached_process = None
_is_setup = False
@classmethod
@profiled
def setUp(cls):
cls._is_setup = True
# Create a client
MemcachedLayer.client = memcache_client_factory()
if (BaseLayer.persist_test_services and
os.path.exists(MemcachedLayer.getPidFile())):
return
# First, check to see if there is a memcached already running.
# This happens when new layers are run as a subprocess.
test_key = "MemcachedLayer__live_test"
if MemcachedLayer.client.set(test_key, "live"):
return
cmd = [
'memcached',
'-m', str(config.memcached.memory_size),
'-l', str(config.memcached.address),
'-p', str(config.memcached.port),
'-U', str(config.memcached.port),
]
if config.memcached.verbose:
cmd.append('-vv')
MemcachedLayer._memcached_process = subprocess.Popen(
cmd, stdin=subprocess.PIPE)
MemcachedLayer._memcached_process.stdin.close()
# Wait for the memcached to become operational.
while not MemcachedLayer.client.set(test_key, "live"):
if MemcachedLayer._memcached_process.returncode is not None:
raise LayerInvariantError(
"memcached never started or has died.",
MemcachedLayer._memcached_process.stdout.read())
MemcachedLayer.client.forget_dead_hosts()
time.sleep(0.1)
# Store the pidfile for other processes to kill.
pid_file = MemcachedLayer.getPidFile()
open(pid_file, 'w').write(str(MemcachedLayer._memcached_process.pid))
@classmethod
@profiled
def tearDown(cls):
if not cls._is_setup:
return
cls._is_setup = False
MemcachedLayer.client.disconnect_all()
MemcachedLayer.client = None
if not BaseLayer.persist_test_services:
# Kill our memcached, and there is no reason to be nice about it.
kill_by_pidfile(MemcachedLayer.getPidFile())
MemcachedLayer._memcached_process = None
@classmethod
@profiled
def testSetUp(cls):
if MemcachedLayer._reset_between_tests:
MemcachedLayer.client.forget_dead_hosts()
MemcachedLayer.client.flush_all()
@classmethod
@profiled
def testTearDown(cls):
pass
@classmethod
def getPidFile(cls):
return os.path.join(config.root, '.memcache.pid')
@classmethod
def purge(cls):
"Purge everything from our memcached."
MemcachedLayer.client.flush_all() # Only do this in tests!
class RabbitMQLayer(BaseLayer):
"""Provides tests access to a rabbitMQ instance."""
_reset_between_tests = True
rabbit = RabbitServer()
_is_setup = False
@classmethod
@profiled
def setUp(cls):
cls.rabbit.setUp()
cls.config_fixture.add_section(
cls.rabbit.config.service_config)
cls.appserver_config_fixture.add_section(
cls.rabbit.config.service_config)
cls._is_setup = True
@classmethod
@profiled
def tearDown(cls):
if not cls._is_setup:
return
cls.rabbit.cleanUp()
cls._is_setup = False
# Can't pop the config above, so bail here and let the test runner
# start a sub-process.
raise NotImplementedError
@classmethod
@profiled
def testSetUp(cls):
pass
@classmethod
@profiled
def testTearDown(cls):
pass
# We store a reference to the DB-API connect method here when we
# put a proxy in its place.
_org_connect = None
class DatabaseLayer(BaseLayer):
"""Provides tests access to the Launchpad sample database."""
# If set to False, database will not be reset between tests. It is
# your responsibility to set it back to True and call
# Database.force_dirty_database() when you do so.
_reset_between_tests = True
_is_setup = False
_db_fixture = None
@classmethod
@profiled
def setUp(cls):
cls._is_setup = True
# Read the sequences we'll need from the test template database.
reset_sequences_sql = LaunchpadTestSetup(
dbname='launchpad_ftest_template').generateResetSequencesSQL()
cls._db_fixture = LaunchpadTestSetup(
reset_sequences_sql=reset_sequences_sql)
cls.force_dirty_database()
# Nuke any existing DB (for persistent-test-services) [though they
# prevent this !?]
cls._db_fixture.tearDown()
# Force a db creation for unique db names - needed at layer init
# because appserver using layers run things at layer setup, not
# test setup.
cls._db_fixture.setUp()
# And take it 'down' again to be in the right state for testSetUp
# - note that this conflicts in principle with layers whose setUp
# needs the db working, but this is a conceptually cleaner starting
# point for addressing that mismatch.
cls._db_fixture.tearDown()
# Bring up the db, so that it is available for other layers.
cls._ensure_db()
@classmethod
@profiled
def tearDown(cls):
if not cls._is_setup:
return
cls._is_setup = False
# Don't leave the DB lying around or it might break tests
# that depend on it not being there on startup, such as found
# in test_layers.py
cls.force_dirty_database()
cls._db_fixture.tearDown()
cls._db_fixture = None
@classmethod
@profiled
def testSetUp(cls):
# The DB is already available - setUp and testTearDown both make it
# available.
if cls.use_mockdb is True:
cls.installMockDb()
@classmethod
def _ensure_db(cls):
if cls._reset_between_tests:
cls._db_fixture.setUp()
# Ensure that the database is connectable. Because we might have
# just created it, keep trying for a few seconds incase PostgreSQL
# is taking its time getting its house in order.
attempts = 60
for count in range(0, attempts):
try:
cls.connect().close()
except psycopg2.Error:
if count == attempts - 1:
raise
time.sleep(0.5)
else:
break
@classmethod
@profiled
def testTearDown(cls):
if cls.use_mockdb is True:
cls.uninstallMockDb()
# Ensure that the database is connectable
cls.connect().close()
if cls._reset_between_tests:
cls._db_fixture.tearDown()
# Fail tests that forget to uninstall their database policies.
from canonical.launchpad.webapp.adapter import StoreSelector
while StoreSelector.get_current() is not None:
BaseLayer.flagTestIsolationFailure(
"Database policy %s still installed"
% repr(StoreSelector.pop()))
# Reset/bring up the db - makes it available for either the next test,
# or a subordinate layer which builds on the db. This wastes one setup
# per db layer teardown per run, but thats tolerable.
cls._ensure_db()
use_mockdb = False
mockdb_mode = None
@classmethod
@profiled
def installMockDb(cls):
assert cls.mockdb_mode is None, 'mock db already installed'
from canonical.testing.mockdb import (
script_filename, ScriptRecorder, ScriptPlayer,
)
# We need a unique key for each test to store the mock db script.
test_key = BaseLayer.test_name
assert test_key, "Invalid test_key %r" % (test_key,)
# Determine if we are in replay or record mode and setup our
# mock db script.
filename = script_filename(test_key)
if os.path.exists(filename):
cls.mockdb_mode = 'replay'
cls.script = ScriptPlayer(test_key)
else:
cls.mockdb_mode = 'record'
cls.script = ScriptRecorder(test_key)
global _org_connect
_org_connect = psycopg2.connect
# Proxy real connections with our mockdb.
def fake_connect(*args, **kw):
return cls.script.connect(_org_connect, *args, **kw)
psycopg2.connect = fake_connect
@classmethod
@profiled
def uninstallMockDb(cls):
if cls.mockdb_mode is None:
return # Already uninstalled
# Store results if we are recording
if cls.mockdb_mode == 'record':
cls.script.store()
assert os.path.exists(cls.script.script_filename), (
"Stored results but no script on disk.")
cls.mockdb_mode = None
global _org_connect
psycopg2.connect = _org_connect
_org_connect = None
@classmethod
@profiled
def force_dirty_database(cls):
cls._db_fixture.force_dirty_database()
@classmethod
@profiled
def connect(cls):
return cls._db_fixture.connect()
@classmethod
@profiled
def _dropDb(cls):
return cls._db_fixture.dropDb()
class LibrarianLayer(DatabaseLayer):
"""Provides tests access to a Librarian instance.
Calls to the Librarian will fail unless there is also a Launchpad
database available.
"""
_reset_between_tests = True
librarian_fixture = None
@classmethod
@profiled
def setUp(cls):
if not cls._reset_between_tests:
raise LayerInvariantError(
"_reset_between_tests changed before LibrarianLayer "
"was actually used.")
cls.librarian_fixture = LibrarianServerFixture(
BaseLayer.config_fixture)
cls.librarian_fixture.setUp()
cls._check_and_reset()
# Make sure things using the appserver config know the
# correct Librarian port numbers.
cls.appserver_config_fixture.add_section(
cls.librarian_fixture.service_config)
@classmethod
@profiled
def tearDown(cls):
# Permit multiple teardowns while we sort out the layering
# responsibilities : not desirable though.
if cls.librarian_fixture is None:
return
try:
cls._check_and_reset()
finally:
librarian = cls.librarian_fixture
cls.librarian_fixture = None
try:
if not cls._reset_between_tests:
raise LayerInvariantError(
"_reset_between_tests not reset before "
"LibrarianLayer shutdown")
finally:
librarian.cleanUp()
@classmethod
@profiled
def _check_and_reset(cls):
"""Raise an exception if the Librarian has been killed.
Reset the storage unless this has been disabled.
"""
try:
f = urlopen(config.librarian.download_url)
f.read()
except Exception, e:
raise LayerIsolationError(
"Librarian has been killed or has hung."
"Tests should use LibrarianLayer.hide() and "
"LibrarianLayer.reveal() where possible, and ensure "
"the Librarian is restarted if it absolutely must be "
"shutdown: " + str(e))
if cls._reset_between_tests:
cls.librarian_fixture.clear()
@classmethod
@profiled
def testSetUp(cls):
cls._check_and_reset()
@classmethod
@profiled
def testTearDown(cls):
if cls._hidden:
cls.reveal()
cls._check_and_reset()
# Flag maintaining state of hide()/reveal() calls
_hidden = False
# Fake upload socket used when the librarian is hidden
_fake_upload_socket = None
@classmethod
@profiled
def hide(cls):
"""Hide the Librarian so nothing can find it. We don't want to
actually shut it down because starting it up again is expensive.
We do this by altering the configuration so the Librarian client
looks for the Librarian server on the wrong port.
"""
cls._hidden = True
if cls._fake_upload_socket is None:
# Bind to a socket, but don't listen to it. This way we
# guarantee that connections to the given port will fail.
cls._fake_upload_socket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
assert config.librarian.upload_host == 'localhost', (
'Can only hide librarian if it is running locally')
cls._fake_upload_socket.bind(('127.0.0.1', 0))
host, port = cls._fake_upload_socket.getsockname()
librarian_data = dedent("""
[librarian]
upload_port: %s
""" % port)
config.push('hide_librarian', librarian_data)
@classmethod
@profiled
def reveal(cls):
"""Reveal a hidden Librarian.
This just involves restoring the config to the original value.
"""
cls._hidden = False
config.pop('hide_librarian')
def test_default_timeout():
"""Don't timeout by default in tests."""
return None
class LaunchpadLayer(LibrarianLayer, MemcachedLayer, RabbitMQLayer):
"""Provides access to the Launchpad database and daemons.
We need to ensure that the database setup runs before the daemon
setup, or the database setup will fail because the daemons are
already connected to the database.
This layer is mainly used by tests that call initZopeless() themselves.
Most tests will use a sublayer such as LaunchpadFunctionalLayer that
provides access to the Component Architecture.
"""
@classmethod
@profiled
def setUp(cls):
pass
@classmethod
@profiled
def tearDown(cls):
pass
@classmethod
@profiled
def testSetUp(cls):
# By default, don't make external service tests timeout.
if get_default_timeout_function() is not None:
raise LayerIsolationError(
"Global default timeout function should be None.")
set_default_timeout_function(test_default_timeout)
@classmethod
@profiled
def testTearDown(cls):
if get_default_timeout_function() is not test_default_timeout:
raise LayerIsolationError(
"Test didn't reset default timeout function.")
set_default_timeout_function(None)
# A database connection to the session database, created by the first
# call to resetSessionDb.
_raw_sessiondb_connection = None
@classmethod
@profiled
def resetSessionDb(cls):
"""Reset the session database.
Layers that need session database isolation call this explicitly
in the testSetUp().
"""
if LaunchpadLayer._raw_sessiondb_connection is None:
from storm.uri import URI
from canonical.launchpad.webapp.adapter import (
LaunchpadSessionDatabase)
launchpad_session_database = LaunchpadSessionDatabase(
URI('launchpad-session:'))
LaunchpadLayer._raw_sessiondb_connection = (
launchpad_session_database.raw_connect())
LaunchpadLayer._raw_sessiondb_connection.cursor().execute(
"DELETE FROM SessionData")
def wsgi_application(environ, start_response):
"""This is a wsgi application for Zope functional testing.
We use it with wsgi_intercept, which is itself mostly interesting
for our webservice (lazr.restful) tests.
"""
# Committing work done up to now is a convenience that the Zope
# zope.app.testing.functional.HTTPCaller does. We're replacing that bit,
# so it is easiest to follow that lead, even if it feels a little loose.
transaction.commit()
# Let's support post-mortem debugging.
if environ.pop('HTTP_X_ZOPE_HANDLE_ERRORS', 'True') == 'False':
environ['wsgi.handleErrors'] = False
handle_errors = environ.get('wsgi.handleErrors', True)
# Make sure the request method is something Launchpad will
# recognize. httplib2 usually takes care of this, but we've
# bypassed that code in our test environment.
environ['REQUEST_METHOD'] = environ['REQUEST_METHOD'].upper()
# Now we do the proper dance to get the desired request. This is an
# almalgam of code from zope.app.testing.functional.HTTPCaller and
# zope.publisher.paste.Application.
request_cls, publication_cls = chooseClasses(
environ['REQUEST_METHOD'], environ)
publication = publication_cls(set_up_functional_test().db)
request = request_cls(environ['wsgi.input'], environ)
request.setPublication(publication)
# The rest of this function is an amalgam of
# zope.publisher.paste.Application.__call__ and van.testing.layers.
request = zope.publisher.publish.publish(
request, handle_errors=handle_errors)
response = request.response
# We sort these, and then put the status first, because
# zope.testbrowser.testing does--and because it makes it easier to write
# reliable tests.
headers = sorted(response.getHeaders())
status = response.getStatusString()
headers.insert(0, ('Status', status))
# Start the WSGI server response.
start_response(status, headers)
# Return the result body iterable.
return response.consumeBodyIter()
class FunctionalLayer(BaseLayer):
"""Loads the Zope3 component architecture in appserver mode."""
# Set to True if tests using the Functional layer are currently being run.
isSetUp = False
@classmethod
@profiled
def setUp(cls):
FunctionalLayer.isSetUp = True
set_up_functional_test().setUp()
# Assert that set_up_functional_test did what it says it does
if not is_ca_available():
raise LayerInvariantError("Component architecture failed to load")
# Access the cookie manager's secret to get the cache populated.
# If we don't, it may issue extra queries depending on test order.
canonical.launchpad.webapp.session.idmanager.secret
# If our request publication factories were defined using ZCML,
# they'd be set up by set_up_functional_test().setUp(). Since
# they're defined by Python code, we need to call that code
# here.
register_launchpad_request_publication_factories()
wsgi_intercept.add_wsgi_intercept(
'localhost', 80, lambda: wsgi_application)
wsgi_intercept.add_wsgi_intercept(
'api.launchpad.dev', 80, lambda: wsgi_application)
httplib2_intercept.install()
@classmethod
@profiled
def tearDown(cls):
FunctionalLayer.isSetUp = False
wsgi_intercept.remove_wsgi_intercept('localhost', 80)
wsgi_intercept.remove_wsgi_intercept('api.launchpad.dev', 80)
httplib2_intercept.uninstall()
# Signal Layer cannot be torn down fully
raise NotImplementedError
@classmethod
@profiled
def testSetUp(cls):
transaction.abort()
transaction.begin()
# Fake a root folder to keep Z3 ZODB dependencies happy.
fs = set_up_functional_test()
if not fs.connection:
fs.connection = fs.db.open()
root = fs.connection.root()
root[ZopePublication.root_name] = MockRootFolder()
# Should be impossible, as the CA cannot be unloaded. Something
# mighty nasty has happened if this is triggered.
if not is_ca_available():
raise LayerInvariantError(
"Component architecture not loaded or totally screwed")
@classmethod
@profiled
def testTearDown(cls):
# Should be impossible, as the CA cannot be unloaded. Something
# mighty nasty has happened if this is triggered.
if not is_ca_available():
raise LayerInvariantError(
"Component architecture not loaded or totally screwed")
transaction.abort()
class ZopelessLayer(BaseLayer):
"""Layer for tests that need the Zopeless component architecture
loaded using execute_zcml_for_scripts().
"""
# Set to True if tests in the Zopeless layer are currently being run.
isSetUp = False
@classmethod
@profiled
def setUp(cls):
ZopelessLayer.isSetUp = True
execute_zcml_for_scripts()
# Assert that execute_zcml_for_scripts did what it says it does.
if not is_ca_available():
raise LayerInvariantError(
"Component architecture not loaded by "
"execute_zcml_for_scripts")
# If our request publication factories were defined using
# ZCML, they'd be set up by execute_zcml_for_scripts(). Since
# they're defined by Python code, we need to call that code
# here.
register_launchpad_request_publication_factories()
@classmethod
@profiled
def tearDown(cls):
ZopelessLayer.isSetUp = False
# Signal Layer cannot be torn down fully
raise NotImplementedError
@classmethod
@profiled
def testSetUp(cls):
# Should be impossible, as the CA cannot be unloaded. Something
# mighty nasty has happened if this is triggered.
if not is_ca_available():
raise LayerInvariantError(
"Component architecture not loaded or totally screwed")
# This should not happen here, it should be caught by the
# testTearDown() method. If it does, something very nasty
# happened.
if getSecurityPolicy() != PermissiveSecurityPolicy:
raise LayerInvariantError(
"Previous test removed the PermissiveSecurityPolicy.")
# execute_zcml_for_scripts() sets up an interaction for the
# anonymous user. A previous script may have changed or removed
# the interaction, so set it up again
login(ANONYMOUS)
@classmethod
@profiled
def testTearDown(cls):
# Should be impossible, as the CA cannot be unloaded. Something
# mighty nasty has happened if this is triggered.
if not is_ca_available():
raise LayerInvariantError(
"Component architecture not loaded or totally screwed")
# Make sure that a test that changed the security policy, reset it
# back to its default value.
if getSecurityPolicy() != PermissiveSecurityPolicy:
raise LayerInvariantError(
"This test removed the PermissiveSecurityPolicy and didn't "
"restore it.")
logout()
class TwistedLayer(BaseLayer):
"""A layer for cleaning up the Twisted thread pool."""
@classmethod
@profiled
def setUp(cls):
pass
@classmethod
@profiled
def tearDown(cls):
pass
@classmethod
def _save_signals(cls):
"""Save the current signal handlers."""
TwistedLayer._original_sigint = signal.getsignal(signal.SIGINT)
TwistedLayer._original_sigterm = signal.getsignal(signal.SIGTERM)
TwistedLayer._original_sigchld = signal.getsignal(signal.SIGCHLD)
# XXX MichaelHudson, 2009-07-14, bug=399118: If a test case in this
# layer launches a process with spawnProcess, there should really be a
# SIGCHLD handler installed to avoid PotentialZombieWarnings. But
# some tests in this layer use tachandler and it is fragile when a
# SIGCHLD handler is installed. tachandler needs to be fixed.
# from twisted.internet import reactor
# signal.signal(signal.SIGCHLD, reactor._handleSigchld)
@classmethod
def _restore_signals(cls):
"""Restore the signal handlers."""
signal.signal(signal.SIGINT, TwistedLayer._original_sigint)
signal.signal(signal.SIGTERM, TwistedLayer._original_sigterm)
signal.signal(signal.SIGCHLD, TwistedLayer._original_sigchld)
@classmethod
@profiled
def testSetUp(cls):
TwistedLayer._save_signals()
from twisted.internet import interfaces, reactor
from twisted.python import threadpool
# zope.exception demands more of frame objects than
# twisted.python.failure provides in its fake frames. This is enough
# to make it work with them as of 2009-09-16. See
# https://bugs.launchpad.net/bugs/425113.
cls._patch = MonkeyPatch(
'twisted.python.failure._Frame.f_locals',
property(lambda self: {}))
cls._patch.setUp()
if interfaces.IReactorThreads.providedBy(reactor):
pool = getattr(reactor, 'threadpool', None)
# If the Twisted threadpool has been obliterated (probably by
# testTearDown), then re-build it using the values that Twisted
# uses.
if pool is None:
reactor.threadpool = threadpool.ThreadPool(0, 10)
reactor.threadpool.start()
@classmethod
@profiled
def testTearDown(cls):
# Shutdown and obliterate the Twisted threadpool, to plug up leaking
# threads.
from twisted.internet import interfaces, reactor
if interfaces.IReactorThreads.providedBy(reactor):
reactor.suggestThreadPoolSize(0)
pool = getattr(reactor, 'threadpool', None)
if pool is not None:
reactor.threadpool.stop()
reactor.threadpool = None
cls._patch.cleanUp()
TwistedLayer._restore_signals()
class GoogleServiceLayer(BaseLayer):
"""Tests for Google web service integration."""
@classmethod
def setUp(cls):
google = GoogleServiceTestSetup()
google.setUp()
@classmethod
def tearDown(cls):
GoogleServiceTestSetup().tearDown()
@classmethod
def testSetUp(self):
# We need to override BaseLayer.testSetUp(), or else we will
# get a LayerIsolationError.
pass
@classmethod
def testTearDown(self):
# We need to override BaseLayer.testTearDown(), or else we will
# get a LayerIsolationError.
pass
class DatabaseFunctionalLayer(DatabaseLayer, FunctionalLayer):
"""Provides the database and the Zope3 application server environment."""
@classmethod
@profiled
def setUp(cls):
pass
@classmethod
@profiled
def tearDown(cls):
pass
@classmethod
@profiled
def testSetUp(cls):
# Connect Storm
reconnect_stores()
@classmethod
@profiled
def testTearDown(cls):
getUtility(IOpenLaunchBag).clear()
# If tests forget to logout, we can do it for them.
if is_logged_in():
logout()
# Disconnect Storm so it doesn't get in the way of database resets
disconnect_stores()
class LaunchpadFunctionalLayer(LaunchpadLayer, FunctionalLayer):
"""Provides the Launchpad Zope3 application server environment."""
@classmethod
@profiled
def setUp(cls):
pass
@classmethod
@profiled
def testSetUp(cls):
# Reset any statistics
from canonical.launchpad.webapp.opstats import OpStats
OpStats.resetStats()
# Connect Storm
reconnect_stores()
@classmethod
@profiled
def testTearDown(cls):
getUtility(IOpenLaunchBag).clear()
# If tests forget to logout, we can do it for them.
if is_logged_in():
logout()
# Reset any statistics
from canonical.launchpad.webapp.opstats import OpStats
OpStats.resetStats()
# Disconnect Storm so it doesn't get in the way of database resets
disconnect_stores()
class GoogleLaunchpadFunctionalLayer(LaunchpadFunctionalLayer,
GoogleServiceLayer):
"""Provides Google service in addition to LaunchpadFunctionalLayer."""
@classmethod
@profiled
def setUp(cls):
pass
@classmethod
@profiled
def tearDown(cls):
pass
@classmethod
@profiled
def testSetUp(cls):
pass
@classmethod
@profiled
def testTearDown(cls):
pass
class ZopelessDatabaseLayer(ZopelessLayer, DatabaseLayer):
"""Testing layer for unit tests with no need for librarian.
Can be used wherever you're accustomed to using LaunchpadZopeless
or LaunchpadScript layers, but there is no need for librarian.
"""
@classmethod
@profiled
def setUp(cls):
pass
@classmethod
@profiled
def tearDown(cls):
# Signal Layer cannot be torn down fully
raise NotImplementedError
@classmethod
@profiled
def testSetUp(cls):
# LaunchpadZopelessLayer takes care of reconnecting the stores
if not LaunchpadZopelessLayer.isSetUp:
reconnect_stores()
@classmethod
@profiled
def testTearDown(cls):
disconnect_stores()
@classmethod
@profiled
def switchDbConfig(cls, database_config_section):
reconnect_stores(database_config_section=database_config_section)
class LaunchpadScriptLayer(ZopelessLayer, LaunchpadLayer):
"""Testing layer for scripts using the main Launchpad database adapter"""
@classmethod
@profiled
def setUp(cls):
# Make a TestMailBox available
# This is registered via ZCML in the LaunchpadFunctionalLayer
# XXX flacoste 2006-10-25 bug=68189: This should be configured from
# ZCML but execute_zcml_for_scripts() doesn't cannot support a
# different testing configuration.
cls._mailbox = TestMailBox()
provideUtility(cls._mailbox, IMailBox)
@classmethod
@profiled
def tearDown(cls):
if not globalregistry.base.unregisterUtility(cls._mailbox):
raise NotImplementedError('failed to unregister mailbox')
@classmethod
@profiled
def testSetUp(cls):
# LaunchpadZopelessLayer takes care of reconnecting the stores
if not LaunchpadZopelessLayer.isSetUp:
reconnect_stores()
@classmethod
@profiled
def testTearDown(cls):
disconnect_stores()
@classmethod
@profiled
def switchDbConfig(cls, database_config_section):
reconnect_stores(database_config_section=database_config_section)
class LaunchpadTestSetup(PgTestSetup):
template = 'launchpad_ftest_template'
dbuser = 'launchpad'
class LaunchpadZopelessLayer(LaunchpadScriptLayer):
"""Full Zopeless environment including Component Architecture and
database connections initialized.
"""
isSetUp = False
txn = ZopelessTransactionManager
@classmethod
@profiled
def setUp(cls):
LaunchpadZopelessLayer.isSetUp = True
@classmethod
@profiled
def tearDown(cls):
LaunchpadZopelessLayer.isSetUp = False
@classmethod
@profiled
def testSetUp(cls):
if ZopelessTransactionManager._installed is not None:
raise LayerIsolationError(
"Last test using Zopeless failed to tearDown correctly")
initZopeless()
# Connect Storm
reconnect_stores()
@classmethod
@profiled
def testTearDown(cls):
ZopelessTransactionManager.uninstall()
if ZopelessTransactionManager._installed is not None:
raise LayerInvariantError(
"Failed to uninstall ZopelessTransactionManager")
# LaunchpadScriptLayer will disconnect the stores for us.
@classmethod
@profiled
def commit(cls):
transaction.commit()
@classmethod
@profiled
def abort(cls):
transaction.abort()
@classmethod
@profiled
def switchDbUser(cls, dbuser):
LaunchpadZopelessLayer.alterConnection(dbuser=dbuser)
@classmethod
@profiled
def alterConnection(cls, **kw):
"""Reset the connection, and reopen the connection by calling
initZopeless with the given keyword arguments.
"""
ZopelessTransactionManager.uninstall()
initZopeless(**kw)
class ExperimentalLaunchpadZopelessLayer(LaunchpadZopelessLayer):
"""LaunchpadZopelessLayer using the mock database."""
@classmethod
def setUp(cls):
DatabaseLayer.use_mockdb = True
@classmethod
def tearDown(cls):
DatabaseLayer.use_mockdb = False
@classmethod
def testSetUp(cls):
pass
@classmethod
def testTearDown(cls):
pass
class MockHTTPTask:
class MockHTTPRequestParser:
headers = None
first_line = None
class MockHTTPServerChannel:
# This is not important to us, so we can hardcode it here.
addr = ['127.0.0.88', 80]
request_data = MockHTTPRequestParser()
channel = MockHTTPServerChannel()
def __init__(self, response, first_line):
self.request = response._request
# We have no way of knowing when the task started, so we use
# the current time here. That shouldn't be a problem since we don't
# care about that for our tests anyway.
self.start_time = time.time()
self.status = response.getStatus()
# When streaming files (see lib/zope/publisher/httpresults.txt)
# the 'Content-Length' header is missing. When it happens we set
# 'bytes_written' to an obviously invalid value. This variable is
# used for logging purposes, see webapp/servers.py.
content_length = response.getHeader('Content-Length')
if content_length is not None:
self.bytes_written = int(content_length)
else:
self.bytes_written = -1
self.request_data.headers = self.request.headers
self.request_data.first_line = first_line
def getCGIEnvironment(self):
return self.request._orig_env
class PageTestLayer(LaunchpadFunctionalLayer, GoogleServiceLayer):
"""Environment for page tests.
"""
@classmethod
@profiled
def resetBetweenTests(cls, flag):
LibrarianLayer._reset_between_tests = flag
DatabaseLayer._reset_between_tests = flag
MemcachedLayer._reset_between_tests = flag
@classmethod
@profiled
def setUp(cls):
if os.environ.get('PROFILE_PAGETESTS_REQUESTS'):
PageTestLayer.profiler = Profile()
else:
PageTestLayer.profiler = None
file_handler = logging.FileHandler('logs/pagetests-access.log', 'w')
file_handler.setFormatter(logging.Formatter())
logger = PythonLogger('pagetests-access')
logger.logger.addHandler(file_handler)
logger.logger.setLevel(logging.INFO)
access_logger = LaunchpadAccessLogger(logger)
def my__call__(obj, request_string, handle_errors=True, form=None):
"""Call HTTPCaller.__call__ and log the page hit."""
if PageTestLayer.profiler:
response = PageTestLayer.profiler.runcall(
orig__call__, obj, request_string,
handle_errors=handle_errors, form=form)
else:
response = orig__call__(
obj, request_string, handle_errors=handle_errors,
form=form)
first_line = request_string.strip().splitlines()[0]
access_logger.log(MockHTTPTask(response._response, first_line))
return response
PageTestLayer.orig__call__ = (
zope.app.testing.functional.HTTPCaller.__call__)
zope.app.testing.functional.HTTPCaller.__call__ = my__call__
PageTestLayer.resetBetweenTests(True)
@classmethod
@profiled
def tearDown(cls):
PageTestLayer.resetBetweenTests(True)
zope.app.testing.functional.HTTPCaller.__call__ = (
PageTestLayer.orig__call__)
if PageTestLayer.profiler:
PageTestLayer.profiler.dump_stats(
os.environ.get('PROFILE_PAGETESTS_REQUESTS'))
@classmethod
@profiled
def startStory(cls):
MemcachedLayer.testSetUp()
DatabaseLayer.testSetUp()
LibrarianLayer.testSetUp()
LaunchpadLayer.resetSessionDb()
PageTestLayer.resetBetweenTests(False)
@classmethod
@profiled
def endStory(cls):
PageTestLayer.resetBetweenTests(True)
LibrarianLayer.testTearDown()
DatabaseLayer.testTearDown()
MemcachedLayer.testTearDown()
@classmethod
@profiled
def testSetUp(cls):
pass
@classmethod
@profiled
def testTearDown(cls):
pass
class TwistedLaunchpadZopelessLayer(TwistedLayer, LaunchpadZopelessLayer):
"""A layer for cleaning up the Twisted thread pool."""
@classmethod
@profiled
def setUp(cls):
pass
@classmethod
@profiled
def tearDown(cls):
pass
@classmethod
@profiled
def testSetUp(cls):
pass
@classmethod
@profiled
def testTearDown(cls):
# XXX 2008-06-11 jamesh bug=239086:
# Due to bugs in the transaction module's thread local
# storage, transactions may be reused by new threads in future
# tests. Therefore we do some cleanup before the pool is
# destroyed by TwistedLayer.testTearDown().
from twisted.internet import interfaces, reactor
if interfaces.IReactorThreads.providedBy(reactor):
pool = getattr(reactor, 'threadpool', None)
if pool is not None and pool.workers > 0:
def cleanup_thread_stores(event):
disconnect_stores()
# Don't exit until the event fires. This ensures
# that our thread doesn't get added to
# pool.waiters until all threads are processed.
event.wait()
event = threading.Event()
# Ensure that the pool doesn't grow, and issue one
# cleanup job for each thread in the pool.
pool.adjustPoolsize(0, pool.workers)
for i in range(pool.workers):
pool.callInThread(cleanup_thread_stores, event)
event.set()
class LayerProcessController:
"""Controller for starting and stopping subprocesses.
Layers which need to start and stop a child process appserver or smtp
server should call the methods in this class, but should NOT inherit from
this class.
"""
# Holds the Popen instance of the spawned app server.
appserver = None
# The config used by the spawned app server.
appserver_config = None
# The SMTP server for layer tests. See
# configs/testrunner-appserver/mail-configure.zcml
smtp_controller = None
@classmethod
def _setConfig(cls):
"""Stash a config for use."""
cls.appserver_config = CanonicalConfig(
BaseLayer.appserver_config_name, 'runlaunchpad')
@classmethod
def setUp(cls):
cls._setConfig()
cls.startSMTPServer()
cls.startAppServer()
@classmethod
@profiled
def startSMTPServer(cls):
"""Start the SMTP server if it hasn't already been started."""
if cls.smtp_controller is not None:
raise LayerInvariantError('SMTP server already running')
# Ensure that the SMTP server does proper logging.
log = logging.getLogger('lazr.smtptest')
log_file = os.path.join(config.mailman.build_var_dir, 'logs', 'smtpd')
handler = logging.FileHandler(log_file)
formatter = logging.Formatter(
fmt='%(asctime)s (%(process)d) %(message)s',
datefmt='%b %d %H:%M:%S %Y')
handler.setFormatter(formatter)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
log.propagate = False
cls.smtp_controller = SMTPController('localhost', 9025)
cls.smtp_controller.start()
@classmethod
@profiled
def startAppServer(cls):
"""Start the app server if it hasn't already been started."""
if cls.appserver is not None:
raise LayerInvariantError('App server already running')
cls._cleanUpStaleAppServer()
cls._runAppServer()
cls._waitUntilAppServerIsReady()
@classmethod
@profiled
def stopSMTPServer(cls):
"""Kill the SMTP server and wait until it's exited."""
if cls.smtp_controller is not None:
cls.smtp_controller.reset()
cls.smtp_controller.stop()
cls.smtp_controller = None
@classmethod
def _kill(cls, sig):
"""Kill the appserver with `sig`.
:param sig: the signal to kill with
:type sig: int
:return: True if the signal was delivered, otherwise False.
:rtype: bool
"""
try:
os.kill(cls.appserver.pid, sig)
except OSError, error:
if error.errno == errno.ESRCH:
# The child process doesn't exist. Maybe it went away by the
# time we got here.
cls.appserver = None
return False
else:
# Something else went wrong.
raise
else:
return True
@classmethod
@profiled
def stopAppServer(cls):
"""Kill the appserver and wait until it's exited."""
if cls.appserver is not None:
# Unfortunately, Popen.wait() does not support a timeout, so poll
# for a little while, then SIGKILL the process if it refuses to
# exit. test_on_merge.py will barf if we hang here for too long.
until = datetime.datetime.now() + WAIT_INTERVAL
last_chance = False
if not cls._kill(signal.SIGTERM):
# The process is already gone.
return
while True:
# Sleep and poll for process exit.
if cls.appserver.poll() is not None:
break
time.sleep(0.5)
# If we slept long enough, send a harder kill and wait again.
# If we already had our last chance, raise an exception.
if datetime.datetime.now() > until:
if last_chance:
raise RuntimeError("The appserver just wouldn't die")
last_chance = True
if not cls._kill(signal.SIGKILL):
# The process is already gone.
return
until = datetime.datetime.now() + WAIT_INTERVAL
cls.appserver = None
@classmethod
@profiled
def postTestInvariants(cls):
"""Enforce some invariants after each test.
Must be called in your layer class's `testTearDown()`.
"""
if cls.appserver.poll() is not None:
raise LayerIsolationError(
"App server died in this test (status=%s):\n%s" % (
cls.appserver.returncode, cls.appserver.stdout.read()))
DatabaseLayer.force_dirty_database()
@classmethod
def _cleanUpStaleAppServer(cls):
"""Kill any stale app server or pid file."""
pid = pidfile.get_pid('launchpad', cls.appserver_config)
if pid is not None:
# Don't worry if the process no longer exists.
try:
os.kill(pid, signal.SIGTERM)
except OSError, error:
if error.errno != errno.ESRCH:
raise
pidfile.remove_pidfile('launchpad', cls.appserver_config)
@classmethod
def _runAppServer(cls):
"""Start the app server using runlaunchpad.py"""
# The app server will not start at all if the database hasn't been
# correctly patched. The app server will make exactly this check,
# doing it here makes the error more obvious.
confirm_dbrevision_on_startup()
_config = cls.appserver_config
cmd = [
os.path.join(_config.root, 'bin', 'run'),
'-C', 'configs/%s/launchpad.conf' % _config.instance_name]
environ = dict(os.environ)
environ['LPCONFIG'] = _config.instance_name
cls.appserver = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
env=environ, cwd=_config.root)
@classmethod
def _waitUntilAppServerIsReady(cls):
"""Wait until the app server accepts connection."""
assert cls.appserver is not None, "App server isn't started."
root_url = cls.appserver_config.vhost.mainsite.rooturl
until = datetime.datetime.now() + WAIT_INTERVAL
while until > datetime.datetime.now():
try:
connection = urlopen(root_url)
connection.read()
except IOError, error:
# We are interested in a wrapped socket.error.
# urlopen() really sucks here.
if len(error.args) <= 1:
raise
if not isinstance(error.args[1], socket.error):
raise
if error.args[1].args[0] != errno.ECONNREFUSED:
raise
returncode = cls.appserver.poll()
if returncode is not None:
raise RuntimeError(
'App server failed to start (status=%d):\n%s' % (
returncode, cls.appserver.stdout.read()))
time.sleep(0.5)
else:
connection.close()
break
else:
os.kill(cls.appserver.pid, signal.SIGTERM)
cls.appserver = None
# Go no further.
raise AssertionError('App server startup timed out.')
class AppServerLayer(LaunchpadFunctionalLayer):
"""Layer for tests that run in the webapp environment with an app server.
"""
@classmethod
@profiled
def setUp(cls):
LayerProcessController.setUp()
@classmethod
@profiled
def tearDown(cls):
LayerProcessController.stopAppServer()
LayerProcessController.stopSMTPServer()
@classmethod
@profiled
def testSetUp(cls):
LaunchpadLayer.resetSessionDb()
@classmethod
@profiled
def testTearDown(cls):
LayerProcessController.postTestInvariants()
class ZopelessAppServerLayer(LaunchpadZopelessLayer):
"""Layer for tests that run in the zopeless environment with an appserver.
"""
@classmethod
@profiled
def setUp(cls):
LayerProcessController.setUp()
@classmethod
@profiled
def tearDown(cls):
LayerProcessController.stopAppServer()
LayerProcessController.stopSMTPServer()
@classmethod
@profiled
def testSetUp(cls):
LaunchpadLayer.resetSessionDb()
@classmethod
@profiled
def testTearDown(cls):
LayerProcessController.postTestInvariants()
class TwistedAppServerLayer(TwistedLaunchpadZopelessLayer):
"""Layer for twisted-using zopeless tests that need a running app server.
"""
@classmethod
@profiled
def setUp(cls):
LayerProcessController.setUp()
@classmethod
@profiled
def tearDown(cls):
LayerProcessController.stopAppServer()
LayerProcessController.stopSMTPServer()
@classmethod
@profiled
def testSetUp(cls):
LaunchpadLayer.resetSessionDb()
@classmethod
@profiled
def testTearDown(cls):
LayerProcessController.postTestInvariants()
class BaseWindmillLayer(AppServerLayer):
"""Layer for Windmill tests.
This layer shouldn't be used directly. A subclass needs to be
created specifying which base URL to use (e.g.
http://bugs.launchpad.dev:8085/).
"""
facet = None
base_url = None
shell_objects = None
config_file = None
@classmethod
@profiled
def setUp(cls):
if cls.base_url is None:
# Only do the setup if we're in a subclass that defines
# base_url. With no base_url, we can't create the config
# file windmill needs.
return
cls._fixStandardInputFileno()
cls._configureWindmillLogging()
cls._configureWindmillStartup()
# Tell windmill to start its browser and server. Our testrunner will
# keep going, passing commands to the server for execution.
cls.shell_objects = start_windmill()
# Patch the config to provide the port number and not use https.
sites = (
(('vhost.%s' % sitename,
'rooturl: %s/' % cls.appserver_root_url(sitename))
for sitename in ['mainsite', 'answers', 'blueprints', 'bugs',
'code', 'testopenid', 'translations']))
for site in sites:
config.push('windmillsettings', "\n[%s]\n%s\n" % site)
allvhosts.reload()
@classmethod
@profiled
def tearDown(cls):
if cls.shell_objects is not None:
windmill_teardown(cls.shell_objects)
if cls.config_file is not None:
# Close the file so that it gets deleted.
cls.config_file.close()
config.reloadConfig()
reset_logging()
# XXX: deryck 2011-01-28 bug=709438
# Windmill mucks about with the default timeout and this is
# a fix until the library itself can be cleaned up.
socket.setdefaulttimeout(None)
@classmethod
@profiled
def testSetUp(cls):
# Left-over threads should be harmless, since they should all
# belong to Windmill, which will be cleaned up on layer
# tear down.
BaseLayer.disable_thread_check = True
socket.setdefaulttimeout(120)
@classmethod
@profiled
def testTearDown(cls):
# To play nice with Windmill layers, we need to reset
# the socket timeout default in this method, too.
socket.setdefaulttimeout(None)
@classmethod
def _fixStandardInputFileno(cls):
"""Patch the STDIN fileno so Windmill doesn't break."""
# If we're running in a bin/test sub-process, sys.stdin is
# replaced by FakeInputContinueGenerator, which doesn't have a
# fileno method. When Windmill starts Firefox,
# sys.stdin.fileno() is called, so we add such a method here, to
# prevent it from breaking. By returning None, we should ensure
# that it doesn't try to use the return value for anything.
if not safe_hasattr(sys.stdin, 'fileno'):
assert isinstance(sys.stdin, FakeInputContinueGenerator), (
"sys.stdin (%r) doesn't have a fileno method." % sys.stdin)
sys.stdin.fileno = lambda: None
@classmethod
def _configureWindmillLogging(cls):
"""Override the default windmill log handling."""
if not config.windmill.debug_log:
return
# Add a new log handler to capture all of the windmill testrunner
# output. This overrides windmill's own log handling, which we do not
# have direct access to.
# We'll overwrite the previous log contents to keep the disk usage
# low, and because the contents are only meant as an in-situ debugging
# aid.
filehandler = logging.FileHandler(config.windmill.debug_log, mode='w')
filehandler.setLevel(logging.NOTSET)
filehandler.setFormatter(
logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
logging.getLogger('windmill').addHandler(filehandler)
# Make sure that everything sent to the windmill logger is captured.
# This works because windmill configures the root logger for its
# purposes, and we are pre-empting that by inserting a new logger one
# level higher in the logger chain.
logging.getLogger('windmill').setLevel(logging.NOTSET)
@classmethod
def _configureWindmillStartup(cls):
"""Pass our startup parameters to the windmill server."""
# Windmill needs a config file on disk to load its settings from.
# There is no way to directly pass settings to the windmill test
# driver from out here.
config_text = dedent("""\
START_FIREFOX = True
TEST_URL = '%s/'
CONSOLE_LOG_LEVEL = %d
""" % (cls.base_url, logging.NOTSET))
cls.config_file = tempfile.NamedTemporaryFile(suffix='.py')
cls.config_file.write(config_text)
# Flush the file so that windmill can read it.
cls.config_file.flush()
os.environ['WINDMILL_CONFIG_FILE'] = cls.config_file.name
class YUITestLayer(FunctionalLayer):
"""The base class for all YUITests cases."""
|