Child: [e23020] (diff)

Download this file

controller.py    184 lines (151 with data), 6.6 kB

  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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Unit and functional test suite for allura."""
import os
import urllib
import mock
import beaker.session
from formencode import variabledecode
from paste.deploy import loadapp
from paste.deploy.converters import asbool
from paste.script.appinstall import SetupCommand
from pylons import tmpl_context as c, app_globals as g
from pylons import url, request, response, session
import tg
from webtest import TestApp
from webob import Request, Response
import ew
from ming.orm import ThreadLocalORMSession
import ming.orm
from allura import model as M
import allura.lib.security
from allura.lib.app_globals import Globals
from allura.lib import helpers as h
from allura.websetup.schema import REGISTRY
#from allura.lib.custom_middleware import environ as ENV, MagicalC
from .validation import ValidatingTestApp
DFL_APP_NAME = 'main_without_authn'
# these are all helpers & base classes, and should never
# be considered test cases when imported into some test module
__test__ = False
def get_config_file(config=None):
if not config:
config = 'test.ini'
try:
conf_dir = tg.config.here
except AttributeError:
conf_dir = os.getcwd()
return os.path.join(conf_dir, config)
def setup_basic_test(config=None, app_name=DFL_APP_NAME):
'''Create clean environment for running tests'''
try:
conf_dir = tg.config.here
except AttributeError:
conf_dir = os.getcwd()
ew.TemplateEngine.initialize({})
test_file = os.path.join(conf_dir, get_config_file(config))
cmd = SetupCommand('setup-app')
cmd.run([test_file])
# run all tasks, e.g. indexing from bootstrap operations
while M.MonQTask.run_ready('setup'):
ThreadLocalORMSession.flush_all()
setup_basic_test.__test__ = False # sometimes __test__ above isn't sufficient
def setup_functional_test(config=None, app_name=DFL_APP_NAME):
'''Create clean environment for running tests. Also return WSGI test app'''
config = get_config_file(config)
setup_basic_test(config, app_name)
conf_dir = tg.config.here
wsgiapp = loadapp('config:%s#%s' % (config, app_name),
relative_to=conf_dir)
return wsgiapp
setup_functional_test.__test__ = False # sometimes __test__ above isn't sufficient
def setup_unit_test():
try:
while True:
REGISTRY.cleanup()
except:
pass
REGISTRY.prepare()
REGISTRY.register(ew.widget_context, ew.core.WidgetContext('http', ew.ResourceManager()))
REGISTRY.register(g, Globals())
REGISTRY.register(c, mock.Mock())
REGISTRY.register(url, lambda:None)
REGISTRY.register(request, Request.blank('/', remote_addr='1.1.1.1'))
REGISTRY.register(response, Response())
REGISTRY.register(session, beaker.session.SessionObject({}))
REGISTRY.register(allura.credentials, allura.lib.security.Credentials())
c.memoize_cache = {}
c.queued_messages = None
c.model_cache = None
ThreadLocalORMSession.close_all()
setup_unit_test.__test__ = False # sometimes __test__ above isn't sufficient
def setup_global_objects():
setup_unit_test()
h.set_context('test', 'wiki', neighborhood='Projects')
c.user = M.User.query.get(username='test-admin')
class TestController(object):
application_under_test = 'main'
validate_skip = False
def setUp(self):
"""Method called by nose before running each test"""
self.app = ValidatingTestApp(setup_functional_test(app_name=self.application_under_test))
if self.validate_skip:
self.app.validate_skip = self.validate_skip
if asbool(tg.config.get('smtp.mock')):
self.smtp_mock = mock.patch('allura.lib.mail_util.smtplib.SMTP')
self.smtp_mock.start()
def tearDown(self):
"""Method called by nose after running each test"""
if asbool(tg.config.get('smtp.mock')):
self.smtp_mock.stop()
def webflash(self, response):
"Extract webflash content from response."
return urllib.unquote(response.cookies_set.get('webflash', ''))
class TestRestApiBase(TestController):
def setUp(self):
super(TestRestApiBase, self).setUp()
setup_global_objects()
# h.set_context('test', 'home')
self.user = M.User.query.get(username='test-admin')
self.token = M.ApiToken(user_id=self.user._id)
ming.orm.session(self.token).flush()
def set_api_token(self, token):
self.token = token
def _api_getpost(self, method, path, api_key=None, api_timestamp=None, api_signature=None,
wrap_args=None, **params):
if wrap_args:
params = {wrap_args: params}
params = variabledecode.variable_encode(params, add_repetitions=False)
if api_key: params['api_key'] = api_key
if api_timestamp: params['api_timestamp'] = api_timestamp
if api_signature: params['api_signature'] = api_signature
params = self.token.sign_request(path, params)
fn = self.app.post if method=='POST' else self.app.get
response = fn(
str(path),
params=params,
status=[200, 302, 400, 403, 404])
if response.status_int == 302:
return response.follow()
else:
return response
def api_get(self, path, api_key=None, api_timestamp=None, api_signature=None,
wrap_args=None, **params):
return self._api_getpost('GET', path, api_key, api_timestamp, api_signature, wrap_args, **params)
def api_post(self, path, api_key=None, api_timestamp=None, api_signature=None,
wrap_args=None, **params):
return self._api_getpost('POST', path, api_key, api_timestamp, api_signature, wrap_args, **params)