Skip to content
This repository has been archived by the owner on Jan 25, 2018. It is now read-only.

Commit

Permalink
Merge pull request #314 from andymckay/pep8
Browse files Browse the repository at this point in the history
Pep8
  • Loading branch information
Andy McKay committed Feb 4, 2015
2 parents 175dc7e + 656c419 commit e838efe
Show file tree
Hide file tree
Showing 54 changed files with 327 additions and 245 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Expand Up @@ -10,6 +10,7 @@ install:
- pip install --no-deps -r requirements/test.txt --find-links https://pyrepo.addons.mozilla.org/
before_script:
- mysql -e 'create database solitude;'
- flake8 . --exclude=./docs/conf.py
script: ./manage.py test --noinput -s
notifications:
irc:
Expand Down
16 changes: 11 additions & 5 deletions bin/update/deploy.py
Expand Up @@ -14,24 +14,27 @@
from commander.deploy import task, hostgroups, BadReturnCode
import commander_settings as settings


@task
def create_virtualenv(ctx):
venv = settings.VIRTUAL_ENV
if not venv.startswith('/data'):
raise Exception('venv must start with /data') # this is just to avoid rm'ing /
# this is just to avoid rm'ing /
raise Exception('venv must start with /data')

ctx.local('rm -rf %s' % venv)

try:
try:
ctx.local("virtualenv --distribute --never-download %s" % venv)
except BadReturnCode:
pass # if this is really broken, then the pip install should fail
# if this is really broken, then the pip install should fail
pass

ctx.local("%s/bin/pip install --exists-action=w --no-deps --no-index "
"--download-cache=/tmp/pip-cache -f %s "
"-r %s/requirements/prod.txt" %
(venv, settings.PYREPO, settings.SRC_DIR))
(venv, settings.PYREPO, settings.SRC_DIR))
finally:
# make sure this always runs
ctx.local("rm -f %s/lib/python2.6/no-global-site-packages.txt" % venv)
Expand Down Expand Up @@ -68,7 +71,8 @@ def update_assets(ctx):
with ctx.lcd(settings.SRC_DIR):
ctx.local("%s manage.py collectstatic --noinput" % settings.PYTHON)
# LANG=en_US.UTF-8 is sometimes necessary for the YUICompressor.
ctx.local('LANG=en_US.UTF8 %s manage.py compress_assets' % settings.PYTHON)
ctx.local('LANG=en_US.UTF8 %s manage.py compress_assets'
% settings.PYTHON)


@task
Expand All @@ -83,13 +87,15 @@ def update_db(ctx):
ctx.local("%s %s/bin/schematic migrations" %
(settings.PYTHON, settings.VIRTUAL_ENV))


@task
def checkin_changes(ctx):
"""Use the local, IT-written deploy script to check in changes."""
ctx.local(settings.DEPLOY_SCRIPT)


@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
@hostgroups(settings.WEB_HOSTGROUP,
remote_kwargs={'ssh_key': settings.SSH_KEY})
def deploy_app(ctx):
"""Call the remote update script to push changes to webheads."""
ctx.remote(settings.REMOTE_UPDATE_SCRIPT)
Expand Down
9 changes: 5 additions & 4 deletions bin/update_site.py
Expand Up @@ -14,13 +14,13 @@

import os
import sys
from textwrap import dedent
from optparse import OptionParser
from hashlib import md5
from optparse import OptionParser
from textwrap import dedent

# Constants
PROJECT = 0
VENDOR = 1
VENDOR = 1

ENV_BRANCH = {
# 'environment': [PROJECT_BRANCH, VENDOR_BRANCH],
Expand All @@ -32,7 +32,8 @@
# The URL of the SVN repository with the localization files (*.po). If you set
# it to a non-empty value, remember to `git rm --cached -r locale` in the root
# of the project. Example:
# LOCALE_REPO_URL = 'https://svn.mozilla.org/projects/l10n-misc/trunk/playdoh/locale'
# LOCALE_REPO_URL = ('https://svn.mozilla.org/projects/'
# 'l10n-misc/trunk/playdoh/locale')
LOCALE_REPO_URL = ''

GIT_PULL = "git pull -q origin %(branch)s"
Expand Down
6 changes: 3 additions & 3 deletions lib/bango/client.py
Expand Up @@ -21,8 +21,6 @@
INTERNAL_ERROR, SERVICE_UNAVAILABLE, WSDL_MAP,
WSDL_MAP_MANGLED)
from .errors import AuthError, BangoError, BangoFormError, ProxyError
from solitude.logger import getLogger


# Add in the list of allowed methods here.
exporter = [
Expand Down Expand Up @@ -61,10 +59,11 @@
# Status codes from the proxy that raise an error and stop processing.
FATAL_PROXY_STATUS_CODES = (404, 500,)


# Most of the names in the WSDL map easily, for example: Foo to FooRequest,
# FooResponse etc. Some do not, this is a map of the exceptions.
def name_map():
return {
return {
'request': {
# Changed with the upgrade to DirectBilling v4_1
'DoRefund': 'InnerDoRefundRequest',
Expand All @@ -74,6 +73,7 @@ def name_map():
}
}


# Map the name of the WSDL into a file. Do this dynamically so that tests
# can mess with this as they need to.
def get_wsdl(name):
Expand Down
23 changes: 12 additions & 11 deletions lib/bango/forms.py
Expand Up @@ -323,11 +323,12 @@ def clean(self):
if trans and sig:
# Both fields were non-empty so check the signature.
if not verify_sig(sig, trans.uuid):
log.info('Signature failed: %s'
% cleaned_data.get('billing_config_id'))
log.info(
'Signature failed: %s'
% cleaned_data.get('billing_config_id'))
raise forms.ValidationError(
'Signature did not match: %s for %s'
% (sig, trans.uuid))
'Signature did not match: %s for %s'
% (sig, trans.uuid))

tok = cleaned_data.get('bango_token')
if settings.CHECK_BANGO_TOKEN and tok:
Expand Down Expand Up @@ -376,9 +377,9 @@ def _check_for_tampering(self, tok, cleaned_data):
.format(true_data=true_data))
# Completely reject the form since it was tampered with.
raise forms.ValidationError(
'Form field {0} has been tampered with. '
'True: {1}; fake: {2}'.format(
form_fld, true_val, form_val))
'Form field {0} has been tampered with. '
'True: {1}; fake: {2}'.format(
form_fld, true_val, form_val))

def clean_network(self):
network = self.cleaned_data['network']
Expand All @@ -399,7 +400,6 @@ def clean_network(self):
self.cleaned_data['region'] = region
return network


def clean_moz_transaction(self):
uuid = self.cleaned_data['moz_transaction']
billing_id = self.cleaned_data.get('billing_config_id')
Expand Down Expand Up @@ -435,7 +435,7 @@ def clean(self):
username = self.cleaned_data.get('username', '')
password = self.cleaned_data.get('password', '')
if (username != settings.BANGO_BASIC_AUTH['USER'] or
password != settings.BANGO_BASIC_AUTH['PASSWORD']):
password != settings.BANGO_BASIC_AUTH['PASSWORD']):
raise forms.ValidationError('Auth incorrect')
return self.cleaned_data

Expand Down Expand Up @@ -466,7 +466,7 @@ def clean_notification(self):
# Easier to work with a dictionary than etree.
data = dict([c.values() for c in elem.getchildren()])
if (not data.get('externalCPTransId') and
not data.get('transId')):
not data.get('transId')):
raise forms.ValidationError('externalCPTransId or transId'
'required')

Expand Down Expand Up @@ -547,7 +547,8 @@ class RefundForm(forms.Form):
manual = forms.BooleanField(required=False)

def clean_uuid(self):
transaction = get_object_or_404(Transaction,
transaction = get_object_or_404(
Transaction,
uuid=self.cleaned_data['uuid'])

if transaction.provider != PROVIDER_BANGO:
Expand Down
7 changes: 5 additions & 2 deletions lib/bango/resources/package.py
Expand Up @@ -48,8 +48,11 @@ def build_bundle(self, obj=None, data=None, request=None):
def dehydrate_full(self, bundle):
if getattr(bundle, 'full', False):
return response_to_dict(
self.client('GetPackage',
{'packageId': bundle.obj.package_id}))
self.client(
'GetPackage',
{'packageId': bundle.obj.package_id}
)
)
return {}

def obj_create(self, bundle, request, **kw):
Expand Down
13 changes: 8 additions & 5 deletions lib/bango/resources/refund.py
Expand Up @@ -90,7 +90,8 @@ def obj_get(self, request, **kw):
is_manual = obj.type == TYPE_REFUND_MANUAL

try:
res = self.client('GetRefundStatus',
res = self.client(
'GetRefundStatus',
{'refundTransactionId': obj.uid_pay},
raise_on=(PENDING, CANT_REFUND, NOT_SUPPORTED),
client=self.get_client(data, fake=is_manual)
Expand Down Expand Up @@ -133,7 +134,8 @@ def obj_create(self, bundle, request, **kw):
external_uuid = str(uuid.uuid4())

try:
res = self.client('DoRefund', {
res = self.client(
'DoRefund', {
'bango': obj.seller_product.product.bango_id,
'externalTransactionId': external_uuid,
'refundType': 'OPERATOR',
Expand All @@ -148,9 +150,10 @@ def obj_create(self, bundle, request, **kw):
# this.
res = BangoResponse(exc.id, exc.message, 'todo')


status = {OK: STATUS_COMPLETED,
PENDING: STATUS_PENDING}
status = {
OK: STATUS_COMPLETED,
PENDING: STATUS_PENDING
}

# If that succeeded, create a new transaction for the refund.
obj = Transaction.objects.create(
Expand Down
6 changes: 4 additions & 2 deletions lib/bango/resources/simple.py
Expand Up @@ -47,8 +47,10 @@ class Meta(SimpleResource.Meta):

def obj_create(self, *args, **kwargs):
try:
res = super(MakePremiumResource, self).obj_create(*args,
raise_on=(BANGO_ALREADY_PREMIUM_ENABLED,), **kwargs)
res = super(MakePremiumResource, self).obj_create(
*args,
raise_on=(BANGO_ALREADY_PREMIUM_ENABLED,),
**kwargs)
except BangoFormError, exc:
# No need to fail if this is called twice, just catch and continue.
if exc.id == BANGO_ALREADY_PREMIUM_ENABLED:
Expand Down
8 changes: 4 additions & 4 deletions lib/bango/resources/status.py
Expand Up @@ -100,8 +100,8 @@ def list(self, request):
serializer = DebugSerializer(data=request.DATA)
if serializer.is_valid():
obj = serializer.object['seller_product_bango']
result = {'bango':
{
result = {
'bango': {
'environment': settings.BANGO_ENV,
'bango_id': obj.bango_id,
'package_id': obj.seller_bango.package_id,
Expand All @@ -124,8 +124,8 @@ def list(self, request):

# Show the last transaction if present.
try:
latest = obj.seller_product.transaction_set.filter(
provider=PROVIDER_BANGO).latest()
latest = (obj.seller_product.transaction_set.filter(
provider=PROVIDER_BANGO).latest())
result['bango']['last_transaction'] = {
'status': latest.status,
'url': reverse('api_dispatch_detail',
Expand Down
9 changes: 5 additions & 4 deletions lib/bango/tests/samples.py
Expand Up @@ -188,7 +188,7 @@
</data>
</event>
</eventList>
</bangoEvents>"""
</bangoEvents>""" # flake8: noqa

event_notification_no_action = """\xef\xbb\xbf<?xml version="1.0" encoding="utf-8"?>
<bangoEvents xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Expand All @@ -214,7 +214,7 @@
</data>
</event>
</eventList>
</bangoEvents>"""
</bangoEvents>""" # flake8: noqa

event_notification_cp_trans_id = """\xef\xbb\xbf<?xml version="1.0" encoding="utf-8"?>
<bangoEvents xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Expand All @@ -227,7 +227,7 @@
</data>
</event>
</eventList>
</bangoEvents>"""
</bangoEvents>""" # flake8: noqa

event_notification_no_data = """\xef\xbb\xbf<?xml version="1.0" encoding="utf-8"?>
<bangoEvents xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Expand All @@ -243,4 +243,5 @@
<action>PAYMENT</action>
</event>
</eventList>
</bangoEvents>"""
</bangoEvents>""" # flake8: noqa

2 changes: 1 addition & 1 deletion lib/bango/tests/test_client.py
Expand Up @@ -164,7 +164,7 @@ def setUp(self):
settings.ROOT,
'lib/bango/wsdl/prod/billing_configuration_v2_0.wsdl')

def test_getf_url(self):
def test_getf_url_error(self):
with self.assertRaises(KeyError):
self.cache.getf(self.url)

Expand Down
2 changes: 1 addition & 1 deletion lib/bango/tests/test_forms.py
Expand Up @@ -90,7 +90,7 @@ class TestPackage(APITest):
def test_no_auth(self, clean):
form = PackageForm(good_address)
ok_(form.is_valid())
ok_(not 'eventNotificationURL' in form.bango_data)
ok_('eventNotificationURL' not in form.bango_data)

def test_auth(self, clean):
with self.settings(BANGO_NOTIFICATION_URL='http://f.com',
Expand Down
3 changes: 2 additions & 1 deletion lib/bango/urls.py
Expand Up @@ -32,7 +32,8 @@
bango_drf.register('status', StatusViewSet)
bango_drf.register('debug', DebugViewSet, base_name='debug')

urlpatterns = patterns('',
urlpatterns = patterns(
'',
url(r'^login/', login, name='bango.login'),
url(r'^', include(bango_drf.urls)),
)
6 changes: 4 additions & 2 deletions lib/buyers/tests/test_models.py
Expand Up @@ -97,13 +97,15 @@ def test_clear_was_locked_out(self):
assert not self.buyer.pin_was_locked_out

def test_under_timeout(self):
self.buyer.pin_locked_out = (datetime.now() -
self.buyer.pin_locked_out = (
datetime.now() -
timedelta(seconds=settings.PIN_FAILURE_LENGTH - 60))
self.buyer.save()
assert self.buyer.locked_out

def test_over_timeout(self):
self.buyer.pin_locked_out = (datetime.now() -
self.buyer.pin_locked_out = (
datetime.now() -
timedelta(seconds=settings.PIN_FAILURE_LENGTH + 60))
self.buyer.save()
assert not self.buyer.locked_out
Expand Down
20 changes: 12 additions & 8 deletions lib/paypal/client.py
Expand Up @@ -144,11 +144,12 @@ def headers(self, url, auth_token=None):
}

if auth_token:
ts, sig = get_auth_header(auth['USER'], auth['PASSWORD'],
auth_token['token'], auth_token['secret'], 'POST', url)
ts, sig = get_auth_header(
auth['USER'], auth['PASSWORD'],
auth_token['token'], auth_token['secret'], 'POST', url)
headers['X-PAYPAL-AUTHORIZATION'] = (
'timestamp=%s,token=%s,signature=%s' %
(ts, auth_token['token'], sig))
'timestamp=%s,token=%s,signature=%s' %
(ts, auth_token['token'], sig))

else:
headers.update({
Expand Down Expand Up @@ -376,7 +377,7 @@ def get_ipn_verify(self, raw):

if res != 'VERIFIED':
log.info('Verification failed.')
#TODO(andym): CEF logging here.
# TODO(andym): CEF logging here.
return False
return True

Expand Down Expand Up @@ -445,9 +446,12 @@ def get_preapproval_key(self, start, end, return_url, cancel_url):

def get_permission_url(self, url, scope):
"""As with get_preapproval_key, skip PayPal."""
return {'token': url +
'&request_token=get-permission-url:%s' % get_uuid() +
'&verification_code=get-permission-url:%s' % get_uuid()}
return {
'token':
url +
'&request_token=get-permission-url:%s' % get_uuid() +
'&verification_code=get-permission-url:%s' % get_uuid()
}

def get_pay_key(self, seller_email, amount, ipn_url, cancel_url,
return_url, currency='USD', preapproval=None, memo='',
Expand Down

0 comments on commit e838efe

Please sign in to comment.