unittest_views_basecontrollers.py 37.2 KB
Newer Older
1
# copyright 2003-2012 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
2
3
4
5
6
7
8
9
10
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of CubicWeb.
#
# CubicWeb is free software: you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
11
# CubicWeb is distributed in the hope that it will be useful, but WITHOUT
12
13
14
15
16
17
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
18
"""cubicweb.web.views.basecontrollers unit tests"""
Adrien Di Mascio's avatar
Adrien Di Mascio committed
19

20
21
22
23
24
25
from urlparse import urlsplit, urlunsplit, urljoin
# parse_qs is deprecated in cgi and has been moved to urlparse in Python 2.6
try:
    from urlparse import parse_qs as url_parse_query
except ImportError:
    from cgi import parse_qs as url_parse_query
26
from logilab.common.testlib import unittest_main, mock_object
27
from logilab.common.decorators import monkeypatch
Adrien Di Mascio's avatar
Adrien Di Mascio committed
28

29
30
from cubicweb import Binary, NoSelectableObject, ValidationError
from cubicweb.view import STRICT_DOCTYPE
31
from cubicweb.devtools.testlib import CubicWebTC
32
from cubicweb.utils import json_dumps
Sylvain Thénault's avatar
Sylvain Thénault committed
33
from cubicweb.uilib import rql_for_eid
34
from cubicweb.web import INTERNAL_FIELD_VALUE, Redirect, RequestError, RemoteCallFailed
35
36
import cubicweb.server.session
from cubicweb.server.session import Transaction as OldTransaction
37
from cubicweb.entities.authobjs import CWUser
Sylvain Thénault's avatar
Sylvain Thénault committed
38
from cubicweb.web.views.autoform import get_pending_inserts, get_pending_deletes
39
40
from cubicweb.web.views.basecontrollers import JSonController, xhtmlize, jsonize
from cubicweb.web.views.ajaxcontroller import ajaxfunc, AjaxFunction
41
import cubicweb.transaction as tx
42

Sylvain Thénault's avatar
Sylvain Thénault committed
43
44
u = unicode

Sylvain Thénault's avatar
Sylvain Thénault committed
45
46
def req_form(user):
    return {'eid': [str(user.eid)],
47
            '_cw_entity_fields:%s' % user.eid: '_cw_generic_field',
Sylvain Thénault's avatar
Sylvain Thénault committed
48
49
            '__type:%s' % user.eid: user.__regid__
            }
Adrien Di Mascio's avatar
Adrien Di Mascio committed
50

51
class EditControllerTC(CubicWebTC):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
52
    def setUp(self):
53
        CubicWebTC.setUp(self)
54
        self.assertTrue('users' in self.schema.eschema('CWGroup').get_groups('read'))
55

Adrien Di Mascio's avatar
Adrien Di Mascio committed
56
    def tearDown(self):
57
        CubicWebTC.tearDown(self)
58
        self.assertTrue('users' in self.schema.eschema('CWGroup').get_groups('read'))
59

Adrien Di Mascio's avatar
Adrien Di Mascio committed
60
61
62
    def test_noparam_edit(self):
        """check behaviour of this controller without any form parameter
        """
63
64
65
        with self.assertRaises(ValidationError) as cm:
            self.ctrl_publish(self.request())
        self.assertEqual(cm.exception.errors, {None: u'no selected entities'})
66

Adrien Di Mascio's avatar
Adrien Di Mascio committed
67
68
    def test_validation_unique(self):
        """test creation of two linked entities
69
        """
Adrien Di Mascio's avatar
Adrien Di Mascio committed
70
        user = self.user()
71
72
        req = self.request()
        req.form = {'eid': 'X', '__type:X': 'CWUser',
73
                    '_cw_entity_fields:X': 'login-subject,upassword-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
74
75
76
                    'login-subject:X': u'admin',
                    'upassword-subject:X': u'toto',
                    'upassword-subject-confirm:X': u'toto',
77
                    }
78
79
        with self.assertRaises(ValidationError) as cm:
            self.ctrl_publish(req)
80
        cm.exception.translate(unicode)
81
        self.assertEqual(cm.exception.errors, {'login-subject': 'the value "admin" is already used, use another one'})
Adrien Di Mascio's avatar
Adrien Di Mascio committed
82
83
84
85
86

    def test_user_editing_itself(self):
        """checking that a manager user can edit itself
        """
        user = self.user()
Sylvain Thénault's avatar
Sylvain Thénault committed
87
        basegroups = [u(eid) for eid, in self.execute('CWGroup G WHERE X in_group G, X eid %(x)s', {'x': user.eid})]
88
        groupeids = [eid for eid, in self.execute('CWGroup G WHERE G name in ("managers", "users")')]
Sylvain Thénault's avatar
Sylvain Thénault committed
89
        groups = [u(eid) for eid in groupeids]
90
        req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
91
        eid = u(user.eid)
92
        req.form = {
Sylvain Thénault's avatar
Sylvain Thénault committed
93
            'eid': eid, '__type:'+eid: 'CWUser',
94
            '_cw_entity_fields:'+eid: 'login-subject,firstname-subject,surname-subject,in_group-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
95
96
97
98
            'login-subject:'+eid:     u(user.login),
            'surname-subject:'+eid: u'Th\xe9nault',
            'firstname-subject:'+eid:   u'Sylvain',
            'in_group-subject:'+eid:  groups,
Adrien Di Mascio's avatar
Adrien Di Mascio committed
99
            }
100
        path, params = self.expect_redirect_handle_request(req, 'edit')
101
        e = self.execute('Any X WHERE X eid %(x)s', {'x': user.eid}).get_entity(0, 0)
102
103
104
105
        self.assertEqual(e.firstname, u'Sylvain')
        self.assertEqual(e.surname, u'Th\xe9nault')
        self.assertEqual(e.login, user.login)
        self.assertEqual([g.eid for g in e.in_group], groupeids)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
106
107
108

    def test_user_can_change_its_password(self):
        req = self.request()
109
110
        user = self.create_user(req, 'user')
        cnx = self.login('user')
Sylvain Thénault's avatar
Sylvain Thénault committed
111
        eid = u(user.eid)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
112
        req.form = {
Sylvain Thénault's avatar
Sylvain Thénault committed
113
114
            'eid': eid, '__maineid' : eid,
            '__type:'+eid: 'CWUser',
115
            '_cw_entity_fields:'+eid: 'upassword-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
116
117
            'upassword-subject:'+eid: 'tournicoton',
            'upassword-subject-confirm:'+eid: 'tournicoton',
Adrien Di Mascio's avatar
Adrien Di Mascio committed
118
            }
119
        path, params = self.expect_redirect_handle_request(req, 'edit')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
120
        cnx.commit() # commit to check we don't get late validation error for instance
121
        self.assertEqual(path, 'cwuser/user')
122
        self.assertFalse('vid' in params)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
123

Sylvain Thénault's avatar
Sylvain Thénault committed
124
    def test_user_editing_itself_no_relation(self):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
125
126
127
128
        """checking we can edit an entity without specifying some required
        relations (meaning no changes)
        """
        user = self.user()
Sylvain Thénault's avatar
Sylvain Thénault committed
129
        groupeids = [g.eid for g in user.in_group]
130
        req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
131
        eid = u(user.eid)
132
        req.form = {
Sylvain Thénault's avatar
Sylvain Thénault committed
133
134
            'eid':       eid,
            '__type:'+eid:    'CWUser',
135
            '_cw_entity_fields:'+eid: 'login-subject,firstname-subject,surname-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
136
137
138
            'login-subject:'+eid:     u(user.login),
            'firstname-subject:'+eid: u'Th\xe9nault',
            'surname-subject:'+eid:   u'Sylvain',
Adrien Di Mascio's avatar
Adrien Di Mascio committed
139
            }
140
        path, params = self.expect_redirect_handle_request(req, 'edit')
141
        e = self.execute('Any X WHERE X eid %(x)s', {'x': user.eid}).get_entity(0, 0)
142
143
144
145
146
        self.assertEqual(e.login, user.login)
        self.assertEqual(e.firstname, u'Th\xe9nault')
        self.assertEqual(e.surname, u'Sylvain')
        self.assertEqual([g.eid for g in e.in_group], groupeids)
        self.assertEqual(e.cw_adapt_to('IWorkflowable').state, 'activated')
147
148


Adrien Di Mascio's avatar
Adrien Di Mascio committed
149
    def test_create_multiple_linked(self):
150
        gueid = self.execute('CWGroup G WHERE G name "users"')[0][0]
151
        req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
152
        req.form = {'eid': ['X', 'Y'], '__maineid' : 'X',
153

154
                    '__type:X': 'CWUser',
155
                    '_cw_entity_fields:X': 'login-subject,upassword-subject,surname-subject,in_group-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
156
157
158
159
                    'login-subject:X': u'adim',
                    'upassword-subject:X': u'toto', 'upassword-subject-confirm:X': u'toto',
                    'surname-subject:X': u'Di Mascio',
                    'in_group-subject:X': u(gueid),
160

161
                    '__type:Y': 'EmailAddress',
162
                    '_cw_entity_fields:Y': 'address-subject,use_email-object',
Sylvain Thénault's avatar
Sylvain Thénault committed
163
164
                    'address-subject:Y': u'dima@logilab.fr',
                    'use_email-object:Y': 'X',
165
                    }
166
        path, params = self.expect_redirect_handle_request(req, 'edit')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
167
        # should be redirected on the created person
168
        self.assertEqual(path, 'cwuser/adim')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
169
        e = self.execute('Any P WHERE P surname "Di Mascio"').get_entity(0, 0)
170
        self.assertEqual(e.surname, 'Di Mascio')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
171
        email = e.use_email[0]
172
        self.assertEqual(email.address, 'dima@logilab.fr')
173

Adrien Di Mascio's avatar
Adrien Di Mascio committed
174
    def test_edit_multiple_linked(self):
175
        req = self.request()
176
        peid = u(self.create_user(req, 'adim').eid)
Sylvain Thénault's avatar
Sylvain Thénault committed
177
        req.form = {'eid': [peid, 'Y'], '__maineid': peid,
178

Sylvain Thénault's avatar
Sylvain Thénault committed
179
                    '__type:'+peid: u'CWUser',
180
                    '_cw_entity_fields:'+peid: u'surname-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
181
                    'surname-subject:'+peid: u'Di Masci',
182

Sylvain Thénault's avatar
Sylvain Thénault committed
183
                    '__type:Y': u'EmailAddress',
184
                    '_cw_entity_fields:Y': u'address-subject,use_email-object',
Sylvain Thénault's avatar
Sylvain Thénault committed
185
186
                    'address-subject:Y': u'dima@logilab.fr',
                    'use_email-object:Y': peid,
187
                    }
188
        path, params = self.expect_redirect_handle_request(req, 'edit')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
189
        # should be redirected on the created person
190
        self.assertEqual(path, 'cwuser/adim')
Sylvain Thénault's avatar
Sylvain Thénault committed
191
        e = self.execute('Any P WHERE P surname "Di Masci"').get_entity(0, 0)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
192
        email = e.use_email[0]
193
        self.assertEqual(email.address, 'dima@logilab.fr')
194

Sylvain Thénault's avatar
Sylvain Thénault committed
195
        emaileid = u(email.eid)
196
        req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
197
198
199
        req.form = {'eid': [peid, emaileid],

                    '__type:'+peid: u'CWUser',
200
                    '_cw_entity_fields:'+peid: u'surname-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
201
202
203
                    'surname-subject:'+peid: u'Di Masci',

                    '__type:'+emaileid: u'EmailAddress',
204
                    '_cw_entity_fields:'+emaileid: u'address-subject,use_email-object',
Sylvain Thénault's avatar
Sylvain Thénault committed
205
206
207
                    'address-subject:'+emaileid: u'adim@logilab.fr',
                    'use_email-object:'+emaileid: peid,
                    }
208
        path, params = self.expect_redirect_handle_request(req, 'edit')
209
        email.cw_clear_all_caches()
210
        self.assertEqual(email.address, 'adim@logilab.fr')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
211

212

Adrien Di Mascio's avatar
Adrien Di Mascio committed
213
214
    def test_password_confirm(self):
        """test creation of two linked entities
215
        """
Adrien Di Mascio's avatar
Adrien Di Mascio committed
216
        user = self.user()
217
        req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
218
219
        req.form = {'eid': 'X',
                    '__cloned_eid:X': u(user.eid), '__type:X': 'CWUser',
220
                    '_cw_entity_fields:X': 'login-subject,upassword-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
221
222
                    'login-subject:X': u'toto',
                    'upassword-subject:X': u'toto',
223
                    }
224
225
226
        with self.assertRaises(ValidationError) as cm:
            self.ctrl_publish(req)
        self.assertEqual(cm.exception.errors, {'upassword-subject': u'password and confirmation don\'t match'})
227
        req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
228
        req.form = {'__cloned_eid:X': u(user.eid),
229
                    'eid': 'X', '__type:X': 'CWUser',
230
                    '_cw_entity_fields:X': 'login-subject,upassword-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
231
232
233
                    'login-subject:X': u'toto',
                    'upassword-subject:X': u'toto',
                    'upassword-subject-confirm:X': u'tutu',
234
                    }
235
236
237
        with self.assertRaises(ValidationError) as cm:
            self.ctrl_publish(req)
        self.assertEqual(cm.exception.errors, {'upassword-subject': u'password and confirmation don\'t match'})
Adrien Di Mascio's avatar
Adrien Di Mascio committed
238
239
240


    def test_interval_bound_constraint_success(self):
Sylvain Thénault's avatar
Sylvain Thénault committed
241
        feid = self.execute('INSERT File X: X data_name "toto.txt", X data %(data)s',
Adrien Di Mascio's avatar
Adrien Di Mascio committed
242
                            {'data': Binary('yo')})[0][0]
243
        self.commit()
244
        req = self.request(rollbackfirst=True)
245
246
        req.form = {'eid': ['X'],
                    '__type:X': 'Salesterm',
247
                    '_cw_entity_fields:X': 'amount-subject,described_by_test-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
248
249
                    'amount-subject:X': u'-10',
                    'described_by_test-subject:X': u(feid),
250
                }
251
252
        with self.assertRaises(ValidationError) as cm:
            self.ctrl_publish(req)
253
        cm.exception.translate(unicode)
254
        self.assertEqual(cm.exception.errors, {'amount-subject': 'value -10 must be >= 0'})
255
        req = self.request(rollbackfirst=True)
256
257
        req.form = {'eid': ['X'],
                    '__type:X': 'Salesterm',
258
                    '_cw_entity_fields:X': 'amount-subject,described_by_test-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
259
260
                    'amount-subject:X': u'110',
                    'described_by_test-subject:X': u(feid),
261
                    }
262
263
        with self.assertRaises(ValidationError) as cm:
            self.ctrl_publish(req)
264
        cm.exception.translate(unicode)
265
        self.assertEqual(cm.exception.errors, {'amount-subject': 'value 110 must be <= 100'})
266
        req = self.request(rollbackfirst=True)
267
268
        req.form = {'eid': ['X'],
                    '__type:X': 'Salesterm',
269
                    '_cw_entity_fields:X': 'amount-subject,described_by_test-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
270
271
                    'amount-subject:X': u'10',
                    'described_by_test-subject:X': u(feid),
272
                    }
273
        self.expect_redirect_handle_request(req, 'edit')
274
        # should be redirected on the created
Adrien Di Mascio's avatar
Adrien Di Mascio committed
275
276
        #eid = params['rql'].split()[-1]
        e = self.execute('Salesterm X').get_entity(0, 0)
277
        self.assertEqual(e.amount, 10)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
278
279
280

    def test_req_pending_insert(self):
        """make sure req's pending insertions are taken into account"""
Sylvain Thénault's avatar
Sylvain Thénault committed
281
        tmpgroup = self.request().create_entity('CWGroup', name=u"test")
Adrien Di Mascio's avatar
Adrien Di Mascio committed
282
        user = self.user()
Sylvain Thénault's avatar
Sylvain Thénault committed
283
        req = self.request(**req_form(user))
284
        req.session.data['pending_insert'] = set([(user.eid, 'in_group', tmpgroup.eid)])
285
        path, params = self.expect_redirect_handle_request(req, 'edit')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
286
287
        usergroups = [gname for gname, in
                      self.execute('Any N WHERE G name N, U in_group G, U eid %(u)s', {'u': user.eid})]
288
289
        self.assertItemsEqual(usergroups, ['managers', 'test'])
        self.assertEqual(get_pending_inserts(req), [])
Adrien Di Mascio's avatar
Adrien Di Mascio committed
290
291
292
293
294


    def test_req_pending_delete(self):
        """make sure req's pending deletions are taken into account"""
        user = self.user()
295
        groupeid = self.execute('INSERT CWGroup G: G name "test", U in_group G WHERE U eid %(x)s',
Adrien Di Mascio's avatar
Adrien Di Mascio committed
296
297
298
299
                                {'x': user.eid})[0][0]
        usergroups = [gname for gname, in
                      self.execute('Any N WHERE G name N, U in_group G, U eid %(u)s', {'u': user.eid})]
        # just make sure everything was set correctly
300
        self.assertItemsEqual(usergroups, ['managers', 'test'])
Adrien Di Mascio's avatar
Adrien Di Mascio committed
301
        # now try to delete the relation
Sylvain Thénault's avatar
Sylvain Thénault committed
302
        req = self.request(**req_form(user))
303
        req.session.data['pending_delete'] = set([(user.eid, 'in_group', groupeid)])
304
        path, params = self.expect_redirect_handle_request(req, 'edit')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
305
306
        usergroups = [gname for gname, in
                      self.execute('Any N WHERE G name N, U in_group G, U eid %(u)s', {'u': user.eid})]
307
308
        self.assertItemsEqual(usergroups, ['managers'])
        self.assertEqual(get_pending_deletes(req), [])
Adrien Di Mascio's avatar
Adrien Di Mascio committed
309
310
311

    def test_redirect_apply_button(self):
        redirectrql = rql_for_eid(4012) # whatever
312
313
        req = self.request()
        req.form = {
Sylvain Thénault's avatar
Sylvain Thénault committed
314
            'eid': 'A', '__maineid' : 'A',
315
            '__type:A': 'BlogEntry', '_cw_entity_fields:A': 'content-subject,title-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
316
317
            'content-subject:A': u'"13:03:43"',
            'title-subject:A': u'huuu',
318
319
320
321
322
323
            '__redirectrql': redirectrql,
            '__redirectvid': 'primary',
            '__redirectparams': 'toto=tutu&tata=titi',
            '__form_id': 'edition',
            '__action_apply': '',
            }
324
        path, params = self.expect_redirect_handle_request(req, 'edit')
325
        self.assertTrue(path.startswith('blogentry/'))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
326
        eid = path.split('/')[1]
327
        self.assertEqual(params['vid'], 'edition')
328
        self.assertNotEqual(int(eid), 4012)
329
330
331
        self.assertEqual(params['__redirectrql'], redirectrql)
        self.assertEqual(params['__redirectvid'], 'primary')
        self.assertEqual(params['__redirectparams'], 'toto=tutu&tata=titi')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
332
333
334

    def test_redirect_ok_button(self):
        redirectrql = rql_for_eid(4012) # whatever
335
336
        req = self.request()
        req.form = {
Sylvain Thénault's avatar
Sylvain Thénault committed
337
            'eid': 'A', '__maineid' : 'A',
338
            '__type:A': 'BlogEntry', '_cw_entity_fields:A': 'content-subject,title-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
339
340
            'content-subject:A': u'"13:03:43"',
            'title-subject:A': u'huuu',
341
342
343
344
345
            '__redirectrql': redirectrql,
            '__redirectvid': 'primary',
            '__redirectparams': 'toto=tutu&tata=titi',
            '__form_id': 'edition',
            }
346
        path, params = self.expect_redirect_handle_request(req, 'edit')
347
348
349
350
351
        self.assertEqual(path, 'view')
        self.assertEqual(params['rql'], redirectrql)
        self.assertEqual(params['vid'], 'primary')
        self.assertEqual(params['tata'], 'titi')
        self.assertEqual(params['toto'], 'tutu')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
352
353

    def test_redirect_delete_button(self):
354
        req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
355
        eid = req.create_entity('BlogEntry', title=u'hop', content=u'hop').eid
Sylvain Thénault's avatar
Sylvain Thénault committed
356
        req.form = {'eid': u(eid), '__type:%s'%eid: 'BlogEntry',
357
                    '__action_delete': ''}
358
        path, params = self.expect_redirect_handle_request(req, 'edit')
359
        self.assertEqual(path, 'blogentry')
Sylvain Thénault's avatar
Sylvain Thénault committed
360
        self.assertIn('_cwmsgid', params)
Sylvain Thénault's avatar
Sylvain Thénault committed
361
        eid = req.create_entity('EmailAddress', address=u'hop@logilab.fr').eid
Adrien Di Mascio's avatar
Adrien Di Mascio committed
362
        self.execute('SET X use_email E WHERE E eid %(e)s, X eid %(x)s',
363
                     {'x': self.session.user.eid, 'e': eid})
Adrien Di Mascio's avatar
Adrien Di Mascio committed
364
        self.commit()
Sylvain Thénault's avatar
Sylvain Thénault committed
365
        req = req
Sylvain Thénault's avatar
Sylvain Thénault committed
366
        req.form = {'eid': u(eid), '__type:%s'%eid: 'EmailAddress',
367
                    '__action_delete': ''}
368
        path, params = self.expect_redirect_handle_request(req, 'edit')
369
        self.assertEqual(path, 'cwuser/admin')
Sylvain Thénault's avatar
Sylvain Thénault committed
370
        self.assertIn('_cwmsgid', params)
Sylvain Thénault's avatar
Sylvain Thénault committed
371
372
        eid1 = req.create_entity('BlogEntry', title=u'hop', content=u'hop').eid
        eid2 = req.create_entity('EmailAddress', address=u'hop@logilab.fr').eid
373
        req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
374
        req.form = {'eid': [u(eid1), u(eid2)],
375
376
377
                    '__type:%s'%eid1: 'BlogEntry',
                    '__type:%s'%eid2: 'EmailAddress',
                    '__action_delete': ''}
378
        path, params = self.expect_redirect_handle_request(req, 'edit')
379
        self.assertEqual(path, 'view')
Sylvain Thénault's avatar
Sylvain Thénault committed
380
        self.assertIn('_cwmsgid', params)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
381

382
383
384
385
386
387
388
389
390
391
392
393
    def test_simple_copy(self):
        req = self.request()
        blog = req.create_entity('Blog', title=u'my-blog')
        blogentry = req.create_entity('BlogEntry', title=u'entry1',
                                      content=u'content1', entry_of=blog)
        req = self.request()
        req.form = {'__maineid' : 'X', 'eid': 'X',
                    '__cloned_eid:X': blogentry.eid, '__type:X': 'BlogEntry',
                    '_cw_entity_fields:X': 'title-subject,content-subject',
                    'title-subject:X': u'entry1-copy',
                    'content-subject:X': u'content1',
                    }
394
        self.expect_redirect_handle_request(req, 'edit')
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
        blogentry2 = req.find_one_entity('BlogEntry', title=u'entry1-copy')
        self.assertEqual(blogentry2.entry_of[0].eid, blog.eid)

    def test_skip_copy_for(self):
        req = self.request()
        blog = req.create_entity('Blog', title=u'my-blog')
        blogentry = req.create_entity('BlogEntry', title=u'entry1',
                                      content=u'content1', entry_of=blog)
        blogentry.__class__.cw_skip_copy_for = [('entry_of', 'subject')]
        try:
            req = self.request()
            req.form = {'__maineid' : 'X', 'eid': 'X',
                        '__cloned_eid:X': blogentry.eid, '__type:X': 'BlogEntry',
                        '_cw_entity_fields:X': 'title-subject,content-subject',
                        'title-subject:X': u'entry1-copy',
                        'content-subject:X': u'content1',
                        }
412
            self.expect_redirect_handle_request(req, 'edit')
413
414
415
416
417
418
            blogentry2 = req.find_one_entity('BlogEntry', title=u'entry1-copy')
            # entry_of should not be copied
            self.assertEqual(len(blogentry2.entry_of), 0)
        finally:
            blogentry.__class__.cw_skip_copy_for = []

Adrien Di Mascio's avatar
Adrien Di Mascio committed
419
    def test_nonregr_eetype_etype_editing(self):
420
        """non-regression test checking that a manager user can edit a CWEType entity
Adrien Di Mascio's avatar
Adrien Di Mascio committed
421
        """
422
        groupeids = sorted(eid for eid, in self.execute('CWGroup G WHERE G name in ("managers", "users")'))
Sylvain Thénault's avatar
Sylvain Thénault committed
423
424
425
426
        groups = [u(eid) for eid in groupeids]
        cwetypeeid = self.execute('CWEType X WHERE X name "CWEType"')[0][0]
        basegroups = [u(eid) for eid, in self.execute('CWGroup G WHERE X read_permission G, X eid %(x)s', {'x': cwetypeeid})]
        cwetypeeid = u(cwetypeeid)
427
428
        req = self.request()
        req.form = {
Sylvain Thénault's avatar
Sylvain Thénault committed
429
430
            'eid':      cwetypeeid,
            '__type:'+cwetypeeid:  'CWEType',
431
            '_cw_entity_fields:'+cwetypeeid: 'name-subject,final-subject,description-subject,read_permission-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
432
            'name-subject:'+cwetypeeid:     u'CWEType',
Sylvain Thénault's avatar
Sylvain Thénault committed
433
            'final-subject:'+cwetypeeid:    '',
Sylvain Thénault's avatar
Sylvain Thénault committed
434
435
            'description-subject:'+cwetypeeid:     u'users group',
            'read_permission-subject:'+cwetypeeid:  groups,
436
            }
Adrien Di Mascio's avatar
Adrien Di Mascio committed
437
        try:
438
            path, params = self.expect_redirect_handle_request(req, 'edit')
439
            e = self.execute('Any X WHERE X eid %(x)s', {'x': cwetypeeid}).get_entity(0, 0)
440
441
            self.assertEqual(e.name, 'CWEType')
            self.assertEqual(sorted(g.eid for g in e.read_permission), groupeids)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
442
443
        finally:
            # restore
444
            self.execute('SET X read_permission Y WHERE X name "CWEType", Y eid IN (%s), NOT X read_permission Y' % (','.join(basegroups)))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
445
            self.commit()
446

Adrien Di Mascio's avatar
Adrien Di Mascio committed
447
448
449
450
    def test_nonregr_strange_text_input(self):
        """non-regression test checking text input containing "13:03:43"

        this seems to be postgres (tsearch?) specific
451
        """
452
453
        req = self.request()
        req.form = {
Sylvain Thénault's avatar
Sylvain Thénault committed
454
            'eid': 'A', '__maineid' : 'A',
455
            '__type:A': 'BlogEntry', '_cw_entity_fields:A': 'title-subject,content-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
456
457
            'title-subject:A': u'"13:03:40"',
            'content-subject:A': u'"13:03:43"',}
458
        path, params = self.expect_redirect_handle_request(req, 'edit')
459
        self.assertTrue(path.startswith('blogentry/'))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
460
        eid = path.split('/')[1]
461
        e = self.execute('Any C, T WHERE C eid %(x)s, C content T', {'x': eid}).get_entity(0, 0)
462
463
        self.assertEqual(e.title, '"13:03:40"')
        self.assertEqual(e.content, '"13:03:43"')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
464
465
466


    def test_nonregr_multiple_empty_email_addr(self):
467
        gueid = self.execute('CWGroup G WHERE G name "users"')[0][0]
468
469
        req = self.request()
        req.form = {'eid': ['X', 'Y'],
470

471
                    '__type:X': 'CWUser',
472
                    '_cw_entity_fields:X': 'login-subject,upassword-subject,in_group-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
473
474
475
                    'login-subject:X': u'adim',
                    'upassword-subject:X': u'toto', 'upassword-subject-confirm:X': u'toto',
                    'in_group-subject:X': `gueid`,
476

477
                    '__type:Y': 'EmailAddress',
478
                    '_cw_entity_fields:Y': 'address-subject,alias-subject,use_email-object',
Sylvain Thénault's avatar
Sylvain Thénault committed
479
480
481
                    'address-subject:Y': u'',
                    'alias-subject:Y': u'',
                    'use_email-object:Y': 'X',
482
                    }
483
484
485
        with self.assertRaises(ValidationError) as cm:
            self.ctrl_publish(req)
        self.assertEqual(cm.exception.errors, {'address-subject': u'required field'})
Adrien Di Mascio's avatar
Adrien Di Mascio committed
486
487
488

    def test_nonregr_copy(self):
        user = self.user()
489
        req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
490
491
        req.form = {'__maineid' : 'X', 'eid': 'X',
                    '__cloned_eid:X': user.eid, '__type:X': 'CWUser',
492
                    '_cw_entity_fields:X': 'login-subject,upassword-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
493
494
                    'login-subject:X': u'toto',
                    'upassword-subject:X': u'toto', 'upassword-subject-confirm:X': u'toto',
495
                    }
496
        path, params = self.expect_redirect_handle_request(req, 'edit')
497
        self.assertEqual(path, 'cwuser/toto')
498
        e = self.execute('Any X WHERE X is CWUser, X login "toto"').get_entity(0, 0)
499
500
        self.assertEqual(e.login, 'toto')
        self.assertEqual(e.in_group[0].name, 'managers')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
501
502
503


    def test_nonregr_rollback_on_validation_error(self):
504
505
        req = self.request()
        p = self.create_user(req, "doe")
Adrien Di Mascio's avatar
Adrien Di Mascio committed
506
507
508
509
        # do not try to skip 'primary_email' for this test
        old_skips = p.__class__.skip_copy_for
        p.__class__.skip_copy_for = ()
        try:
Sylvain Thénault's avatar
Sylvain Thénault committed
510
            e = self.request().create_entity('EmailAddress', address=u'doe@doe.com')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
511
512
            self.execute('SET P use_email E, P primary_email E WHERE P eid %(p)s, E eid %(e)s',
                         {'p' : p.eid, 'e' : e.eid})
513
            req = self.request()
Sylvain Thénault's avatar
Sylvain Thénault committed
514
515
            req.form = {'eid': 'X',
                        '__cloned_eid:X': p.eid, '__type:X': 'CWUser',
516
                        '_cw_entity_fields:X': 'login-subject,surname-subject',
Sylvain Thénault's avatar
Sylvain Thénault committed
517
518
                        'login-subject': u'dodo',
                        'surname-subject:X': u'Boom',
519
                        '__errorurl' : "whatever but required",
Sylvain Thénault's avatar
Sylvain Thénault committed
520
                        }
Adrien Di Mascio's avatar
Adrien Di Mascio committed
521
522
523
524
525
            # try to emulate what really happens in the web application
            # 1/ validate form => EditController.publish raises a ValidationError
            #    which fires a Redirect
            # 2/ When re-publishing the copy form, the publisher implicitly commits
            try:
526
                self.app_handle_request(req, 'edit')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
527
            except Redirect:
Sylvain Thénault's avatar
Sylvain Thénault committed
528
                req = self.request()
529
530
                req.form['rql'] = 'Any X WHERE X eid %s' % p.eid
                req.form['vid'] = 'copy'
531
                self.app_handle_request(req, 'view')
532
            rset = self.execute('CWUser P WHERE P surname "Boom"')
533
            self.assertEqual(len(rset), 0)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
534
535
536
537
        finally:
            p.__class__.skip_copy_for = old_skips


538
class ReportBugControllerTC(CubicWebTC):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
539

540
    def test_usable_by_guest(self):
541
        self.login('anon')
Sylvain Thénault's avatar
Sylvain Thénault committed
542
543
544
        self.assertRaises(NoSelectableObject,
                          self.vreg['controllers'].select, 'reportbug', self.request())
        self.vreg['controllers'].select('reportbug', self.request(description='hop'))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
545
546


547
548
class AjaxControllerTC(CubicWebTC):
    tested_controller = 'ajax'
Adrien Di Mascio's avatar
Adrien Di Mascio committed
549
550
551

    def ctrl(self, req=None):
        req = req or self.request(url='http://whatever.fr/')
552
        return self.vreg['controllers'].select(self.tested_controller, req)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
553
554

    def setup_database(self):
Sylvain Thénault's avatar
Sylvain Thénault committed
555
556
557
        req = self.request()
        self.pytag = req.create_entity('Tag', name=u'python')
        self.cubicwebtag = req.create_entity('Tag', name=u'cubicweb')
558
        self.john = self.create_user(req, u'John')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
559
560
561
562


    ## tests ##################################################################
    def test_simple_exec(self):
sylvain.thenault@logilab.fr's avatar
sylvain.thenault@logilab.fr committed
563
564
565
566
        req = self.request(rql='CWUser P WHERE P login "John"',
                           pageid='123', fname='view')
        ctrl = self.ctrl(req)
        rset = self.john.as_rset()
567
        rset.req = req
568
        source = ctrl.publish()
569
        self.assertTrue(source.startswith('<div>'))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
570

sylvain.thenault@logilab.fr's avatar
sylvain.thenault@logilab.fr committed
571
572
573
#     def test_json_exec(self):
#         rql = 'Any T,N WHERE T is Tag, T name N'
#         ctrl = self.ctrl(self.request(mode='json', rql=rql, pageid='123'))
574
#         self.assertEqual(ctrl.publish(),
575
#                           json_dumps(self.execute(rql).rows))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
576
577
578

    def test_remote_add_existing_tag(self):
        self.remote_call('tag_entity', self.john.eid, ['python'])
579
        self.assertItemsEqual(
580
581
            [tname for tname, in self.execute('Any N WHERE T is Tag, T name N')],
            ['python', 'cubicweb'])
582
        self.assertEqual(
583
584
            self.execute('Any N WHERE T tags P, P is CWUser, T name N').rows,
            [['python']])
585

Adrien Di Mascio's avatar
Adrien Di Mascio committed
586
587
    def test_remote_add_new_tag(self):
        self.remote_call('tag_entity', self.john.eid, ['javascript'])
588
        self.assertItemsEqual(
589
590
            [tname for tname, in self.execute('Any N WHERE T is Tag, T name N')],
            ['python', 'cubicweb', 'javascript'])
591
        self.assertEqual(
592
593
            self.execute('Any N WHERE T tags P, P is CWUser, T name N').rows,
            [['javascript']])
Adrien Di Mascio's avatar
Adrien Di Mascio committed
594
595

    def test_pending_insertion(self):
sylvain.thenault@logilab.fr's avatar
sylvain.thenault@logilab.fr committed
596
        res, req = self.remote_call('add_pending_inserts', [['12', 'tags', '13']])
Sylvain Thénault's avatar
Sylvain Thénault committed
597
        deletes = get_pending_deletes(req)
598
        self.assertEqual(deletes, [])
Sylvain Thénault's avatar
Sylvain Thénault committed
599
        inserts = get_pending_inserts(req)
600
        self.assertEqual(inserts, ['12:tags:13'])
sylvain.thenault@logilab.fr's avatar
sylvain.thenault@logilab.fr committed
601
        res, req = self.remote_call('add_pending_inserts', [['12', 'tags', '14']])
Sylvain Thénault's avatar
Sylvain Thénault committed
602
        deletes = get_pending_deletes(req)
603
        self.assertEqual(deletes, [])
Sylvain Thénault's avatar
Sylvain Thénault committed
604
        inserts = get_pending_inserts(req)
605
        self.assertEqual(inserts, ['12:tags:13', '12:tags:14'])
Sylvain Thénault's avatar
Sylvain Thénault committed
606
        inserts = get_pending_inserts(req, 12)
607
        self.assertEqual(inserts, ['12:tags:13', '12:tags:14'])
Sylvain Thénault's avatar
Sylvain Thénault committed
608
        inserts = get_pending_inserts(req, 13)
609
        self.assertEqual(inserts, ['12:tags:13'])
Sylvain Thénault's avatar
Sylvain Thénault committed
610
        inserts = get_pending_inserts(req, 14)
611
        self.assertEqual(inserts, ['12:tags:14'])
Adrien Di Mascio's avatar
Adrien Di Mascio committed
612
613
614
615
        req.remove_pending_operations()

    def test_pending_deletion(self):
        res, req = self.remote_call('add_pending_delete', ['12', 'tags', '13'])
Sylvain Thénault's avatar
Sylvain Thénault committed
616
        inserts = get_pending_inserts(req)
617
        self.assertEqual(inserts, [])
Sylvain Thénault's avatar
Sylvain Thénault committed
618
        deletes = get_pending_deletes(req)
619
        self.assertEqual(deletes, ['12:tags:13'])
Adrien Di Mascio's avatar
Adrien Di Mascio committed
620
        res, req = self.remote_call('add_pending_delete', ['12', 'tags', '14'])
Sylvain Thénault's avatar
Sylvain Thénault committed
621
        inserts = get_pending_inserts(req)
622
        self.assertEqual(inserts, [])
Sylvain Thénault's avatar
Sylvain Thénault committed
623
        deletes = get_pending_deletes(req)
624
        self.assertEqual(deletes, ['12:tags:13', '12:tags:14'])
Sylvain Thénault's avatar
Sylvain Thénault committed
625
        deletes = get_pending_deletes(req, 12)
626
        self.assertEqual(deletes, ['12:tags:13', '12:tags:14'])
Sylvain Thénault's avatar
Sylvain Thénault committed
627
        deletes = get_pending_deletes(req, 13)
628
        self.assertEqual(deletes, ['12:tags:13'])
Sylvain Thénault's avatar
Sylvain Thénault committed
629
        deletes = get_pending_deletes(req, 14)
630
        self.assertEqual(deletes, ['12:tags:14'])
Adrien Di Mascio's avatar
Adrien Di Mascio committed
631
632
633
634
        req.remove_pending_operations()

    def test_remove_pending_operations(self):
        self.remote_call('add_pending_delete', ['12', 'tags', '13'])
sylvain.thenault@logilab.fr's avatar
sylvain.thenault@logilab.fr committed
635
        _, req = self.remote_call('add_pending_inserts', [['12', 'tags', '14']])
Sylvain Thénault's avatar
Sylvain Thénault committed
636
        inserts = get_pending_inserts(req)
637
        self.assertEqual(inserts, ['12:tags:14'])
Sylvain Thénault's avatar
Sylvain Thénault committed
638
        deletes = get_pending_deletes(req)
639
        self.assertEqual(deletes, ['12:tags:13'])
Adrien Di Mascio's avatar
Adrien Di Mascio committed
640
        req.remove_pending_operations()
641
642
        self.assertEqual(get_pending_deletes(req), [])
        self.assertEqual(get_pending_inserts(req), [])
643

Adrien Di Mascio's avatar
Adrien Di Mascio committed
644
645
646
647

    def test_add_inserts(self):
        res, req = self.remote_call('add_pending_inserts',
                                    [('12', 'tags', '13'), ('12', 'tags', '14')])
Sylvain Thénault's avatar
Sylvain Thénault committed
648
        inserts = get_pending_inserts(req)
649
        self.assertEqual(inserts, ['12:tags:13', '12:tags:14'])
Adrien Di Mascio's avatar
Adrien Di Mascio committed
650
        req.remove_pending_operations()
651

Adrien Di Mascio's avatar
Adrien Di Mascio committed
652
653
654

    # silly tests
    def test_external_resource(self):
655
        self.assertEqual(self.remote_call('external_resource', 'RSS_LOGO')[0],
656
                          json_dumps(self.config.uiprops['RSS_LOGO']))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
657
    def test_i18n(self):
658
        self.assertEqual(self.remote_call('i18n', ['bimboom'])[0],
659
                          json_dumps(['bimboom']))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
660
661

    def test_format_date(self):
662
        self.assertEqual(self.remote_call('format_date', '2007-01-01 12:00:00')[0],
663
                          json_dumps('2007/01/01'))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
664

665
666
667
668
    def test_ajaxfunc_noparameter(self):
        @ajaxfunc
        def foo(self, x, y):
            return 'hello'
669
670
671
672
673
674
        self.assertEqual(foo(object, 1, 2), 'hello')
        appobject = foo.__appobject__
        self.assertTrue(issubclass(appobject, AjaxFunction))
        self.assertEqual(appobject.__regid__, 'foo')
        self.assertEqual(appobject.check_pageid, False)
        self.assertEqual(appobject.output_type, None)
675
        req = self.request()
676
        f = appobject(req)
677
678
679
        self.assertEqual(f(12, 13), 'hello')

    def test_ajaxfunc_checkpageid(self):
680
        @ajaxfunc(check_pageid=True)
681
        def foo(self, x, y):
682
683
684
685
686
687
688
            return 'hello'
        self.assertEqual(foo(object, 1, 2), 'hello')
        appobject = foo.__appobject__
        self.assertTrue(issubclass(appobject, AjaxFunction))
        self.assertEqual(appobject.__regid__, 'foo')
        self.assertEqual(appobject.check_pageid, True)
        self.assertEqual(appobject.output_type, None)
689
690
        # no pageid
        req = self.request()
691
        f = appobject(req)
692
693
694
695
696
697
        self.assertRaises(RemoteCallFailed, f, 12, 13)

    def test_ajaxfunc_json(self):
        @ajaxfunc(output_type='json')
        def foo(self, x, y):
            return x + y
698
699
700
701
702
703
        self.assertEqual(foo(object, 1, 2), 3)
        appobject = foo.__appobject__
        self.assertTrue(issubclass(appobject, AjaxFunction))
        self.assertEqual(appobject.__regid__, 'foo')
        self.assertEqual(appobject.check_pageid, False)
        self.assertEqual(appobject.output_type, 'json')
704
705
        # no pageid
        req = self.request()
706
        f = appobject(req)
707
708
709
710
711
712
713
        self.assertEqual(f(12, 13), '25')


class JSonControllerTC(AjaxControllerTC):
    # NOTE: this class performs the same tests as AjaxController but with
    #       deprecated 'json' controller (i.e. check backward compatibility)
    tested_controller = 'json'
Adrien Di Mascio's avatar
Adrien Di Mascio committed
714

715
716
717
718
    def setUp(self):
        super(JSonControllerTC, self).setUp()
        self.exposed_remote_funcs = [fname for fname in dir(JSonController)
                                     if fname.startswith('js_')]
719

720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
    def tearDown(self):
        super(JSonControllerTC, self).tearDown()
        for funcname in dir(JSonController):
            # remove functions added dynamically during tests
            if funcname.startswith('js_') and funcname not in self.exposed_remote_funcs:
                delattr(JSonController, funcname)

    def test_monkeypatch_jsoncontroller(self):
        self.assertRaises(RemoteCallFailed, self.remote_call, 'foo')
        @monkeypatch(JSonController)
        def js_foo(self):
            return u'hello'
        res, req = self.remote_call('foo')
        self.assertEqual(res, u'hello')

    def test_monkeypatch_jsoncontroller_xhtmlize(self):
        self.assertRaises(RemoteCallFailed, self.remote_call, 'foo')
        @monkeypatch(JSonController)
        @xhtmlize
        def js_foo(self):
            return u'hello'
        res, req = self.remote_call('foo')
742
        self.assertEqual(u'<div>hello</div>', res)
743
744
745
746
747
748
749
750
751

    def test_monkeypatch_jsoncontroller_jsonize(self):
        self.assertRaises(RemoteCallFailed, self.remote_call, 'foo')
        @monkeypatch(JSonController)
        @jsonize
        def js_foo(self):
            return 12
        res, req = self.remote_call('foo')
        self.assertEqual(res, '12')
752
753
754
755
756
757
758
759

    def test_monkeypatch_jsoncontroller_stdfunc(self):
        @monkeypatch(JSonController)
        @jsonize
        def js_reledit_form(self):
            return 12
        res, req = self.remote_call('reledit_form')
        self.assertEqual(res, '12')
760

761
762
763

class UndoControllerTC(CubicWebTC):

764
765
766
767
768
769
770
771
772
773
774
775
    def setUp(self):
        class Transaction(OldTransaction):
            """Force undo feature to be turned on in all case"""
            undo_actions = property(lambda tx: True, lambda x, y:None)
        cubicweb.server.session.Transaction = Transaction
        super(UndoControllerTC, self).setUp()

    def tearDown(self):
        super(UndoControllerTC, self).tearDown()
        cubicweb.server.session.Transaction = OldTransaction