Changeset 3128 in products


Ignore:
Timestamp:
Apr 18, 2011 11:16:39 AM (10 years ago)
Author:
vmaksymiv
Message:

pep8 fixes

Location:
quintagroup.captcha.core/trunk
Files:
17 edited

Legend:

Unmodified
Added
Removed
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/CaptchaTool.py

    r2180 r3128  
    55from AccessControl import ClassSecurityInfo 
    66from Products.Transience.Transience import TransientObjectContainer 
     7 
    78 
    89class CaptchaTool(TransientObjectContainer): 
     
    1314    security.declarePublic('addExpiredKey') 
    1415 
    15     def __init__(self, id='portal_captchas', title='', timeout_mins=60, addNotification=None, 
     16    def __init__(self, id='portal_captchas', title='', 
     17                 timeout_mins=60, addNotification=None, 
    1618                 delNotification=None, limit=0, period_secs=60): 
    17         TransientObjectContainer.__init__(self, id, title, timeout_mins, addNotification, 
    18                                           delNotification, limit, period_secs) 
     19        TransientObjectContainer.__init__(self, id, title, timeout_mins, 
     20                                          addNotification, delNotification, 
     21                                          limit, period_secs) 
    1922 
    2023    def addExpiredKey(self, key): 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/Crypto.py

    r797 r3128  
    11# xor implementation with PyCrypto interface 
     2 
    23 
    34def new(key): 
    45    return Xor(key) 
     6 
    57 
    68class Xor: 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/Extensions/Install.py

    r1952 r3128  
    22from Products.CMFCore.utils import getToolByName 
    33 
     4 
    45def uninstall(self): 
    56    portal_setup = getToolByName(self, 'portal_setup') 
    6     portal_setup.runAllImportStepsFromProfile('profile-quintagroup.captcha.core:uninstall', purge_old=False) 
     7    profile = "profile-quintagroup.captcha.core:uninstall" 
     8    portal_setup.runAllImportStepsFromProfile(profile, purge_old=False) 
    79    transaction.savepoint() 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/Extensions/__init__.py

    r963 r3128  
    1 # 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/__init__.py

    r1978 r3128  
    77from quintagroup.captcha.core import CaptchaTool 
    88 
    9 ProductMessageFactory = MessageFactory('quintagroup.captcha.core') 
    10 ModuleSecurityInfo('quintagroup.captcha.core').declarePublic("ProductMessageFactory") 
     9product = 'quintagroup.captcha.core' 
     10ProductMessageFactory = MessageFactory(product) 
     11ModuleSecurityInfo(product).declarePublic("ProductMessageFactory") 
    1112 
    1213allow_module('quintagroup.captcha.core.utils') 
    1314allow_module('quintagroup.captcha.core.config') 
     15 
    1416 
    1517def initialize(context): 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/encrypt_images.py

    r797 r3128  
    11import md5 
    22import os 
     3 
    34 
    45def encrypt_md5(s): 
     
    1213    fname = file[:-5] 
    1314    hash = md5.new(fname).hexdigest().upper() 
    14     new_fname = str(index)+'.jpg' 
     15    new_fname = str(index) + '.jpg' 
    1516    metaname = new_fname + '.metadata' 
    16     meta = open(metaname,'w') 
     17    meta = open(metaname, 'w') 
    1718    meta.write('[default]\n') 
    18     meta.write('title='+hash) 
     19    meta.write('title=' + hash) 
    1920    meta.close() 
    2021    os.rename(file, new_fname) 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/setuphandlers.py

    r1953 r3128  
    66    ALL_LAYERS, PROPERTY_SHEET 
    77 
     8 
    89def generateKey(length): 
    910    key = '' 
     
    1112        key += str(randint(0, 9)) 
    1213    return key 
     14 
    1315 
    1416def setupVarious(context): 
     
    2426    else: 
    2527        site._setProperty(CAPTCHA_KEY, value, 'string') 
     28 
    2629 
    2730def uninstall(context): 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/skins/captcha_core/dynamic/getCaptcha.py

    r1993 r3128  
    1212# *randint* return random integer in range [a, b], 
    1313# including *both* end points. 
    14 key = formKey(randint(0, getCaptchasCount(True)-1)) 
     14key = formKey(randint(0, getCaptchasCount(True) - 1)) 
    1515encrypted_key = encrypt(context.captcha_key, key) 
    1616 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/skins/captcha_core/getCaptchaType.py

    r1955 r3128  
    1616default_skin = skinsTool.getDefaultSkin() 
    1717path = skinsTool.getSkinPath(default_skin) 
    18 path = map( string.strip, string.split( path,',' ) ) 
     18path = map(string.strip, string.split(path, ',')) 
    1919 
    2020if LAYER_STATIC_CAPTCHAS in path: 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/base.py

    r1991 r3128  
    2424burn 
    2525""" 
     26 
     27 
    2628def testPatch(): 
    2729    # PATCH dictionary for captcha testing 
     
    3234    utils.CAPTCHAS_COUNT = len(utils.basic_english.words.split()) 
    3335    # END OF PATCH 
     36 
    3437 
    3538@onsetup 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testConfiglet.py

    r2447 r3128  
    1 import re, string 
     1import re 
     2import string 
    23from base import * 
     4 
    35 
    46class TestConfiglet(ptc.FunctionalTestCase): 
     
    68    def afterSetUp(self): 
    79        self.sp = self.portal.portal_properties.site_properties 
    8         self.basic_auth = ':'.join((portal_owner,default_password)) 
     10        self.basic_auth = ':'.join((portal_owner, default_password)) 
    911        self.loginAsPortalOwner() 
    1012        self.addProduct(PRODUCT_NAME) 
    11          
     13 
    1214        self.capprops = self.portal.portal_properties[PROPERTY_SHEET] 
    1315        self.save_url = self.portal.id + \ 
     
    2022        for skin in skins.getSkinSelections(): 
    2123            path = skins.getSkinPath(skin) 
    22             path = map( string.strip, string.split( path,',' )) 
     24            path = map(string.strip, string.split(path, ',')) 
    2325            if not layer in path: 
    2426                return False 
     
    2931        self.publish(self.save_url + '&static_captchas=static', 
    3032                     self.basic_auth) 
    31          
     33 
    3234        self.assertTrue(self.layerInSkins(LAYER_STATIC_CAPTCHAS), 
    3335            "No '%s' skin layer in some skins" % LAYER_STATIC_CAPTCHAS) 
     
    3638        res = self.publish(self.save_url + '&static_captchas=dynamic', 
    3739                     self.basic_auth).getBody() 
    38          
     40 
    3941        self.assertTrue(self.layerInSkins(LAYER_DYNAMIC_CAPTCHAS), 
    4042            "No '%s' skin layer in some skins" % LAYER_DYNAMIC_CAPTCHAS) 
     
    99101        self.loginAsPortalOwner() 
    100102        self.addProduct(PRODUCT_NAME) 
    101         self.view = self.publish(self.portal.id+'/prefs_captchas_setup_form', 
    102                                  portal_owner+":"+default_password).getBody() 
    103   
     103        captcha_pref_path = self.portal.id + '/prefs_captchas_setup_form' 
     104        basic_auth = portal_owner + ":" + default_password 
     105        self.view = self.publish(captcha_pref_path, basic_auth).getBody() 
     106 
    104107    def matchinput(self, name): 
    105108        return re.match('.*<input\s+[^\>]*name=\"%s\"[^>]*>' % name, 
    106                         self.view, re.I|re.S) 
     109                        self.view, re.I | re.S) 
    107110 
    108111    def test_basic_form(self): 
    109         form = re.match('.*<form\s+[^\>]*action=\"[^\"]*?prefs_captchas_setup_form\"[^>]*>', 
    110                         self.view, re.I|re.S) 
     112        reg_expr = '.*<form\s+[^\>]*action=\"[^\"]*?'\ 
     113                   'prefs_captchas_setup_form\"[^>]*>' 
     114        form = re.match(reg_expr, self.view, re.I | re.S) 
    111115        self.assertNotEqual(form, None, 
    112116            "No 'Plone Captchas Setup' form present on the configlet view") 
     
    122126            self.assertNotEqual(self.matchinput(param), None, 
    123127                "'%s' form element absence on the configlet form" % param) 
    124          
     128 
    125129 
    126130def test_suite(): 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testDynamic.py

    r2450 r3128  
    1212    from PIL import ImageFont 
    1313    fontspath = abspath(dirname(dirname(__file__))) + '/data/fonts/vera/' 
    14     font = ImageFont.truetype(fontspath+'VeraBd.ttf', 27) 
     14    font = ImageFont.truetype(fontspath + 'VeraBd.ttf', 27) 
    1515except ImportError: 
    1616    DYNAMIC_WORKABLE = False 
     
    2424        for skin in skins.getSkinSelections(): 
    2525            path = skins.getSkinPath(skin) 
    26             path = map( string.strip, string.split( path,',' )) 
     26            path = map(string.strip, string.split(path, ',')) 
    2727            try: 
    2828                i = path.index(LAYER_STATIC_CAPTCHAS) 
     
    3131            except ValueError: 
    3232                pass 
    33             path = string.join( path, ', ' ) 
    34             skins.addSkinSelection( skin, path ) 
     33            path = string.join(path, ', ') 
     34            skins.addSkinSelection(skin, path) 
    3535            self._refreshSkinData() 
    3636 
    3737 
    3838class TestPIL(unittest.TestCase): 
    39      
     39 
    4040    def testPILImageFont(self): 
    4141        if not DYNAMIC_WORKABLE: 
     
    6969        # index start from 0 and lower or equals to captchas count 
    7070        index = int(parsed_key['key']) 
    71         self.assertTrue(index >= 0 and index <= len(utils.basic_english.words.split())) 
     71        words = utils.basic_english.words.split() 
     72        self.assertTrue(index >= 0 and index <= len(words)) 
    7273        # encrypted key must be equals to word from the dictionary, 
    7374        # under index position and must be not empty string 
     
    7677    def test_GetImage(self): 
    7778        # getCaptchaImage function must return image coded in hashkey same to 
    78         # image get by 'key' after parsing decrypted key  
     79        # image get by 'key' after parsing decrypted key 
    7980        decrypted_key = decrypt(self.captcha_key, self.hashkey) 
    8081        parsed_key = parseKey(decrypted_key) 
    8182 
    8283        img_html = self.publish( 
    83             self.portal.absolute_url(1)+"/getCaptchaImage/%s" % self.hashkey) 
     84            self.portal.absolute_url(1) + "/getCaptchaImage/%s" % self.hashkey) 
    8485 
    8586        img_ctype = img_html.getHeader('content-type') 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testInstallation.py

    r1957 r3128  
    11from base import * 
     2 
    23 
    34class TestInstallation(ptc.FunctionalTestCase): 
     
    1516    def testPropertysheetInstall(self): 
    1617        pp = getToolByName(self.portal, 'portal_properties') 
    17         self.assert_(PROPERTY_SHEET in pp.objectIds(), 'Property sheet isn\'t found') 
     18        msg = 'Property sheet isn\'t found' 
     19        self.assert_(PROPERTY_SHEET in pp.objectIds(), msg) 
    1820 
    1921    def testPropertysheetUninstall(self): 
     
    2426 
    2527    def testConfigletInstall(self): 
    26         self.assert_(CONFIGLET_ID in [a.getId() for a in self.cp.listActions()], 'Configlet not found') 
     28        list_ids = [] 
     29        for action in self.cp.listActions(): 
     30            list_ids.append(action.getId()) 
     31        self.assert_(CONFIGLET_ID in list_ids, 'Configlet not found') 
    2732 
    2833    def testConfigletUninstall(self): 
    2934        self.qi.uninstallProducts([PRODUCT_NAME]) 
    30         self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True,'%s is already installed' % PRODUCT_NAME) 
    31         self.assert_(not CONFIGLET_ID in [a.getId() for a in self.cp.listActions()], 'Configlet found after uninstallation') 
     35        self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True, 
     36                            '%s is already installed' % PRODUCT_NAME) 
     37        list_ids = [] 
     38        for action in self.cp.listActions(): 
     39            list_ids.append(action.getId()) 
     40        msg = 'Configlet found after uninstallation' 
     41        self.assert_(not CONFIGLET_ID in list_ids, msg) 
    3242 
    3343    def testSkinsInstall(self): 
     
    3848            path = map(str.strip, path.split(',')) 
    3949            for layer in layers: 
    40                 self.assert_(layer.split('/')[0] in skinstool.objectIds(), '%s directory view not found in portal_skins after installation' % layer) 
    41                 self.assert_(layer in path, '%s layer not found in %s' % (PRODUCT_NAME, skin)) 
     50                msg = '%s directory view not found in'\ 
     51                      'portal_skins after installation' % layer 
     52                self.assert_(layer.split('/')[0] in skinstool.objectIds(), msg) 
     53                msg = '%s layer not found in %s' % (PRODUCT_NAME, skin) 
     54                self.assert_(layer in path, msg) 
    4255 
    4356    def testSkinsUninstall(self): 
    4457        self.qi.uninstallProducts([PRODUCT_NAME]) 
    45         self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True,'%s is already installed' % PRODUCT_NAME) 
     58        self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True, 
     59                            '%s is already installed' % PRODUCT_NAME) 
    4660        skinstool = self.st 
    4761        layers = self.getLayers() 
     
    5064            path = map(str.strip, path.split(',')) 
    5165            for layer in layers: 
    52                 self.assert_(not layer.split('/')[0] in skinstool.objectIds(), '%s directory view found in portal_skins after uninstallation' % layer) 
    53                 self.assert_(not layer in path, '%s layer found in %s after uninstallation' % (layer, skin)) 
     66                msg = '%s directory view found in'\ 
     67                      'portal_skins after uninstallation' % layer 
     68                skins_tool_ids = skinstool.objectIds() 
     69                self.assert_(not layer.split('/')[0] in skins_tool_ids, msg) 
     70                msg = '%s layer found in'\ 
     71                      '%s after uninstallation' % (layer, skin) 
     72                self.assert_(not layer in path, msg) 
    5473 
    5574    def testToolInstall(self): 
     
    5877    def testToolUninstall(self): 
    5978        self.qi.uninstallProducts([PRODUCT_NAME]) 
    60         self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True,  
     79        self.assertNotEqual(self.qi.isProductInstalled(PRODUCT_NAME), True, 
    6180            '%s is already installed' % PRODUCT_NAME) 
    6281        self.assert_(not TOOL_ID in self.portal.objectIds()) 
     
    6988        self.assert_(not self.portal.hasProperty(CAPTCHA_KEY)) 
    7089 
     90 
    7191def test_suite(): 
    7292    suite = unittest.TestSuite() 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testStatic.py

    r2542 r3128  
    44from DateTime import DateTime 
    55from Products.CMFFormController.ControllerState import ControllerState 
     6 
    67 
    78class TestStatic(ptc.FunctionalTestCase): 
     
    1920        for skin in self.skins.getSkinSelections(): 
    2021            path = self.skins.getSkinPath(skin) 
    21             path = map( string.strip, string.split( path,',' )) 
     22            path = map(string.strip, string.split(path, ',')) 
    2223            self.assertTrue(LAYER_STATIC_CAPTCHAS in path) 
    2324 
     
    2627        static = self.skins.restrictedTraverse('captchas') 
    2728        static_ids = static.objectIds() 
    28         for i in range(1, CAPTCHAS_COUNT+1): 
     29        for i in range(1, CAPTCHAS_COUNT + 1): 
    2930            self.assertTrue("%s.jpg" % i in static_ids, 
    30                             "No %s.jpg in static, %s" % (i,static_ids)) 
     31                            "No %s.jpg in static, %s" % (i, static_ids)) 
    3132 
    3233    def test_GetCaptcha_Date(self): 
     
    4546        self.assertTrue(index >= 1 and index <= CAPTCHAS_COUNT) 
    4647        # encrypted key must be equals to title of the image 
    47         key = getWord( index-1 ) 
     48        key = getWord(index - 1) 
    4849        img = getattr(self.portal, '%s.jpg' % index) 
    4950        self.assertTrue(encrypt1(key) == img.title) 
     
    5152    def test_GetImage(self): 
    5253        # getCaptchaImage function must return image coded in hashkey same to 
    53         # image get by 'key' after parsing decrypted key  
     54        # image get by 'key' after parsing decrypted key 
    5455        req, resp = self.app.REQUEST, self.app.REQUEST.RESPONSE 
    5556        decrypted_key = decrypt(self.captcha_key, self.hashkey) 
    5657        parsed_key = parseKey(decrypted_key) 
    57         img = self.portal.restrictedTraverse(parsed_key['key']+'.jpg') 
     58        img = self.portal.restrictedTraverse(parsed_key['key'] + '.jpg') 
    5859        img_html = img.index_html(req, resp) 
    5960 
    60         obj_html = self.publish( 
    61             self.portal.absolute_url(1)+"/getCaptchaImage/%s" % self.hashkey).getBody() 
    62         self.assertTrue(obj_html == img_html, "Image get by getCaptchaImage script " \ 
    63             "is differ from image get by index (after parsing decrypted key)") 
    64          
     61        portal = self.portal.absolute_url(1) 
     62        captcha_path = portal + "/getCaptchaImage/%s" % self.hashkey 
     63        obj_html = self.publish(captcha_path).getBody() 
     64        msg = "Image get by getCaptchaImage script is differ from"\ 
     65              "image get by index (after parsing decrypted key)" 
     66        self.assertTrue(obj_html == img_html, msg) 
     67 
    6568 
    6669class TestStaticValidator(ptc.PloneTestCase): 
     
    8083    def testGoodData(self): 
    8184        hashkey = self.portal.getCaptcha() 
    82         key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1 ) 
     85        decrypted_key = decrypt(self.captcha_key, hashkey) 
     86        key = getWord(int(parseKey(decrypted_key)['key']) - 1) 
    8387        self.req.form['hashkey'] = hashkey 
    84         self.req.form['key'] = key+'1' 
     88        self.req.form['key'] = key + '1' 
    8589 
    86         cstate = self.pfc.validate(self.dummycs, self.req, ['captcha_validator',]) 
    87         self.assertTrue(cstate.getErrors()['key'] == 'Please re-enter validation code.', 
     90        cstate = self.pfc.validate(self.dummycs, self.req, 
     91                                   ['captcha_validator', ]) 
     92        error_msg = 'Please re-enter validation code.' 
     93        self.assertTrue(cstate.getErrors()['key'] == error_msg, 
    8894                        "Static captcha validator validate wrong key") 
    8995 
    9096    def testBadKey(self): 
    9197        hashkey = self.portal.getCaptcha() 
    92         key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1 ) 
     98        decrypted_key = decrypt(self.captcha_key, hashkey) 
     99        key = getWord(int(parseKey(decrypted_key)['key']) - 1) 
    93100        self.req.form['hashkey'] = hashkey 
    94101        self.req.form['key'] = 'bad key' 
    95          
    96         cstate = self.pfc.validate(self.dummycs, self.req, ['captcha_validator',]) 
    97         self.assertTrue(cstate.getErrors()['key'] == 'Please re-enter validation code.', 
     102 
     103        cstate = self.pfc.validate(self.dummycs, self.req, 
     104                                   ['captcha_validator', ]) 
     105        error_msg = 'Please re-enter validation code.' 
     106        self.assertTrue(cstate.getErrors()['key'] == error_msg, 
    98107                        "Static captcha validator validate wrong key") 
    99108 
     
    103112        now = DateTime().timeTime() 
    104113        DateTime.timeTime = lambda s: now - float(3601) 
    105          
     114 
    106115        hashkey = self.portal.getCaptcha() 
    107         key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1 ) 
     116 
     117        decrypted_key = decrypt(self.captcha_key, hashkey) 
     118        key = getWord(int(parseKey(decrypted_key)['key']) - 1) 
    108119        self.req.form['hashkey'] = hashkey 
    109120        self.req.form['key'] = key 
    110121        # Return original Date 
    111122        DateTime.timeTime = origDTTT 
    112         cstate = self.pfc.validate(self.dummycs, self.req, ['captcha_validator',]) 
    113         self.assertTrue(cstate.getErrors()['key'] == 'Please re-enter validation code.', 
     123        cstate = self.pfc.validate(self.dummycs, self.req, 
     124                                   ['captcha_validator', ]) 
     125        error_msg = 'Please re-enter validation code.' 
     126        self.assertTrue(cstate.getErrors()['key'] == error_msg, 
    114127                        "Static captcha validator validate wrong key") 
    115128 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/tests/testWidget.py

    r2542 r3128  
    1212testPatch() 
    1313 
     14 
    1415def addTestLayer(self): 
    1516    # Install test_captcha skin layer 
     
    1920    skinName = skins.getDefaultSkin() 
    2021    paths = map(string.strip, skins.getSkinPath(skinName).split(',')) 
    21     paths.insert(paths.index('custom')+1, 'test_captcha') 
     22    paths.insert(paths.index('custom') + 1, 'test_captcha') 
    2223    skins.addSkinSelection(skinName, ','.join(paths)) 
    2324    self._refreshSkinData() 
     
    3435        self.absolute_url = self.portal['index_html'].absolute_url_path() 
    3536 
    36         self.basic_auth = ':'.join((portal_owner,default_password)) 
     37        self.basic_auth = ':'.join((portal_owner, default_password)) 
    3738        self.captcha_key = self.portal.captcha_key 
    3839 
    3940    def testImage(self): 
    4041        path = '%s/test_form' % self.absolute_url 
    41         response = self.publish(path, self.basic_auth, request_method='GET').getBody() 
     42        response = self.publish(path, self.basic_auth, 
     43                                request_method='GET').getBody() 
    4244        patt = re.compile(IMAGE_PATT % self.portal.absolute_url()) 
    4345        match_obj = patt.search(response) 
    4446 
    4547        img_url = match_obj.group(1) 
    46         content_type = self.publish('/plone' + img_url, self.basic_auth).getHeader('content-type') 
     48        res = self.publish('/plone' + img_url, self.basic_auth) 
     49        content_type = res.getHeader('content-type') 
    4750        self.assert_(content_type.startswith('image')) 
    4851 
    4952    def testSubmitRightCaptcha(self): 
    5053        hashkey = self.portal.getCaptcha() 
    51         # index of word number starts from 1, but index of dictionary starts from 0 
    52         key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1 ) 
     54        # index of word number starts from 1, 
     55        # but index of dictionary starts from 0 
     56        decrypted_key = decrypt(self.captcha_key, hashkey) 
     57        key = getWord(int(parseKey(decrypted_key)['key']) - 1) 
    5358        parameters = 'form.submitted=1&key=%s' % key 
    5459        path = '%s/test_form?%s' % (self.absolute_url, parameters) 
    5560        extra = {'hashkey': hashkey, 
    5661                 'form.button.Save': 'Save'} 
    57         response = self.publish(path, self.basic_auth, extra=extra, request_method='GET').getBody() 
     62        response = self.publish(path, self.basic_auth, extra=extra, 
     63                                request_method='GET').getBody() 
    5864        self.assert_(not NOT_VALID.search(response)) 
    5965 
     
    6470        extra = {'hashkey': hashkey, 
    6571                 'form.button.Save': 'Save'} 
    66         response = self.publish(path, self.basic_auth, extra=extra, request_method='GET').getBody() 
     72        response = self.publish(path, self.basic_auth, extra=extra, 
     73                                request_method='GET').getBody() 
    6774        self.assert_(NOT_VALID.search(response)) 
    6875 
    6976    def testSubmitRightCaptchaTwice(self): 
    7077        hashkey = self.portal.getCaptcha() 
    71         key = getWord(int(parseKey(decrypt(self.captcha_key, hashkey))['key'])-1) 
    72         parameters = 'form.submitted=1&key=%s'%key 
    73         path = '%s/test_form?%s'%(self.absolute_url, parameters) 
     78        decrypted_key = decrypt(self.captcha_key, hashkey) 
     79        key = getWord(int(parseKey(decrypted_key)['key']) - 1) 
     80        parameters = 'form.submitted=1&key=%s' % key 
     81        path = '%s/test_form?%s' % (self.absolute_url, parameters) 
    7482        extra = {'hashkey': hashkey, 
    7583                 'form.button.Save': 'Save'} 
    7684        self.publish(path, self.basic_auth, extra=extra, request_method='GET') 
    77         response = self.publish(path, self.basic_auth, extra=extra, request_method='GET').getBody() 
     85        response = self.publish(path, self.basic_auth, extra=extra, 
     86                                request_method='GET').getBody() 
    7887 
    7988        self.assert_(NOT_VALID.search(response)) 
     
    8291        # captcha core related issue, described in 
    8392        # in http://plone.org/products/plone-comments/issues/5 
    84         resp = self.publish(self.portal.absolute_url(1)+"/captcha_widget") 
     93        resp = self.publish(self.portal.absolute_url(1) + "/captcha_widget") 
    8594        self.assertEqual(resp.status / 100, 2) 
     95 
    8696 
    8797def test_suite(): 
  • quintagroup.captcha.core/trunk/quintagroup/captcha/core/utils.py

    r3097 r3128  
    1919    import Crypto 
    2020 
     21 
    2122def encrypt1(s): 
    2223    return md5.md5(s).hexdigest().upper() 
    2324 
     25 
    2426def getTransform(x, y, a, p, o): 
    25     return (math.sin( (y+o[0])*p )*a + x, math.sin( (x+o[1])*p )*a + y) 
     27    return (math.sin((y + o[0]) * p) * a + x, math.sin((x + o[1]) * p) * a + y) 
     28 
    2629 
    2730def gen_captcha(**kwargs): 
     
    5760 
    5861    #select font for captcha text 
    59     ALL_FONTS=('Bd', 'It', 'MoBI', 'Mono', 'Se', 'BI', 'MoBd', 'MoIt', 'SeBd', '') 
     62    ALL_FONTS = ('Bd', 'It', 'MoBI', 'Mono', 'Se', 
     63                 'BI', 'MoBd', 'MoIt', 'SeBd', '') 
    6064    rand_font = random.choice(ALL_FONTS) 
    61     font = ImageFont.truetype(FONT_PATH+'/vera/Vera%s.ttf'%rand_font, fnt_sz) 
     65    rand_font_path = FONT_PATH + '/vera/Vera%s.ttf' % rand_font 
     66    font = ImageFont.truetype(rand_font_path, fnt_sz) 
    6267    textSize = font.getsize(text) 
    6368 
    6469#------------------------------render   background1 ----------------------- 
    65     image = Image.new('RGB', (textSize[0]+7,textSize[1]+7), bkground) 
     70    image = Image.new('RGB', (textSize[0] + 7, textSize[1] + 7), bkground) 
    6671    image.paste(bkground) 
    6772#------------------------------render       Text2 ------------------------ 
    6873    draw = ImageDraw.Draw(image) 
    69     alignment = (random.uniform(0,1), random.uniform(0,1)) 
     74    alignment = (random.uniform(0, 1), random.uniform(0, 1)) 
    7075    x = int((image.size[0] - textSize[0]) * alignment[0] + 0.5) 
    7176    y = int((image.size[1] - textSize[1]) * alignment[1] + 0.5) 
    7277 
    73     draw.text((x,y), text, font=font, fill=font_color) 
     78    draw.text((x, y), text, font=font, fill=font_color) 
    7479 
    7580#------------------------------render       Distortion ----------------------- 
     
    8590        yRow = [] 
    8691        for i in xrange(xPoints): 
    87             x, y = getTransform(i*r, j*r, amplitude, period, offset) 
     92            x, y = getTransform(i * r, j * r, amplitude, period, offset) 
    8893 
    8994            # Clamp the edges so we don't get black undefined areas 
    90             x = max(0, min(image.size[0]-1, x)) 
    91             y = max(0, min(image.size[1]-1, y)) 
     95            x = max(0, min(image.size[0] - 1, x)) 
     96            y = max(0, min(image.size[1] - 1, y)) 
    9297 
    9398            xRow.append(x) 
     
    99104    # each square between points on the grid 
    100105    mesh = [] 
    101     for j in xrange(yPoints-1): 
    102         for i in xrange(xPoints-1): 
     106    for j in xrange(yPoints - 1): 
     107        for i in xrange(xPoints - 1): 
    103108            mesh.append(( 
    104109                # Destination rectangle 
    105                 (i*r, j*r, 
    106                  (i+1)*r, (j+1)*r), 
     110                (i * r, j * r, 
     111                 (i + 1) * r, (j + 1) * r), 
    107112                # Source quadrilateral 
    108                 (xRows[j  ][i  ], yRows[j  ][i  ], 
    109                  xRows[j+1][i  ], yRows[j+1][i  ], 
    110                  xRows[j+1][i+1], yRows[j+1][i+1], 
    111                  xRows[j  ][i+1], yRows[j  ][i+1]), 
     113                (xRows[j][i],         yRows[j][i], 
     114                 xRows[j + 1][i],     yRows[j + 1][i], 
     115                 xRows[j + 1][i + 1], yRows[j + 1][i + 1], 
     116                 xRows[j][i + 1],     yRows[j][i + 1]), 
    112117                )) 
    113118 
     
    120125    size = len(src) 
    121126    sys.modules['ImageFile'] = ImageFile 
    122     return {'src':src, 'size':size} 
     127    return {'src': src, 'size': size} 
    123128 
    124129 
     
    127132    return words[index] 
    128133 
     134 
    129135def getIndex(word): 
    130136    words = basic_english.words.split() 
     
    132138        res = words.index(word) 
    133139    except ValueError: 
    134         res = getLen()+1 
     140        res = getLen() + 1 
    135141    return res 
     142 
    136143 
    137144def getCaptchasCount(dynamic): 
     
    141148        return CAPTCHAS_COUNT 
    142149 
     150 
    143151def formKey(num): 
    144152    def normalize(s): 
    145         return (not len(s)%8 and s) or normalize(s+str(randint(0, 9))) 
     153        return (not len(s) % 8 and s) or normalize(s + str(randint(0, 9))) 
    146154 
    147     return normalize('%s_%i_'%(str(DateTime().timeTime()), num)) 
     155    return normalize('%s_%i_' % (str(DateTime().timeTime()), num)) 
     156 
    148157 
    149158def encrypt(key, s): 
    150159    return toHex(Crypto.new(key).encrypt(s)) 
    151160 
     161 
    152162def decrypt(key, s): 
    153163    return Crypto.new(key).decrypt(toStr(s)) 
     164 
    154165 
    155166def parseKey(s): 
     
    157168    if ps is None: 
    158169        return {'date': '', 'key': ''} 
    159     return {'date': ps.group(1), 'key':ps.group(2)} 
     170    return {'date': ps.group(1), 'key': ps.group(2)} 
     171 
    160172 
    161173def toHex(s): 
     
    164176        hv = hex(ord(ch)).replace('0x', '') 
    165177        if len(hv) == 1: 
    166             hv = '0'+hv 
     178            hv = '0' + hv 
    167179        lst.append(hv) 
    168180 
    169     return reduce(lambda x,y:x+y, lst) 
     181    return reduce(lambda x, y: x + y, lst) 
     182 
    170183 
    171184def toStr(s): 
  • quintagroup.captcha.core/trunk/setup.py

    r2820 r3128  
    99      long_description=open("README.txt").read() + "\n" + 
    1010                       open(os.path.join("docs", "HISTORY.txt")).read(), 
    11       # Get more strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers 
    1211      classifiers=[ 
    1312        "Framework :: Plone", 
Note: See TracChangeset for help on using the changeset viewer.