~launchpad-pqm/launchpad/devel

14027.3.2 by Jeroen Vermeulen
Merge devel, resolve conflicts.
1
# Copyright 2009-2011 Canonical Ltd.  This software is licensed under the
8687.15.18 by Karl Fogel
Add the copyright header block to files under lib/canonical/.
2
# GNU Affero General Public License version 3 (see the file LICENSE).
3
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
4
from __future__ import with_statement
5
3691.57.38 by Stuart Bishop
Add Layer tests
6
""" Test layers
7
8
Note that many tests are performed at run time in the layers themselves
9
to confirm that the environment hasn't been corrupted by tests
10
"""
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
11
3691.57.38 by Stuart Bishop
Add Layer tests
12
__metaclass__ = type
13
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
14
from contextlib import nested
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
15
from cStringIO import StringIO
6697.3.2 by Francis J. Lacoste
Refactored AppServerLayer to only start up the web app server using runlaunchpad.py.
16
import os
17
import signal
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
18
import smtplib
3691.57.42 by Stuart Bishop
More post review feedback updates
19
from urllib import urlopen
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
20
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
21
from amqplib import client_0_8 as amqp
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
22
from fixtures import (
13023.9.10 by Gavin Panella
Format imports.
23
    EnvironmentVariableFixture,
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
24
    Fixture,
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
25
    TestWithFixtures,
26
    )
13023.9.10 by Gavin Panella
Format imports.
27
from lazr.config import as_host_port
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
28
import testtools
13023.9.10 by Gavin Panella
Format imports.
29
from zope.component import (
30
    ComponentLookupError,
31
    getUtility,
32
    )
3691.57.38 by Stuart Bishop
Add Layer tests
33
14605.1.1 by Curtis Hovey
Moved canonical.config to lp.services.
34
from lp.services.config import config
14606.2.2 by William Grant
Move canonical.librarian.{client,utils} to lp.services.librarian.
35
from lp.services.librarian.client import (
13023.9.10 by Gavin Panella
Format imports.
36
    LibrarianClient,
37
    UploadFailed,
38
    )
14606.2.8 by William Grant
format-imports
39
from lp.services.librarian.interfaces.client import ILibrarianClient
14606.2.2 by William Grant
Move canonical.librarian.{client,utils} to lp.services.librarian.
40
from lp.services.memcache.client import memcache_client_factory
14606.4.14 by William Grant
More stuff.
41
from lp.services.pidfile import pidfile_path
14604.1.1 by Curtis Hovey
Separate test-authoring classes from test-running classes.
42
from lp.testing.layers import (
11728.2.5 by Robert Collins
Update last user of LaunchpadFunctionalTestSetup and discard it. Move the now movable LaunchpadTestSetup to Layers.
43
    AppServerLayer,
44
    BaseLayer,
45
    DatabaseLayer,
46
    FunctionalLayer,
47
    LaunchpadFunctionalLayer,
48
    LaunchpadLayer,
49
    LaunchpadScriptLayer,
50
    LaunchpadTestSetup,
51
    LaunchpadZopelessLayer,
52
    LayerInvariantError,
53
    LayerIsolationError,
54
    LayerProcessController,
55
    LibrarianLayer,
56
    MemcachedLayer,
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
57
    RabbitMQLayer,
11728.2.5 by Robert Collins
Update last user of LaunchpadFunctionalTestSetup and discard it. Move the now movable LaunchpadTestSetup to Layers.
58
    ZopelessLayer,
59
    )
3691.57.38 by Stuart Bishop
Add Layer tests
60
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
61
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
62
class BaseLayerIsolator(Fixture):
63
    """A fixture for isolating BaseLayer.
3691.57.66 by Stuart Bishop
Fix BaseLayer tests
64
13023.9.6 by Gavin Panella
Fix lint.
65
    This is useful to test interactions with LP_PERSISTENT_TEST_SERVICES
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
66
    which makes tests within layers unable to test that easily.
67
    """
68
69
    def __init__(self, with_persistent=False):
70
        """Create a BaseLayerIsolator.
71
72
        :param with_persistent: If True LP_PERSISTENT_TEST_SERVICES will
73
            be enabled during setUp.
74
        """
75
        super(BaseLayerIsolator, self).__init__()
76
        self.with_persistent = with_persistent
77
78
    def setUp(self):
79
        super(BaseLayerIsolator, self).setUp()
80
        if self.with_persistent:
81
            env_value = ''
82
        else:
83
            env_value = None
11737.4.7 by Robert Collins
Clarity.
84
        self.useFixture(EnvironmentVariableFixture(
85
            'LP_PERSISTENT_TEST_SERVICES', env_value))
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
86
        self.useFixture(EnvironmentVariableFixture('LP_TEST_INSTANCE'))
87
88
89
class LayerFixture(Fixture):
90
    """Adapt a layer to a fixture.
91
92
    Note that the layer setup/teardown are called, not the base class ones.
93
94
    :ivar layer: The adapted layer.
95
    """
96
97
    def __init__(self, layer):
98
        """Create a LayerFixture.
99
100
        :param layer: The layer to use.
101
        """
102
        super(LayerFixture, self).__init__()
103
        self.layer = layer
104
105
    def setUp(self):
106
        super(LayerFixture, self).setUp()
107
        self.layer.setUp()
108
        self.addCleanup(self.layer.tearDown)
109
110
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
111
class TestBaseLayer(testtools.TestCase, TestWithFixtures):
112
113
    def test_allocates_LP_TEST_INSTANCE(self):
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
114
        self.useFixture(BaseLayerIsolator())
115
        with LayerFixture(BaseLayer):
116
            self.assertEqual(
117
                str(os.getpid()),
118
                os.environ.get('LP_TEST_INSTANCE'))
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
119
        self.assertEqual(None, os.environ.get('LP_TEST_INSTANCE'))
120
121
    def test_persist_test_services_disables_LP_TEST_INSTANCE(self):
3691.57.66 by Stuart Bishop
Fix BaseLayer tests
122
        self.useFixture(BaseLayerIsolator(with_persistent=True))
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
123
        with LayerFixture(BaseLayer):
11728.3.2 by Robert Collins
Create unique configs in the test runner.
124
            self.assertEqual(None, os.environ.get('LP_TEST_INSTANCE'))
125
        self.assertEqual(None, os.environ.get('LP_TEST_INSTANCE'))
126
127
    def test_generates_unique_config(self):
128
        config.setInstance('testrunner')
129
        orig_instance = config.instance_name
130
        self.useFixture(
131
            EnvironmentVariableFixture('LP_PERSISTENT_TEST_SERVICES'))
132
        self.useFixture(EnvironmentVariableFixture('LP_TEST_INSTANCE'))
133
        self.useFixture(EnvironmentVariableFixture('LPCONFIG'))
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
134
        with LayerFixture(BaseLayer):
11728.3.2 by Robert Collins
Create unique configs in the test runner.
135
            self.assertEqual(
136
                'testrunner_%s' % os.environ['LP_TEST_INSTANCE'],
137
                config.instance_name)
138
        self.assertEqual(orig_instance, config.instance_name)
139
140
    def test_generates_unique_config_dirs(self):
141
        self.useFixture(
142
            EnvironmentVariableFixture('LP_PERSISTENT_TEST_SERVICES'))
143
        self.useFixture(EnvironmentVariableFixture('LP_TEST_INSTANCE'))
144
        self.useFixture(EnvironmentVariableFixture('LPCONFIG'))
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
145
        with LayerFixture(BaseLayer):
11728.3.2 by Robert Collins
Create unique configs in the test runner.
146
            runner_root = 'configs/%s' % config.instance_name
147
            runner_appserver_root = 'configs/testrunner-appserver_%s' % \
148
                os.environ['LP_TEST_INSTANCE']
149
            self.assertTrue(os.path.isfile(
150
                runner_root + '/launchpad-lazr.conf'))
151
            self.assertTrue(os.path.isfile(
152
                runner_appserver_root + '/launchpad-lazr.conf'))
153
        self.assertFalse(os.path.exists(runner_root))
154
        self.assertFalse(os.path.exists(runner_appserver_root))
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
155
156
157
class BaseTestCase(testtools.TestCase):
3691.57.42 by Stuart Bishop
More post review feedback updates
158
    """Both the Base layer tests, as well as the base Test Case
159
    for all the other Layer tests.
160
    """
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
161
    layer = BaseLayer
3691.57.38 by Stuart Bishop
Add Layer tests
162
3691.57.42 by Stuart Bishop
More post review feedback updates
163
    # These flags will be overridden in subclasses to describe the
164
    # environment they expect to have available.
3691.57.38 by Stuart Bishop
Add Layer tests
165
    want_component_architecture = False
166
    want_librarian_running = False
167
    want_launchpad_database = False
3691.57.39 by Stuart Bishop
More Layer tests
168
    want_functional_flag = False
3691.57.42 by Stuart Bishop
More post review feedback updates
169
    want_zopeless_flag = False
9232.2.7 by Stuart Bishop
memcached test layer
170
    want_memcached = False
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
171
    want_rabbitmq = False
3691.57.38 by Stuart Bishop
Add Layer tests
172
173
    def testBaseIsSetUpFlag(self):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
174
        self.failUnlessEqual(BaseLayer.isSetUp, True)
3691.57.38 by Stuart Bishop
Add Layer tests
175
3691.57.39 by Stuart Bishop
More Layer tests
176
    def testFunctionalIsSetUp(self):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
177
        self.failUnlessEqual(
178
                FunctionalLayer.isSetUp, self.want_functional_flag
179
                )
3691.57.39 by Stuart Bishop
More Layer tests
180
3691.57.42 by Stuart Bishop
More post review feedback updates
181
    def testZopelessIsSetUp(self):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
182
        self.failUnlessEqual(
183
                ZopelessLayer.isSetUp, self.want_zopeless_flag
184
                )
3691.57.39 by Stuart Bishop
More Layer tests
185
3691.57.38 by Stuart Bishop
Add Layer tests
186
    def testComponentArchitecture(self):
187
        try:
188
            getUtility(ILibrarianClient)
189
        except ComponentLookupError:
190
            self.failIf(
191
                    self.want_component_architecture,
192
                    'Component Architecture should be available.'
193
                    )
3691.57.42 by Stuart Bishop
More post review feedback updates
194
        else:
195
            self.failUnless(
196
                    self.want_component_architecture,
197
                    'Component Architecture should not be available.'
198
                    )
3691.57.38 by Stuart Bishop
Add Layer tests
199
200
    def testLibrarianRunning(self):
3691.57.42 by Stuart Bishop
More post review feedback updates
201
        # Check that the librarian is running. Note that even if the
202
        # librarian is running, it may not be able to actually store
203
        # or retrieve files if, for example, the Launchpad database is
204
        # not currently available.
3691.57.38 by Stuart Bishop
Add Layer tests
205
        try:
206
            urlopen(config.librarian.download_url).read()
207
            self.failUnless(
208
                    self.want_librarian_running,
209
                    'Librarian should not be running.'
210
                    )
211
        except IOError:
212
            self.failIf(
213
                    self.want_librarian_running,
214
                    'Librarian should be running.'
215
                    )
216
3691.57.42 by Stuart Bishop
More post review feedback updates
217
    def testLibrarianWorking(self):
218
        # Check that the librian is actually working. This means at
219
        # a minimum the Librarian service is running and is connected
220
        # to the Launchpad database.
221
        want_librarian_working = (
222
                self.want_librarian_running and self.want_launchpad_database
223
                and self.want_component_architecture
224
                )
225
        client = LibrarianClient()
226
        data = 'Whatever'
227
        try:
13023.9.6 by Gavin Panella
Fix lint.
228
            client.addFile(
3691.57.42 by Stuart Bishop
More post review feedback updates
229
                    'foo.txt', len(data), StringIO(data), 'text/plain'
230
                    )
231
        except UploadFailed:
232
            self.failIf(
233
                    want_librarian_working,
234
                    'Librarian should be fully operational'
235
                    )
5821.4.22 by James Henstridge
fix the canonical.testing tests
236
        except (AttributeError, ComponentLookupError):
3691.57.42 by Stuart Bishop
More post review feedback updates
237
            self.failIf(
238
                    want_librarian_working,
239
                    'Librarian not operational as component architecture '
240
                    'not loaded'
241
                    )
242
        else:
243
            self.failUnless(
244
                    want_librarian_working,
245
                    'Librarian should not be operational'
246
                    )
247
3691.57.38 by Stuart Bishop
Add Layer tests
248
    def testLaunchpadDbAvailable(self):
11728.2.13 by Robert Collins
Trivial test case fallout.
249
        if not self.want_launchpad_database:
250
            self.assertEqual(None, DatabaseLayer._db_fixture)
251
            return
252
        con = DatabaseLayer.connect()
253
        cur = con.cursor()
254
        cur.execute("SELECT id FROM Person LIMIT 1")
255
        self.assertNotEqual(None, cur.fetchone())
3691.57.38 by Stuart Bishop
Add Layer tests
256
9232.2.7 by Stuart Bishop
memcached test layer
257
    def testMemcachedWorking(self):
258
        client = MemcachedLayer.client or memcache_client_factory()
259
        key = "BaseTestCase.testMemcachedWorking"
260
        client.forget_dead_hosts()
261
        is_live = client.set(key, "live")
262
        if self.want_memcached:
263
            self.assertEqual(
264
                is_live, True, "memcached not live when it should be.")
265
        else:
266
            self.assertEqual(
267
                is_live, False, "memcached is live but should not be.")
268
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
269
    def testRabbitWorking(self):
270
        rabbitmq = config.rabbitmq
271
        if not self.want_rabbitmq:
272
            self.assertEqual(None, rabbitmq.host)
273
        else:
274
            self.assertNotEqual(None, rabbitmq.host)
13023.9.6 by Gavin Panella
Fix lint.
275
            conn = amqp.Connection(
276
                host=rabbitmq.host,
277
                userid=rabbitmq.userid,
278
                password=rabbitmq.password,
279
                virtual_host=rabbitmq.virtual_host,
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
280
                insist=False)
281
            conn.close()
282
9232.2.7 by Stuart Bishop
memcached test layer
283
284
class MemcachedTestCase(BaseTestCase):
285
    layer = MemcachedLayer
286
    want_memcached = True
287
3691.57.38 by Stuart Bishop
Add Layer tests
288
289
class LibrarianTestCase(BaseTestCase):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
290
    layer = LibrarianLayer
3691.57.38 by Stuart Bishop
Add Layer tests
291
11737.2.10 by Robert Collins
Update Librarian test expectations.
292
    want_launchpad_database = True
3691.57.38 by Stuart Bishop
Add Layer tests
293
    want_librarian_running = True
294
11737.2.11 by Robert Collins
With the Librarian depending on the database, having the layer is enough to be useful.
295
    def testUploadsSucceed(self):
11737.2.12 by Robert Collins
Update missed comment.
296
        # This layer is able to be used on its own as it depends on
297
        # DatabaseLayer.
5718.5.4 by Stuart Bishop
Updates from Gavin's review
298
        # We can test this using remoteAddFile (it does not need the CA
299
        # loaded)
3691.57.38 by Stuart Bishop
Add Layer tests
300
        client = LibrarianClient()
301
        data = 'This is a test'
11737.2.11 by Robert Collins
With the Librarian depending on the database, having the layer is enough to be useful.
302
        client.remoteAddFile(
303
            'foo.txt', len(data), StringIO(data), 'text/plain')
3691.57.38 by Stuart Bishop
Add Layer tests
304
305
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
306
class LibrarianLayerTest(testtools.TestCase, TestWithFixtures):
307
308
    def test_makes_unique_instance(self):
309
        # Capture the original settings
310
        default_root = config.librarian_server.root
311
        download_port = config.librarian.download_port
312
        restricted_download_port = config.librarian.restricted_download_port
313
        self.useFixture(BaseLayerIsolator())
314
        with nested(
315
            LayerFixture(BaseLayer),
316
            LayerFixture(DatabaseLayer),
317
            ):
318
            with LayerFixture(LibrarianLayer):
319
                active_root = config.librarian_server.root
320
                # The config settings have changed:
321
                self.assertNotEqual(default_root, active_root)
322
                self.assertNotEqual(
323
                    download_port, config.librarian.download_port)
324
                self.assertNotEqual(
325
                    restricted_download_port,
326
                    config.librarian.restricted_download_port)
327
                self.assertTrue(os.path.exists(active_root))
11737.4.7 by Robert Collins
Clarity.
328
            # This needs more sophistication in the config system (tearDown on
329
            # the layer needs to pop the config fragment off of disk - and
330
            # perhaps notify other processes that its done this. So for now we
331
            # leave the new config in place).
11737.4.6 by Robert Collins
Make the librarian use dynamically allocated ports and root dir (except when in production / persistent test services).
332
            # self.assertEqual(default_root, config.librarian_server.root)
333
            # The working dir has to have been deleted.
334
            self.assertFalse(os.path.exists(active_root))
335
336
13322.1.4 by Robert Collins
Remove unneeded (redundant in story tests, unused otherwise) layer reset control logic.
337
class LibrarianResetTestCase(testtools.TestCase):
3691.57.38 by Stuart Bishop
Add Layer tests
338
    """Our page tests need to run multple tests without destroying
339
    the librarian database in between.
340
    """
13322.1.4 by Robert Collins
Remove unneeded (redundant in story tests, unused otherwise) layer reset control logic.
341
    layer = LibrarianLayer
3691.57.39 by Stuart Bishop
More Layer tests
342
3691.57.38 by Stuart Bishop
Add Layer tests
343
    sample_data = 'This is a test'
3691.57.39 by Stuart Bishop
More Layer tests
344
13322.1.4 by Robert Collins
Remove unneeded (redundant in story tests, unused otherwise) layer reset control logic.
345
    def test_librarian_is_reset(self):
346
        # Add a file. We use remoteAddFile because it does not need the CA
347
        # loaded to work.
3691.57.38 by Stuart Bishop
Add Layer tests
348
        client = LibrarianClient()
349
        LibrarianTestCase.url = client.remoteAddFile(
350
                self.sample_data, len(self.sample_data),
351
                StringIO(self.sample_data), 'text/plain'
352
                )
353
        self.failUnlessEqual(
354
                urlopen(LibrarianTestCase.url).read(), self.sample_data
355
                )
13322.1.4 by Robert Collins
Remove unneeded (redundant in story tests, unused otherwise) layer reset control logic.
356
        # Perform the librarian specific between-test code:
357
        LibrarianLayer.testTearDown()
358
        LibrarianLayer.testSetUp()
359
        # Which should have nuked the old file.
4664.1.1 by Curtis Hovey
Normalized comments for bug 3732.
360
        # XXX: StuartBishop 2006-06-30 Bug=51370:
361
        # We should get a DownloadFailed exception here.
3691.57.38 by Stuart Bishop
Add Layer tests
362
        data = urlopen(LibrarianTestCase.url).read()
363
        self.failIfEqual(data, self.sample_data)
364
365
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
366
class LibrarianHideTestCase(testtools.TestCase):
4696.2.1 by James Henstridge
make LibrarianLayer.hide() more reliable
367
    layer = LaunchpadLayer
368
369
    def testHideLibrarian(self):
370
        # First perform a successful upload:
371
        client = LibrarianClient()
372
        data = 'foo'
373
        client.remoteAddFile(
374
            'foo', len(data), StringIO(data), 'text/plain')
6233.8.4 by Michael Hudson
add a couple of force_dirty_database calls
375
        # The database was committed to, but not by this process, so we need
376
        # to ensure that it is fully torn down and recreated.
377
        DatabaseLayer.force_dirty_database()
4696.2.1 by James Henstridge
make LibrarianLayer.hide() more reliable
378
379
        # Hide the librarian, and show that the upload fails:
380
        LibrarianLayer.hide()
381
        self.assertRaises(UploadFailed, client.remoteAddFile,
382
                          'foo', len(data), StringIO(data), 'text/plain')
383
384
        # Reveal the librarian again, allowing uploads:
385
        LibrarianLayer.reveal()
386
        client.remoteAddFile(
387
            'foo', len(data), StringIO(data), 'text/plain')
388
389
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
390
class RabbitMQTestCase(BaseTestCase):
391
    layer = RabbitMQLayer
392
    want_rabbitmq = True
393
394
3691.57.38 by Stuart Bishop
Add Layer tests
395
class DatabaseTestCase(BaseTestCase):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
396
    layer = DatabaseLayer
3691.57.38 by Stuart Bishop
Add Layer tests
397
398
    want_launchpad_database = True
399
400
    def testConnect(self):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
401
        DatabaseLayer.connect()
3691.57.38 by Stuart Bishop
Add Layer tests
402
403
    def getWikinameCount(self, con):
404
        cur = con.cursor()
405
        cur.execute("SELECT COUNT(*) FROM Wikiname")
406
        num = cur.fetchone()[0]
407
        return num
408
13322.1.4 by Robert Collins
Remove unneeded (redundant in story tests, unused otherwise) layer reset control logic.
409
    def test_db_is_reset(self):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
410
        con = DatabaseLayer.connect()
3691.57.38 by Stuart Bishop
Add Layer tests
411
        cur = con.cursor()
412
        cur.execute("DELETE FROM Wikiname")
413
        self.failUnlessEqual(self.getWikinameCount(con), 0)
414
        con.commit()
13322.1.4 by Robert Collins
Remove unneeded (redundant in story tests, unused otherwise) layer reset control logic.
415
        # Run the per-test code for the Database layer.
416
        DatabaseLayer.testTearDown()
417
        DatabaseLayer.testSetUp()
418
        # Wikiname table should have been restored.
419
        con = DatabaseLayer.connect()
420
        self.assertNotEqual(0, self.getWikinameCount(con))
3691.57.38 by Stuart Bishop
Add Layer tests
421
422
423
class LaunchpadTestCase(BaseTestCase):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
424
    layer = LaunchpadLayer
3691.57.38 by Stuart Bishop
Add Layer tests
425
426
    want_launchpad_database = True
427
    want_librarian_running = True
9232.2.8 by Stuart Bishop
MemcacheClient tests and layer fixes
428
    want_memcached = True
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
429
    want_rabbitmq = True
3691.57.38 by Stuart Bishop
Add Layer tests
430
431
432
class FunctionalTestCase(BaseTestCase):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
433
    layer = FunctionalLayer
3691.57.38 by Stuart Bishop
Add Layer tests
434
435
    want_component_architecture = True
3691.57.39 by Stuart Bishop
More Layer tests
436
    want_functional_flag = True
3691.57.38 by Stuart Bishop
Add Layer tests
437
438
439
class ZopelessTestCase(BaseTestCase):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
440
    layer = ZopelessLayer
3691.57.38 by Stuart Bishop
Add Layer tests
441
442
    want_component_architecture = True
3962.1.3 by Stuart Bishop
ZopelessLayer should not bring up database and librarian
443
    want_launchpad_database = False
444
    want_librarian_running = False
3691.57.42 by Stuart Bishop
More post review feedback updates
445
    want_zopeless_flag = True
3691.57.39 by Stuart Bishop
More Layer tests
446
447
448
class LaunchpadFunctionalTestCase(BaseTestCase):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
449
    layer = LaunchpadFunctionalLayer
3691.57.39 by Stuart Bishop
More Layer tests
450
451
    want_component_architecture = True
452
    want_launchpad_database = True
453
    want_librarian_running = True
454
    want_functional_flag = True
9232.2.8 by Stuart Bishop
MemcacheClient tests and layer fixes
455
    want_memcached = True
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
456
    want_rabbitmq = True
3691.57.39 by Stuart Bishop
More Layer tests
457
458
4264.3.3 by James Henstridge
add LaunchpadScriptLayer for testing scripts that use the main database adapter
459
class LaunchpadZopelessTestCase(BaseTestCase):
3691.57.47 by Stuart Bishop
Rename canonical.testing.layers.* to canonical.testing.*Layer
460
    layer = LaunchpadZopelessLayer
3691.57.39 by Stuart Bishop
More Layer tests
461
462
    want_component_architecture = True
463
    want_launchpad_database = True
464
    want_librarian_running = True
3691.57.42 by Stuart Bishop
More post review feedback updates
465
    want_zopeless_flag = True
9232.2.8 by Stuart Bishop
MemcacheClient tests and layer fixes
466
    want_memcached = True
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
467
    want_rabbitmq = True
3691.57.38 by Stuart Bishop
Add Layer tests
468
469
4264.3.3 by James Henstridge
add LaunchpadScriptLayer for testing scripts that use the main database adapter
470
class LaunchpadScriptTestCase(BaseTestCase):
471
    layer = LaunchpadScriptLayer
472
473
    want_component_architecture = True
474
    want_launchpad_database = True
475
    want_librarian_running = True
476
    want_zopeless_flag = True
9232.2.8 by Stuart Bishop
MemcacheClient tests and layer fixes
477
    want_memcached = True
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
478
    want_rabbitmq = True
4264.3.3 by James Henstridge
add LaunchpadScriptLayer for testing scripts that use the main database adapter
479
480
7064.1.4 by Barry Warsaw
Response to Francis's review.
481
class LayerProcessControllerInvariantsTestCase(BaseTestCase):
6697.3.2 by Francis J. Lacoste
Refactored AppServerLayer to only start up the web app server using runlaunchpad.py.
482
    layer = AppServerLayer
483
484
    want_component_architecture = True
485
    want_launchpad_database = True
486
    want_librarian_running = True
487
    want_functional_flag = True
488
    want_zopeless_flag = False
9232.2.8 by Stuart Bishop
MemcacheClient tests and layer fixes
489
    want_memcached = True
13023.9.1 by Robert Collins
Add a layer for RabbitMQ and bring that into the launchpad layers.
490
    want_rabbitmq = True
6697.3.2 by Francis J. Lacoste
Refactored AppServerLayer to only start up the web app server using runlaunchpad.py.
491
492
    def testAppServerIsAvailable(self):
493
        # Test that the app server is up and running.
7064.1.4 by Barry Warsaw
Response to Francis's review.
494
        mainsite = LayerProcessController.appserver_config.vhost.mainsite
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
495
        home_page = urlopen(mainsite.rooturl).read()
6697.3.2 by Francis J. Lacoste
Refactored AppServerLayer to only start up the web app server using runlaunchpad.py.
496
        self.failUnless(
9481.3.8 by Henning Eggers
Kiko's improvments. Fixed tests.
497
            'Is your project registered yet?' in home_page,
6697.3.2 by Francis J. Lacoste
Refactored AppServerLayer to only start up the web app server using runlaunchpad.py.
498
            "Home page couldn't be retrieved:\n%s" % home_page)
499
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
500
    def testSMTPServerIsAvailable(self):
501
        # Test that the SMTP server is up and running.
502
        smtpd = smtplib.SMTP()
7064.1.4 by Barry Warsaw
Response to Francis's review.
503
        host, port = as_host_port(config.mailman.smtp)
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
504
        code, message = smtpd.connect(host, port)
505
        self.assertEqual(code, 220)
506
507
    def testStartingAppServerTwiceRaisesInvariantError(self):
508
        # Starting the appserver twice should raise an exception.
509
        self.assertRaises(LayerInvariantError,
7064.1.4 by Barry Warsaw
Response to Francis's review.
510
                          LayerProcessController.startAppServer)
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
511
512
    def testStartingSMTPServerTwiceRaisesInvariantError(self):
513
        # Starting the SMTP server twice should raise an exception.
514
        self.assertRaises(LayerInvariantError,
7064.1.4 by Barry Warsaw
Response to Francis's review.
515
                          LayerProcessController.startSMTPServer)
516
517
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
518
class LayerProcessControllerTestCase(testtools.TestCase):
7064.1.4 by Barry Warsaw
Response to Francis's review.
519
    """Tests for the `LayerProcessController`."""
6789.14.9 by Michael Hudson
fix tests
520
    # We need the database to be set up, no more.
521
    layer = DatabaseLayer
6697.3.2 by Francis J. Lacoste
Refactored AppServerLayer to only start up the web app server using runlaunchpad.py.
522
523
    def tearDown(self):
11737.2.1 by Robert Collins
Convert test_layers to use testtools test cases.
524
        super(LayerProcessControllerTestCase, self).tearDown()
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
525
        # Stop both servers.  It's okay if they aren't running.
7064.1.4 by Barry Warsaw
Response to Francis's review.
526
        LayerProcessController.stopSMTPServer()
527
        LayerProcessController.stopAppServer()
6697.3.2 by Francis J. Lacoste
Refactored AppServerLayer to only start up the web app server using runlaunchpad.py.
528
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
529
    def test_stopAppServer(self):
530
        # Test that stopping the app server kills the process and remove the
531
        # PID file.
13992.1.1 by Gary Poster
Add yui xhr integration test support.
532
        LayerProcessController.setConfig()
7064.1.4 by Barry Warsaw
Response to Francis's review.
533
        LayerProcessController.startAppServer()
534
        pid = LayerProcessController.appserver.pid
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
535
        pid_file = pidfile_path('launchpad',
7064.1.4 by Barry Warsaw
Response to Francis's review.
536
                                LayerProcessController.appserver_config)
537
        LayerProcessController.stopAppServer()
6697.3.2 by Francis J. Lacoste
Refactored AppServerLayer to only start up the web app server using runlaunchpad.py.
538
        self.assertRaises(OSError, os.kill, pid, 0)
539
        self.failIf(os.path.exists(pid_file), "PID file wasn't removed")
7064.1.4 by Barry Warsaw
Response to Francis's review.
540
        self.failUnless(LayerProcessController.appserver is None,
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
541
                        "appserver class attribute wasn't reset")
542
543
    def test_postTestInvariants(self):
544
        # A LayerIsolationError should be raised if the app server dies in the
545
        # middle of a test.
13992.1.1 by Gary Poster
Add yui xhr integration test support.
546
        LayerProcessController.setConfig()
7064.1.4 by Barry Warsaw
Response to Francis's review.
547
        LayerProcessController.startAppServer()
548
        pid = LayerProcessController.appserver.pid
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
549
        os.kill(pid, signal.SIGTERM)
7064.1.4 by Barry Warsaw
Response to Francis's review.
550
        LayerProcessController.appserver.wait()
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
551
        self.assertRaises(LayerIsolationError,
7064.1.4 by Barry Warsaw
Response to Francis's review.
552
                          LayerProcessController.postTestInvariants)
7064.1.1 by Barry Warsaw
Remove _BaseAppServerLayer as a layer because inheritance does not work the
553
554
    def test_postTestInvariants_dbIsReset(self):
555
        # The database should be reset by the test invariants.
13992.1.1 by Gary Poster
Add yui xhr integration test support.
556
        LayerProcessController.setConfig()
7064.1.4 by Barry Warsaw
Response to Francis's review.
557
        LayerProcessController.startAppServer()
558
        LayerProcessController.postTestInvariants()
11728.2.3 by Robert Collins
Other users of LaunchpadTestSetup converted to use instances.
559
        # XXX: Robert Collins 2010-10-17 bug=661967 - this isn't a reset, its
560
        # a flag that it *needs* a reset, which is actually quite different;
13992.1.1 by Gary Poster
Add yui xhr integration test support.
561
        # the lack of a teardown will leak databases.
6697.3.2 by Francis J. Lacoste
Refactored AppServerLayer to only start up the web app server using runlaunchpad.py.
562
        self.assertEquals(True, LaunchpadTestSetup()._reset_db)
563
564
11728.3.1 by Robert Collins
Set LP_TEST_INSTANCE during BaseLayer, if we're not using persistent test helpers.
565
class TestNameTestCase(testtools.TestCase):
5398.8.29 by Stuart Bishop
Final tweaks before landing this part 1. Expose the test name for other uses.
566
    layer = BaseLayer
13023.9.6 by Gavin Panella
Fix lint.
567
5398.8.29 by Stuart Bishop
Final tweaks before landing this part 1. Expose the test name for other uses.
568
    def testTestName(self):
569
        self.failUnlessEqual(
570
                BaseLayer.test_name,
571
                "testTestName "
14604.1.1 by Curtis Hovey
Separate test-authoring classes from test-running classes.
572
                "(lp.testing.tests.test_layers_functional.TestNameTestCase)")