Some docs for the TestingMiddleware
[mediagoblin.git] / mediagoblin / tests / tools.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17
18 import pkg_resources
19 import os, shutil
20
21 from paste.deploy import loadapp
22 from webtest import TestApp
23
24 from mediagoblin import mg_globals
25 from mediagoblin.tools import testing
26 from mediagoblin.middleware.testing import TestingMiddleware
27 from mediagoblin.init.config import read_mediagoblin_config
28 from mediagoblin.decorators import _make_safe
29 from mediagoblin.db.open import setup_connection_and_db_from_config
30
31
32 MEDIAGOBLIN_TEST_DB_NAME = u'__mediagoblin_tests__'
33 TEST_SERVER_CONFIG = pkg_resources.resource_filename(
34 'mediagoblin.tests', 'test_paste.ini')
35 TEST_APP_CONFIG = pkg_resources.resource_filename(
36 'mediagoblin.tests', 'test_mgoblin_app.ini')
37 TEST_USER_DEV = pkg_resources.resource_filename(
38 'mediagoblin.tests', 'test_user_dev')
39 MGOBLIN_APP = None
40
41 USER_DEV_DIRECTORIES_TO_SETUP = [
42 'media/public', 'media/queue',
43 'beaker/sessions/data', 'beaker/sessions/lock']
44
45 BAD_CELERY_MESSAGE = """\
46 Sorry, you *absolutely* must run nosetests with the
47 mediagoblin.init.celery.from_tests module. Like so:
48 $ CELERY_CONFIG_MODULE=mediagoblin.init.celery.from_tests ./bin/nosetests"""
49
50
51 class BadCeleryEnviron(Exception): pass
52
53
54 def suicide_if_bad_celery_environ():
55 if not os.environ.get('CELERY_CONFIG_MODULE') == \
56 'mediagoblin.init.celery.from_tests':
57 raise BadCeleryEnviron(BAD_CELERY_MESSAGE)
58
59
60 def get_test_app(dump_old_app=True):
61 suicide_if_bad_celery_environ()
62
63 # Make sure we've turned on testing
64 testing._activate_testing()
65
66 # Leave this imported as it sets up celery.
67 from mediagoblin.init.celery import from_tests
68
69 global MGOBLIN_APP
70
71 # Just return the old app if that exists and it's okay to set up
72 # and return
73 if MGOBLIN_APP and not dump_old_app:
74 return MGOBLIN_APP
75
76 # Remove and reinstall user_dev directories
77 if os.path.exists(TEST_USER_DEV):
78 shutil.rmtree(TEST_USER_DEV)
79
80 for directory in USER_DEV_DIRECTORIES_TO_SETUP:
81 full_dir = os.path.join(TEST_USER_DEV, directory)
82 os.makedirs(full_dir)
83
84 # Get app config
85 global_config, validation_result = read_mediagoblin_config(TEST_APP_CONFIG)
86 app_config = global_config['mediagoblin']
87
88 # Wipe database
89 # @@: For now we're dropping collections, but we could also just
90 # collection.remove() ?
91 connection, db = setup_connection_and_db_from_config(app_config)
92 assert db.name == MEDIAGOBLIN_TEST_DB_NAME
93
94 collections_to_wipe = [
95 collection
96 for collection in db.collection_names()
97 if not collection.startswith('system.')]
98
99 for collection in collections_to_wipe:
100 db.drop_collection(collection)
101
102 # TODO: Drop and recreate indexes
103
104 # setup app and return
105 test_app = loadapp(
106 'config:' + TEST_SERVER_CONFIG)
107
108 # Insert the TestingMiddleware, which can do some
109 # sanity checks on every request/response.
110 # Doing it this way is probably not the cleanest way.
111 # We'll fix it, when we have plugins!
112 mg_globals.app.middleware.insert(0, TestingMiddleware(mg_globals.app))
113
114 app = TestApp(test_app)
115 MGOBLIN_APP = app
116
117 return app
118
119
120 def setup_fresh_app(func):
121 """
122 Decorator to setup a fresh test application for this function.
123
124 Cleans out test buckets and passes in a new, fresh test_app.
125 """
126 def wrapper(*args, **kwargs):
127 test_app = get_test_app()
128 testing.clear_test_buckets()
129 return func(test_app, *args, **kwargs)
130
131 return _make_safe(wrapper, func)
132
133
134 def install_fixtures_simple(db, fixtures):
135 """
136 Very simply install fixtures in the database
137 """
138 for collection_name, collection_fixtures in fixtures.iteritems():
139 collection = db[collection_name]
140 for fixture in collection_fixtures:
141 collection.insert(fixture)
142
143
144 def assert_db_meets_expected(db, expected):
145 """
146 Assert a database contains the things we expect it to.
147
148 Objects are found via '_id', so you should make sure your document
149 has an _id.
150
151 Args:
152 - db: pymongo or mongokit database connection
153 - expected: the data we expect. Formatted like:
154 {'collection_name': [
155 {'_id': 'foo',
156 'some_field': 'some_value'},]}
157 """
158 for collection_name, collection_data in expected.iteritems():
159 collection = db[collection_name]
160 for expected_document in collection_data:
161 document = collection.find_one({'_id': expected_document['_id']})
162 assert document is not None # make sure it exists
163 assert document == expected_document # make sure it matches