author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Thu, 01 Oct 2009 09:41:26 +0200 | |
branch | stable |
changeset 3540 | 9428810469a6 |
parent 3225 | 464c5b9c6fa0 |
child 4212 | ab6573088b4a |
permissions | -rw-r--r-- |
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2298
diff
changeset
|
1 |
"""This module provides misc utilities to test instances |
0 | 2 |
|
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1648
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1648
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
9 |
||
10 |
from copy import deepcopy |
|
11 |
||
12 |
import simplejson |
|
13 |
||
14 |
from logilab.common.testlib import TestCase |
|
15 |
from logilab.common.pytest import nocoverage |
|
16 |
from logilab.common.umessage import message_from_string |
|
17 |
||
2613
5e19c2bb370e
R [all] logilab.common 0.44 provides only deprecated
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2476
diff
changeset
|
18 |
from logilab.common.deprecation import deprecated |
1394
ff1e912cbc39
remove pmainactions and deprecate paddrelactions
Katia Saurfelt <katia.saurfelt@logilab.fr>
parents:
1383
diff
changeset
|
19 |
|
0 | 20 |
from cubicweb.devtools import init_test_database, TestServerConfiguration, ApptestConfiguration |
21 |
from cubicweb.devtools._apptest import TestEnvironment |
|
22 |
from cubicweb.devtools.fake import FakeRequest |
|
23 |
||
24 |
from cubicweb.dbapi import repo_connect, ConnectionProperties, ProgrammingError |
|
25 |
||
26 |
||
27 |
MAILBOX = [] |
|
28 |
class Email: |
|
29 |
def __init__(self, recipients, msg): |
|
30 |
self.recipients = recipients |
|
31 |
self.msg = msg |
|
32 |
||
33 |
@property |
|
34 |
def message(self): |
|
35 |
return message_from_string(self.msg) |
|
1486 | 36 |
|
2298
8dffb4cce3b7
nicer api to test sent email
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
37 |
@property |
8dffb4cce3b7
nicer api to test sent email
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
38 |
def subject(self): |
8dffb4cce3b7
nicer api to test sent email
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
39 |
return self.message.get('Subject') |
8dffb4cce3b7
nicer api to test sent email
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
40 |
|
8dffb4cce3b7
nicer api to test sent email
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
41 |
@property |
8dffb4cce3b7
nicer api to test sent email
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
42 |
def content(self): |
8dffb4cce3b7
nicer api to test sent email
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
43 |
return self.message.get_payload(decode=True) |
8dffb4cce3b7
nicer api to test sent email
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
44 |
|
0 | 45 |
def __repr__(self): |
46 |
return '<Email to %s with subject %s>' % (','.join(self.recipients), |
|
47 |
self.message.get('Subject')) |
|
1486 | 48 |
|
0 | 49 |
class MockSMTP: |
50 |
def __init__(self, server, port): |
|
51 |
pass |
|
52 |
def close(self): |
|
53 |
pass |
|
54 |
def sendmail(self, helo_addr, recipients, msg): |
|
55 |
MAILBOX.append(Email(recipients, msg)) |
|
56 |
||
2221
d9b85a7b0bdd
create sendmails method on cwconfig, use it in SendMailOp
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
57 |
from cubicweb import cwconfig |
d9b85a7b0bdd
create sendmails method on cwconfig, use it in SendMailOp
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
58 |
cwconfig.SMTP = MockSMTP |
0 | 59 |
|
60 |
||
61 |
def get_versions(self, checkversions=False): |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2298
diff
changeset
|
62 |
"""return the a dictionary containing cubes used by this instance |
0 | 63 |
as key with their version as value, including cubicweb version. This is a |
64 |
public method, not requiring a session id. |
|
65 |
||
66 |
replace Repository.get_versions by this method if you don't want versions |
|
67 |
checking |
|
68 |
""" |
|
69 |
vcconf = {'cubicweb': self.config.cubicweb_version()} |
|
70 |
self.config.bootstrap_cubes() |
|
71 |
for pk in self.config.cubes(): |
|
17
62ce3e6126e0
work in progress: fix cubicweb/server tests
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
0
diff
changeset
|
72 |
version = self.config.cube_version(pk) |
0 | 73 |
vcconf[pk] = version |
74 |
self.config._cubes = None |
|
75 |
return vcconf |
|
76 |
||
77 |
||
78 |
@property |
|
79 |
def late_binding_env(self): |
|
80 |
"""builds TestEnvironment as late as possible""" |
|
81 |
if not hasattr(self, '_env'): |
|
82 |
self.__class__._env = TestEnvironment('data', configcls=self.configcls, |
|
83 |
requestcls=self.requestcls) |
|
84 |
return self._env |
|
85 |
||
86 |
||
87 |
class autoenv(type): |
|
88 |
"""automatically set environment on EnvBasedTC subclasses if necessary |
|
89 |
""" |
|
90 |
def __new__(mcs, name, bases, classdict): |
|
91 |
env = classdict.get('env') |
|
92 |
# try to find env in one of the base classes |
|
93 |
if env is None: |
|
94 |
for base in bases: |
|
95 |
env = getattr(base, 'env', None) |
|
96 |
if env is not None: |
|
97 |
classdict['env'] = env |
|
98 |
break |
|
99 |
if not classdict.get('__abstract__') and not classdict.get('env'): |
|
100 |
classdict['env'] = late_binding_env |
|
101 |
return super(autoenv, mcs).__new__(mcs, name, bases, classdict) |
|
102 |
||
103 |
||
104 |
class EnvBasedTC(TestCase): |
|
105 |
"""abstract class for test using an apptest environment |
|
106 |
""" |
|
107 |
__metaclass__ = autoenv |
|
108 |
__abstract__ = True |
|
109 |
env = None |
|
110 |
configcls = ApptestConfiguration |
|
111 |
requestcls = FakeRequest |
|
1486 | 112 |
|
0 | 113 |
# user / session management ############################################### |
114 |
||
115 |
def user(self, req=None): |
|
116 |
if req is None: |
|
117 |
req = self.env.create_request() |
|
118 |
return self.env.cnx.user(req) |
|
119 |
else: |
|
120 |
return req.user |
|
121 |
||
122 |
def create_user(self, *args, **kwargs): |
|
123 |
return self.env.create_user(*args, **kwargs) |
|
124 |
||
387
dbe9997ffc7e
password can now be given as optional argument
sylvain.thenault@logilab.fr
parents:
17
diff
changeset
|
125 |
def login(self, login, password=None): |
dbe9997ffc7e
password can now be given as optional argument
sylvain.thenault@logilab.fr
parents:
17
diff
changeset
|
126 |
return self.env.login(login, password) |
0 | 127 |
|
128 |
def restore_connection(self): |
|
129 |
self.env.restore_connection() |
|
1486 | 130 |
|
0 | 131 |
# db api ################################################################## |
132 |
||
133 |
@nocoverage |
|
134 |
def cursor(self, req=None): |
|
135 |
return self.env.cnx.cursor(req or self.request()) |
|
1486 | 136 |
|
0 | 137 |
@nocoverage |
138 |
def execute(self, *args, **kwargs): |
|
139 |
return self.env.execute(*args, **kwargs) |
|
140 |
||
141 |
@nocoverage |
|
142 |
def commit(self): |
|
143 |
self.env.cnx.commit() |
|
1486 | 144 |
|
0 | 145 |
@nocoverage |
146 |
def rollback(self): |
|
147 |
try: |
|
148 |
self.env.cnx.rollback() |
|
149 |
except ProgrammingError: |
|
150 |
pass |
|
1486 | 151 |
|
0 | 152 |
# other utilities ######################################################### |
153 |
def set_debug(self, debugmode): |
|
154 |
from cubicweb.server import set_debug |
|
155 |
set_debug(debugmode) |
|
1486 | 156 |
|
0 | 157 |
@property |
158 |
def config(self): |
|
159 |
return self.vreg.config |
|
160 |
||
161 |
def session(self): |
|
162 |
"""return current server side session (using default manager account)""" |
|
163 |
return self.env.repo._sessions[self.env.cnx.sessionid] |
|
1486 | 164 |
|
0 | 165 |
def request(self, *args, **kwargs): |
166 |
"""return a web interface request""" |
|
167 |
return self.env.create_request(*args, **kwargs) |
|
168 |
||
169 |
@nocoverage |
|
170 |
def rset_and_req(self, *args, **kwargs): |
|
171 |
return self.env.get_rset_and_req(*args, **kwargs) |
|
1486 | 172 |
|
0 | 173 |
def entity(self, rql, args=None, eidkey=None, req=None): |
174 |
return self.execute(rql, args, eidkey, req=req).get_entity(0, 0) |
|
1486 | 175 |
|
0 | 176 |
def etype_instance(self, etype, req=None): |
177 |
req = req or self.request() |
|
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2616
diff
changeset
|
178 |
e = self.env.vreg['etypes'].etype_class(etype)(req) |
0 | 179 |
e.eid = None |
180 |
return e |
|
1486 | 181 |
|
0 | 182 |
def add_entity(self, etype, **kwargs): |
183 |
rql = ['INSERT %s X' % etype] |
|
184 |
||
185 |
# dict for replacement in RQL Request |
|
186 |
rql_args = {} |
|
187 |
||
188 |
if kwargs: # |
|
189 |
rql.append(':') |
|
190 |
# dict to define new entities variables |
|
191 |
entities = {} |
|
192 |
||
193 |
# assignement part of the request |
|
194 |
sub_rql = [] |
|
195 |
for key, value in kwargs.iteritems(): |
|
196 |
# entities |
|
1486 | 197 |
if hasattr(value, 'eid'): |
0 | 198 |
new_value = "%s__" % key.upper() |
1486 | 199 |
|
0 | 200 |
entities[new_value] = value.eid |
201 |
rql_args[new_value] = value.eid |
|
1486 | 202 |
|
0 | 203 |
sub_rql.append("X %s %s" % (key, new_value)) |
204 |
# final attributes |
|
1486 | 205 |
else: |
0 | 206 |
sub_rql.append('X %s %%(%s)s' % (key, key)) |
207 |
rql_args[key] = value |
|
208 |
rql.append(', '.join(sub_rql)) |
|
209 |
||
210 |
||
211 |
if entities: |
|
212 |
rql.append('WHERE') |
|
213 |
# WHERE part of the request (to link entity to they eid) |
|
214 |
sub_rql = [] |
|
215 |
for key, value in entities.iteritems(): |
|
216 |
sub_rql.append("%s eid %%(%s)s" % (key, key)) |
|
217 |
rql.append(', '.join(sub_rql)) |
|
218 |
||
219 |
rql = ' '.join(rql) |
|
220 |
rset = self.execute(rql, rql_args) |
|
221 |
return rset.get_entity(0, 0) |
|
222 |
||
223 |
def set_option(self, optname, value): |
|
224 |
self.vreg.config.global_set_option(optname, value) |
|
225 |
||
226 |
def pviews(self, req, rset): |
|
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2616
diff
changeset
|
227 |
return sorted((a.id, a.__class__) for a in self.vreg['views'].possible_views(req, rset=rset)) |
1486 | 228 |
|
3540
9428810469a6
by default skip new 'footer' category
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3225
diff
changeset
|
229 |
def pactions(self, req, rset, skipcategories=('addrelated', 'siteactions', 'useractions', 'footer')): |
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2616
diff
changeset
|
230 |
return [(a.id, a.__class__) for a in self.vreg['actions'].possible_vobjects(req, rset=rset) |
0 | 231 |
if a.category not in skipcategories] |
1394
ff1e912cbc39
remove pmainactions and deprecate paddrelactions
Katia Saurfelt <katia.saurfelt@logilab.fr>
parents:
1383
diff
changeset
|
232 |
|
3225
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
233 |
def action_submenu(self, req, rset, id): |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
234 |
return self._test_action(self.vreg['actions'].select(id, req, rset=rset)) |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
235 |
|
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
236 |
def _test_action(self, action): |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
237 |
class fake_menu(list): |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
238 |
@property |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
239 |
def items(self): |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
240 |
return self |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
241 |
class fake_box(object): |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
242 |
def mk_action(self, label, url, **kwargs): |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
243 |
return (label, url) |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
244 |
def box_action(self, action, **kwargs): |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
245 |
return (action.title, action.url()) |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
246 |
submenu = fake_menu() |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
247 |
action.fill_menu(fake_box(), submenu) |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
248 |
return submenu |
464c5b9c6fa0
facilities to test new submenu actions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2920
diff
changeset
|
249 |
|
1394
ff1e912cbc39
remove pmainactions and deprecate paddrelactions
Katia Saurfelt <katia.saurfelt@logilab.fr>
parents:
1383
diff
changeset
|
250 |
def pactions_by_cats(self, req, rset, categories=('addrelated',)): |
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2616
diff
changeset
|
251 |
return [(a.id, a.__class__) for a in self.vreg['actions'].possible_vobjects(req, rset=rset) |
1394
ff1e912cbc39
remove pmainactions and deprecate paddrelactions
Katia Saurfelt <katia.saurfelt@logilab.fr>
parents:
1383
diff
changeset
|
252 |
if a.category in categories] |
1486 | 253 |
|
2613
5e19c2bb370e
R [all] logilab.common 0.44 provides only deprecated
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2476
diff
changeset
|
254 |
paddrelactions = deprecated()(pactions_by_cats) |
1394
ff1e912cbc39
remove pmainactions and deprecate paddrelactions
Katia Saurfelt <katia.saurfelt@logilab.fr>
parents:
1383
diff
changeset
|
255 |
|
0 | 256 |
def pactionsdict(self, req, rset, skipcategories=('addrelated', 'siteactions', 'useractions')): |
257 |
res = {} |
|
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2616
diff
changeset
|
258 |
for a in self.vreg['actions'].possible_vobjects(req, rset=rset): |
0 | 259 |
if a.category not in skipcategories: |
260 |
res.setdefault(a.category, []).append(a.__class__) |
|
261 |
return res |
|
262 |
||
1486 | 263 |
|
0 | 264 |
def remote_call(self, fname, *args): |
265 |
"""remote call simulation""" |
|
266 |
dump = simplejson.dumps |
|
267 |
args = [dump(arg) for arg in args] |
|
1648 | 268 |
req = self.request(fname=fname, pageid='123', arg=args) |
2661
f8df42c9da6b
[vreg api update] remove some deprecation warnings
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
269 |
ctrl = self.vreg['controllers'].select('json', req) |
0 | 270 |
return ctrl.publish(), req |
271 |
||
272 |
# default test setup and teardown ######################################### |
|
1486 | 273 |
|
0 | 274 |
def setup_database(self): |
275 |
pass |
|
276 |
||
277 |
def setUp(self): |
|
278 |
self.restore_connection() |
|
279 |
session = self.session() |
|
280 |
#self.maxeid = self.execute('Any MAX(X)') |
|
281 |
session.set_pool() |
|
282 |
self.maxeid = session.system_sql('SELECT MAX(eid) FROM entities').fetchone()[0] |
|
283 |
self.app = self.env.app |
|
284 |
self.vreg = self.env.app.vreg |
|
285 |
self.schema = self.vreg.schema |
|
286 |
self.vreg.config.mode = 'test' |
|
287 |
# set default-dest-addrs to a dumb email address to avoid mailbox or |
|
288 |
# mail queue pollution |
|
289 |
self.set_option('default-dest-addrs', ['whatever']) |
|
290 |
self.setup_database() |
|
291 |
self.commit() |
|
292 |
MAILBOX[:] = [] # reset mailbox |
|
1486 | 293 |
|
0 | 294 |
@nocoverage |
295 |
def tearDown(self): |
|
296 |
self.rollback() |
|
297 |
# self.env.restore_database() |
|
298 |
self.env.restore_connection() |
|
299 |
self.session().unsafe_execute('DELETE Any X WHERE X eid > %s' % self.maxeid) |
|
300 |
self.commit() |
|
301 |
||
2730
bb6fcb8c5d71
to make cw schemas importable, they have to be installed w/ cw code, not in /usr/share/cubicweb/schemas
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2661
diff
changeset
|
302 |
# global resources accessors ############################################### |
0 | 303 |
|
304 |
# XXX |
|
305 |
try: |
|
306 |
from cubicweb.web import Redirect |
|
307 |
from urllib import unquote |
|
308 |
except ImportError: |
|
309 |
pass # cubicweb-web not installed |
|
310 |
else: |
|
311 |
class ControllerTC(EnvBasedTC): |
|
312 |
def setUp(self): |
|
313 |
super(ControllerTC, self).setUp() |
|
314 |
self.req = self.request() |
|
2661
f8df42c9da6b
[vreg api update] remove some deprecation warnings
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
315 |
self.ctrl = self.vreg['controllers'].select('edit', self.req) |
0 | 316 |
|
317 |
def publish(self, req): |
|
318 |
assert req is self.ctrl.req |
|
319 |
try: |
|
320 |
result = self.ctrl.publish() |
|
321 |
req.cnx.commit() |
|
322 |
except Redirect: |
|
323 |
req.cnx.commit() |
|
324 |
raise |
|
325 |
return result |
|
326 |
||
327 |
def expect_redirect_publish(self, req=None): |
|
328 |
if req is not None: |
|
2661
f8df42c9da6b
[vreg api update] remove some deprecation warnings
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
329 |
self.ctrl = self.vreg['controllers'].select('edit', req) |
0 | 330 |
else: |
331 |
req = self.req |
|
332 |
try: |
|
333 |
res = self.publish(req) |
|
334 |
except Redirect, ex: |
|
335 |
try: |
|
336 |
path, params = ex.location.split('?', 1) |
|
337 |
except: |
|
338 |
path, params = ex.location, "" |
|
339 |
req._url = path |
|
340 |
cleanup = lambda p: (p[0], unquote(p[1])) |
|
341 |
params = dict(cleanup(p.split('=', 1)) for p in params.split('&') if p) |
|
342 |
return req.relative_path(False), params # path.rsplit('/', 1)[-1], params |
|
343 |
else: |
|
344 |
self.fail('expected a Redirect exception') |
|
345 |
||
346 |
||
347 |
def make_late_binding_repo_property(attrname): |
|
348 |
@property |
|
349 |
def late_binding(self): |
|
350 |
"""builds cnx as late as possible""" |
|
351 |
if not hasattr(self, attrname): |
|
352 |
# sets explicit test mode here to avoid autoreload |
|
353 |
from cubicweb.cwconfig import CubicWebConfiguration |
|
354 |
CubicWebConfiguration.mode = 'test' |
|
355 |
cls = self.__class__ |
|
356 |
config = self.repo_config or TestServerConfiguration('data') |
|
357 |
cls._repo, cls._cnx = init_test_database('sqlite', config=config) |
|
358 |
return getattr(self, attrname) |
|
359 |
return late_binding |
|
360 |
||
361 |
||
362 |
class autorepo(type): |
|
363 |
"""automatically set repository on RepositoryBasedTC subclasses if necessary |
|
364 |
""" |
|
365 |
def __new__(mcs, name, bases, classdict): |
|
366 |
repo = classdict.get('repo') |
|
367 |
# try to find repo in one of the base classes |
|
368 |
if repo is None: |
|
369 |
for base in bases: |
|
370 |
repo = getattr(base, 'repo', None) |
|
371 |
if repo is not None: |
|
372 |
classdict['repo'] = repo |
|
373 |
break |
|
374 |
if name != 'RepositoryBasedTC' and not classdict.get('repo'): |
|
375 |
classdict['repo'] = make_late_binding_repo_property('_repo') |
|
376 |
classdict['cnx'] = make_late_binding_repo_property('_cnx') |
|
377 |
return super(autorepo, mcs).__new__(mcs, name, bases, classdict) |
|
378 |
||
379 |
||
380 |
class RepositoryBasedTC(TestCase): |
|
381 |
"""abstract class for test using direct repository connections |
|
382 |
""" |
|
383 |
__metaclass__ = autorepo |
|
384 |
repo_config = None # set a particular config instance if necessary |
|
1486 | 385 |
|
0 | 386 |
# user / session management ############################################### |
387 |
||
388 |
def create_user(self, user, groups=('users',), password=None, commit=True): |
|
389 |
if password is None: |
|
390 |
password = user |
|
2920
64322aa83a1d
start a new workflow engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2730
diff
changeset
|
391 |
eid = self.execute('INSERT CWUser X: X login %(x)s, X upassword %(p)s', |
0 | 392 |
{'x': unicode(user), 'p': password})[0][0] |
393 |
groups = ','.join(repr(group) for group in groups) |
|
394 |
self.execute('SET X in_group Y WHERE X eid %%(x)s, Y name IN (%s)' % groups, |
|
395 |
{'x': eid}) |
|
396 |
if commit: |
|
397 |
self.commit() |
|
1486 | 398 |
self.session.reset_pool() |
0 | 399 |
return eid |
1486 | 400 |
|
0 | 401 |
def login(self, login, password=None): |
402 |
cnx = repo_connect(self.repo, unicode(login), password or login, |
|
403 |
ConnectionProperties('inmemory')) |
|
404 |
self.cnxs.append(cnx) |
|
405 |
return cnx |
|
406 |
||
407 |
def current_session(self): |
|
408 |
return self.repo._sessions[self.cnxs[-1].sessionid] |
|
1486 | 409 |
|
0 | 410 |
def restore_connection(self): |
411 |
assert len(self.cnxs) == 1, self.cnxs |
|
412 |
cnx = self.cnxs.pop() |
|
413 |
try: |
|
414 |
cnx.close() |
|
415 |
except Exception, ex: |
|
416 |
print "exception occured while closing connection", ex |
|
1486 | 417 |
|
0 | 418 |
# db api ################################################################## |
419 |
||
420 |
def execute(self, rql, args=None, eid_key=None): |
|
421 |
assert self.session.id == self.cnxid |
|
422 |
rset = self.__execute(self.cnxid, rql, args, eid_key) |
|
423 |
rset.vreg = self.vreg |
|
424 |
rset.req = self.session |
|
425 |
# call to set_pool is necessary to avoid pb when using |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2298
diff
changeset
|
426 |
# instance entities for convenience |
0 | 427 |
self.session.set_pool() |
428 |
return rset |
|
1486 | 429 |
|
0 | 430 |
def commit(self): |
431 |
self.__commit(self.cnxid) |
|
1486 | 432 |
self.session.set_pool() |
433 |
||
0 | 434 |
def rollback(self): |
435 |
self.__rollback(self.cnxid) |
|
1486 | 436 |
self.session.set_pool() |
437 |
||
0 | 438 |
def close(self): |
439 |
self.__close(self.cnxid) |
|
440 |
||
441 |
# other utilities ######################################################### |
|
1486 | 442 |
|
0 | 443 |
def set_debug(self, debugmode): |
444 |
from cubicweb.server import set_debug |
|
445 |
set_debug(debugmode) |
|
1486 | 446 |
|
0 | 447 |
def set_option(self, optname, value): |
448 |
self.vreg.config.global_set_option(optname, value) |
|
1486 | 449 |
|
0 | 450 |
def add_entity(self, etype, **kwargs): |
451 |
restrictions = ', '.join('X %s %%(%s)s' % (key, key) for key in kwargs) |
|
452 |
rql = 'INSERT %s X' % etype |
|
453 |
if kwargs: |
|
454 |
rql += ': %s' % ', '.join('X %s %%(%s)s' % (key, key) for key in kwargs) |
|
455 |
rset = self.execute(rql, kwargs) |
|
456 |
return rset.get_entity(0, 0) |
|
457 |
||
458 |
def default_user_password(self): |
|
459 |
config = self.repo.config #TestConfiguration('data') |
|
460 |
user = unicode(config.sources()['system']['db-user']) |
|
461 |
passwd = config.sources()['system']['db-password'] |
|
462 |
return user, passwd |
|
1486 | 463 |
|
0 | 464 |
def close_connections(self): |
465 |
for cnx in self.cnxs: |
|
466 |
try: |
|
467 |
cnx.rollback() |
|
468 |
cnx.close() |
|
469 |
except: |
|
470 |
continue |
|
471 |
self.cnxs = [] |
|
472 |
||
473 |
pactions = EnvBasedTC.pactions.im_func |
|
474 |
pactionsdict = EnvBasedTC.pactionsdict.im_func |
|
1486 | 475 |
|
0 | 476 |
# default test setup and teardown ######################################### |
1486 | 477 |
|
0 | 478 |
def _prepare(self): |
479 |
MAILBOX[:] = [] # reset mailbox |
|
480 |
if hasattr(self, 'cnxid'): |
|
481 |
return |
|
482 |
repo = self.repo |
|
483 |
self.__execute = repo.execute |
|
484 |
self.__commit = repo.commit |
|
485 |
self.__rollback = repo.rollback |
|
486 |
self.__close = repo.close |
|
976 | 487 |
self.cnxid = self.cnx.sessionid |
0 | 488 |
self.session = repo._sessions[self.cnxid] |
489 |
self.cnxs = [] |
|
490 |
# reset caches, they may introduce bugs among tests |
|
491 |
repo._type_source_cache = {} |
|
492 |
repo._extid_cache = {} |
|
493 |
repo.querier._rql_cache = {} |
|
494 |
for source in repo.sources: |
|
495 |
source.reset_caches() |
|
496 |
for s in repo.sources: |
|
497 |
if hasattr(s, '_cache'): |
|
498 |
s._cache = {} |
|
499 |
||
500 |
@property |
|
501 |
def config(self): |
|
502 |
return self.repo.config |
|
503 |
||
504 |
@property |
|
505 |
def vreg(self): |
|
506 |
return self.repo.vreg |
|
507 |
||
508 |
@property |
|
509 |
def schema(self): |
|
510 |
return self.repo.schema |
|
1486 | 511 |
|
0 | 512 |
def setUp(self): |
513 |
self._prepare() |
|
514 |
self.session.set_pool() |
|
515 |
self.maxeid = self.session.system_sql('SELECT MAX(eid) FROM entities').fetchone()[0] |
|
1486 | 516 |
|
1263 | 517 |
def tearDown(self): |
0 | 518 |
self.close_connections() |
519 |
self.rollback() |
|
520 |
self.session.unsafe_execute('DELETE Any X WHERE X eid > %(x)s', {'x': self.maxeid}) |
|
521 |
self.commit() |
|
1486 | 522 |