source: products/quintagroup.plonecaptchas/trunk/quintagroup/plonecaptchas/tests/testForms.py

Last change on this file was 3609, checked in by vmaksymiv, 12 years ago

PPP fixes

  • Property svn:eol-style set to native
File size: 8.1 KB
Line 
1import unittest
2import doctest
3import re
4from urllib import urlencode
5from StringIO import StringIO
6
7from Products.PloneTestCase.PloneTestCase import portal_owner
8from Products.PloneTestCase.PloneTestCase import default_password
9
10from quintagroup.plonecaptchas.tests.base import FunctionalTestCase, ztc
11from quintagroup.plonecaptchas.config import PRODUCT_NAME, HAS_APP_DISCUSSION
12
13from quintagroup.captcha.core.tests.testWidget import IMAGE_PATT, NOT_VALID
14from quintagroup.captcha.core.tests.testWidget import addTestLayer
15from quintagroup.captcha.core.tests.base import testPatch
16from quintagroup.captcha.core.utils import getWord, decrypt, parseKey
17
18from plone.app.controlpanel.security import ISecuritySchema
19
20# BBB for plone v<3.1, where plone.protect not used yet
21PROTECT_SUPPORT = True
22try:
23    from plone import protect
24    # pyflakes fix (pyflakes message: 'protect' imported but unused)
25    protect
26except ImportError:
27    PROTECT_SUPPORT = False
28
29# USE PATCH FROM quintagroup.captcha.core
30# patch to use test images and dictionary
31testPatch()
32
33
34class TestFormMixin(FunctionalTestCase):
35
36    formkey_key = "key"
37    formkey_hashkey = "hashkey"
38
39    def afterSetUp(self):
40        self.loginAsPortalOwner()
41        self.addProduct(PRODUCT_NAME)
42        # Add test_captcha layer from quintagroup.captcah.core
43        addTestLayer(self)
44        # Prepare form data
45        self.basic_auth = ':'.join((portal_owner, default_password))
46        self.form_url = ''
47        self.form_method = "POST"
48        self.hasAuthenticator = False
49        self.form_data = self.getFormData()
50        # Prepare captcha related test data
51        self.captcha_key = self.portal.captcha_key
52        self.hashkey = self.portal.getCaptcha()
53        self.form_data[self.formkey_hashkey] = self.hashkey
54        self.form_data[self.formkey_key] = ''
55
56    def getFormData(self):
57        raise NotImplementedError(
58            "getFormData not implemented")
59
60    def publishForm(self):
61        stdin_data = None
62        form_url = self.portal.absolute_url(1) + self.form_url
63        # Prepare form data
64        if PROTECT_SUPPORT and self.hasAuthenticator:
65            self.form_data['_authenticator'] = self._getauth()
66        form_data = urlencode(self.form_data)
67        if self.form_method.upper() == 'GET':
68            form_url += "?%s" % form_data
69        else:
70            stdin_data = StringIO(form_data)
71        # Publish form and get response
72        response = self.publish(form_url, self.basic_auth,
73                                request_method=self.form_method,
74                                stdin=stdin_data)
75        return response
76
77    def _getauth(self):
78        # Fix authenticator for the form
79        authenticator = self.portal.restrictedTraverse("@@authenticator")
80        html = authenticator.authenticator()
81        handle = re.search('value="(.*)"', html).groups()[0]
82        return handle
83
84    def elog(self, name="", response=""):
85        open("/tmp/test.%s.html" % name, "w").write(response)
86        logs = self.portal.error_log.getLogEntries()
87        if len(logs) > 0:
88            i = 0
89            while logs:
90                l = logs.pop()
91                i += 1
92                open("/tmp/test.%s.error.%d.html" % (l["id"], i),
93                     "w").write(l["tb_html"])
94
95    def testImage(self):
96        self.form_data = {}
97        self.form_method = "GET"
98        response = self.publishForm().getBody()
99        patt = re.compile(IMAGE_PATT % self.portal.absolute_url())
100        match_obj = patt.search(response)
101        self.elog("image", response)
102        img_url = match_obj.group(1)
103
104        content_type = self.publish(
105            '/plone' + img_url).getHeader('content-type')
106        self.assertTrue(content_type.startswith('image'),
107                        "Wrong captcha image content type")
108
109    def testSubmitRightCaptcha(self):
110        key = getWord(int(parseKey(decrypt(self.captcha_key,
111                                           self.hashkey))['key']) - 1)
112        self.form_data[self.formkey_key] = key
113
114        response = self.publishForm().getBody()
115        self.elog("right", response)
116        self.assertFalse(NOT_VALID.search(response))
117
118    def testSubmitWrongCaptcha(self):
119        self.form_data[self.formkey_key] = 'wrong word'
120        response = self.publishForm().getBody()
121        self.elog("wrong", response)
122        self.assertTrue(NOT_VALID.search(response))
123
124    def testSubmitRightCaptchaTwice(self):
125        key = getWord(int(parseKey(decrypt(self.captcha_key,
126                                           self.hashkey))['key']) - 1)
127        self.form_data[self.formkey_key] = key
128
129        response1 = self.publishForm().getBody()
130        self.elog("right1", response1)
131        response2 = self.publishForm().getBody()
132        self.elog("right2", response2)
133        self.assertTrue(NOT_VALID.search(response2))
134
135
136class TestDiscussionForm(TestFormMixin):
137
138    def afterSetUp(self):
139        TestFormMixin.afterSetUp(self)
140        self.portal.invokeFactory('Document', 'index_html')
141        self.portal['index_html'].allowDiscussion(True)
142        self.form_url = '/index_html/discussion_reply_form'
143
144    def getFormData(self):
145        return {'form.submitted': '1',
146                'subject': 'testing',
147                'Creator': portal_owner,
148                'body_text': 'Text in Comment',
149                'discussion_reply:method': 'Save',
150                'form.button.form_submit': 'Save'}
151
152
153class TestRegisterForm(TestFormMixin):
154
155    formkey_key = "form.captcha"
156    formkey_hashkey = "form..hashkey"
157
158    def afterSetUp(self):
159        TestFormMixin.afterSetUp(self)
160        ISecuritySchema(self.portal).enable_self_reg = True
161        self.portal._updateProperty('validate_email', False)
162        self.hasAuthenticator = True
163        self.form_url = '/@@register'
164        self.basic_auth = ":"
165        self.logout()
166
167    def getFormData(self):
168        return {"form.fullname": "Tester",
169                "form.username": "tester",
170                "form.email": "tester@test.com",
171                "form.password": "123456",
172                "form.password_ctl": "123456",
173                'form.actions.register': 'Register'}
174
175
176class TestSendtoForm(TestFormMixin):
177
178    def afterSetUp(self):
179        TestFormMixin.afterSetUp(self)
180        self.portal.invokeFactory('Document', 'index_html')
181        self.portal['index_html'].allowDiscussion(True)
182        self.form_url = '/index_html/sendto_form'
183
184    def getFormData(self):
185        return {'form.submitted': '1',
186                "send_to_address": "recipient@test.com",
187                "send_from_address": "sender@test.com",
188                'comment': 'Text in Comment',
189                'form.button.Send': 'Save'}
190
191
192def send_patch(self, *args, **kwargs):
193    """This patch prevent breakage on sending."""
194
195
196class TestContactInfo(TestFormMixin):
197
198    def afterSetUp(self):
199        TestFormMixin.afterSetUp(self)
200        # preparation to form correct working
201        self.portal._updateProperty('email_from_address', 'manager@test.com')
202        self.logout()
203        self.form_url = '/contact-info'
204        self.orig_mh_send = self.portal.MailHost.send
205        self.portal.MailHost.send = send_patch
206
207    def beforeTearDown(self):
208        self.portal.MailHost.send = self.orig_mh_send
209
210    def getFormData(self):
211        return {'form.submitted': '1',
212                "sender_fullname": "tester",
213                "sender_from_address": "sender@test.com",
214                'subject': 'Subject',
215                'message': 'Message',
216                'form.button.Send': 'Save'}
217
218
219def test_suite():
220    suite = unittest.TestSuite()
221    if HAS_APP_DISCUSSION:
222        suite.addTest(unittest.TestSuite([
223            ztc.FunctionalDocFileSuite(
224                'discussion.txt', package='quintagroup.plonecaptchas.tests',
225                test_class=FunctionalTestCase, globs=globals(),
226                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE |
227                doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS),
228        ]))
229
230    else:
231        suite.addTest(unittest.makeSuite(TestDiscussionForm))
232    suite.addTest(unittest.makeSuite(TestRegisterForm))
233    suite.addTest(unittest.makeSuite(TestSendtoForm))
234    suite.addTest(unittest.makeSuite(TestContactInfo))
235    return suite
Note: See TracBrowser for help on using the repository browser.