source: products/quintagroup.plonecaptchas/branches/plone4/quintagroup/plonecaptchas/tests/testForms.py @ 3154

Last change on this file since 3154 was 3154, checked in by vmaksymiv, 13 years ago

pyfakes fixes

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