This repository was archived by the owner on Nov 29, 2019. It is now read-only.
Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
232 lines (185 loc) · 7.33 KB
/
Copy path__init__.py
File metadata and controls
232 lines (185 loc) · 7.33 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
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
"""
All utility methods, classes and functions needed for testing applications
"""
import os
from contextlib import contextmanager
from io import BytesIO
from itertools import chain
from pyramid.threadlocal import manager
from webob.request import environ_from_url
from webtest import TestRequest
from assembl.auth import R_PARTICIPANT
from assembl.lib import logging
from assembl.lib.sqla import (
get_session_maker,
get_metadata, mark_changed)
log = logging.getLogger()
class FakeLocalizer(object):
def translate(self, message):
return message
class PyramidWebTestRequest(TestRequest):
"""
A mock Pyramid web request this pushes itself onto the threadlocal stack
that also contains the Assembl user_id according to authentication
model
This is very useful because throughout the model logic, a request is often
required to determine the current_user, but outside of a Pyramid view. The
way a request is injected is via the current_thread from threadlocal.
"""
def __init__(self, *args, **kwargs):
super(PyramidWebTestRequest, self).__init__(*args, **kwargs)
manager.push({'request': self, 'registry': self._registry})
self._base_pyramid_request = self._pyramid_app.request_factory(
environ_from_url('/'))
def get_response(self, app, catch_exc_info=True):
try:
super(PyramidWebTestRequest, app).get_response(
catch_exc_info=catch_exc_info)
finally:
manager.pop()
def route_path(self, name, *args, **kwargs):
return self._base_pyramid_request.route_path(
name, *args, **kwargs)
def route_url(self, name, *args, **kwargs):
return self._base_pyramid_request.route_url(
name, *args, **kwargs)
# TODO: Find a way to change user here
authenticated_userid = None
# How come this is missing in TestRequest?
# TODO: Use the negotiator
locale_name = 'en'
localizer = FakeLocalizer()
def committing_session_tween_factory(handler, registry):
# This ensures that the app has the latest state
def committing_session_tween(request):
get_session_maker().commit()
resp = handler(request)
get_session_maker().flush()
return resp
return committing_session_tween
def as_boolean(s):
if isinstance(s, bool):
return s
return str(s).lower() in ['true', '1', 'on', 'yes']
def get_all_tables(app_settings, session, reversed=True):
schema = app_settings.get('db_schema', 'assembl_test')
# TODO: Quote schema name!
res = session.execute(
"SELECT table_name FROM "
"information_schema.tables WHERE table_schema = "
"'%s' ORDER BY table_name" % (schema,)).fetchall()
res = {row[0] for row in res}
# get the ordered version to minimize cascade.
# cascade does not exist on virtuoso.
ordered = [t.name for t in get_metadata().sorted_tables
if t.name in res]
ordered.extend([t for t in res if t not in ordered])
if reversed:
ordered.reverse()
log.debug('Current tables: %s' % str(ordered))
return ordered
def self_referential_columns(table):
return [fk.parent for fk in chain(*[
c.foreign_keys for c in table.columns])
if fk.column.table == table]
def clear_rows(app_settings, session):
log.info('Clearing database rows.')
tables_by_name = {
t.name: t for t in get_metadata().sorted_tables}
for table_name in get_all_tables(app_settings, session):
log.debug("Clearing table: %s" % table_name)
table = tables_by_name.get(table_name, None)
if table is not None:
cols = self_referential_columns(table)
if len(cols):
for col in cols:
session.execute("UPDATE %s SET %s=NULL" % (table_name, col.key))
session.flush()
session.execute("DELETE FROM \"%s\"" % table_name)
session.commit()
session.transaction.close()
def drop_tables(app_settings, session):
log.info('Dropping all tables.')
session.close()
try:
get_metadata().drop_all(session.connection())
mark_changed()
except Exception as e:
raise Exception('Error dropping tables: %s' % e)
def base_fixture_dirname():
from os.path import dirname
return dirname(dirname(dirname(dirname(__file__)))) +\
"/assembl/static/js/app/tests/fixtures/"
def api_call_to_fname(api_call, method="GET", **args):
"""Translate an API call to a filename containing most of the call information
Used in :js:func:`ajaxMock`"""
import os.path
base_fixture_dir = base_fixture_dirname()
api_dir, fname = api_call.rsplit("/", 1)
api_dir = base_fixture_dir + api_dir
if not os.path.isdir(api_dir):
os.makedirs(api_dir)
args = args.items()
args.sort()
args = "_".join(["%s_%s" % x for x in args])
if args:
fname += "_" + args
if method != "GET":
fname = method + "_" + fname
fname += ".json"
return os.path.join(api_dir, fname)
class RecordingApp(object):
"Decorator for the test_app"
def __init__(self, test_app):
self.app = test_app
def __getattribute__(self, name):
if name not in {
"get", "post", "post_json", "put", "put_json",
"delete", "patch", "patch_json"}:
return super(RecordingApp, self).__getattribute__(name)
def appmethod(url, params=None, headers=None):
r = getattr(self.app, name)(url, params, headers)
assert 200 <= r.status_code < 300
params = params or {}
methodname = name.split("_")[0].upper()
with open(api_call_to_fname(url, methodname, **params), "w") as f:
f.write(r.body)
return r
return appmethod
def _create_role_for_user(user, discussion, session=None, role=R_PARTICIPANT):
from assembl.models.auth import LocalUserRole, Role
session = session or Role.default_db
role = Role.get_role(role)
local_role = LocalUserRole(user_id=user.id, discussion_id=discussion.id, role_id=role.id)
session.add(local_role)
session.flush()
return local_role
def _delete_all_local_roles_for_user(user, discussion, session=None):
from assembl.models import LocalUserRole
session = session or LocalUserRole.default_db
session.query(LocalUserRole).filter(
LocalUserRole.discussion_id == discussion.id,
LocalUserRole.user_id == user.id).delete()
session.flush()
@contextmanager
def give_user_role(user, discussion, role=R_PARTICIPANT, session=None):
"""A usuable context manager to temporarily give a non-admin user a role within a discussion.
All testing can be done in the context of this higher role-based user."""
_create_role_for_user(user, discussion, session=session, role=role)
yield
_delete_all_local_roles_for_user(user, discussion, session=session)
@contextmanager
def update_configuration(settings, **kwargs):
import copy
from assembl.lib.config import set_config
old_settings = settings
new_settings = copy.deepcopy(settings)
new_settings.update(kwargs)
set_config(new_settings)
yield new_settings
set_config(old_settings)
class FakeUploadedFile(object):
file = BytesIO(os.urandom(16))
def __init__(self, filename, type):
self.filename = filename
self.type = type