more coverage
This commit is contained in:
@@ -79,10 +79,10 @@ class UserAdmin(admin.ModelAdmin):
|
|||||||
|
|
||||||
search_fields = ["username","first_name","last_name","email"]
|
search_fields = ["username","first_name","last_name","email"]
|
||||||
|
|
||||||
def rowerplan(self, obj):
|
def rowerplan(self, obj): # pragma: no cover
|
||||||
return obj.rower.rowerplan
|
return obj.rower.rowerplan
|
||||||
|
|
||||||
def clubsize(self, obj):
|
def clubsize(self, obj): # pragma: no cover
|
||||||
return obj.rower.clubsize
|
return obj.rower.clubsize
|
||||||
|
|
||||||
class WorkoutAdmin(admin.ModelAdmin):
|
class WorkoutAdmin(admin.ModelAdmin):
|
||||||
|
|||||||
@@ -62,7 +62,10 @@ def process_webhook(notification):
|
|||||||
with open('braintreewebhooks.log','a') as f:
|
with open('braintreewebhooks.log','a') as f:
|
||||||
t = time.localtime()
|
t = time.localtime()
|
||||||
timestamp = time.strftime('%b-%d-%Y_%H%M', t)
|
timestamp = time.strftime('%b-%d-%Y_%H%M', t)
|
||||||
f.write(timestamp+' '+notification.kind+'\n')
|
try:
|
||||||
|
f.write(timestamp+' '+notification.kind+'\n')
|
||||||
|
except TypeError:
|
||||||
|
f.write(timestamp+'\n')
|
||||||
if notification.kind == 'subscription_charged_successfully':
|
if notification.kind == 'subscription_charged_successfully':
|
||||||
return send_invoice(notification.subscription)
|
return send_invoice(notification.subscription)
|
||||||
if notification.kind == 'subscription_canceled':
|
if notification.kind == 'subscription_canceled':
|
||||||
@@ -80,7 +83,7 @@ def process_webhook(notification):
|
|||||||
return subscription.id
|
return subscription.id
|
||||||
with open('braintreewebhooks.log','a') as f: # pragma: no cover
|
with open('braintreewebhooks.log','a') as f: # pragma: no cover
|
||||||
f.write('Could not cancel Subscription: '+str(subscription.id)+'\n')
|
f.write('Could not cancel Subscription: '+str(subscription.id)+'\n')
|
||||||
return 0
|
return 0 # pragma: no cover
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
def send_invoice(subscription):
|
def send_invoice(subscription):
|
||||||
@@ -207,8 +210,11 @@ def make_payment(rower,data):
|
|||||||
id = fakturoid.create_invoice(rower,amount,transaction.id,dosend=True,contact_id=fakturoid_contact_id,
|
id = fakturoid.create_invoice(rower,amount,transaction.id,dosend=True,contact_id=fakturoid_contact_id,
|
||||||
name='Rowsandall Purchase')
|
name='Rowsandall Purchase')
|
||||||
|
|
||||||
job = myqueue(queuehigh,handle_send_email_transaction,
|
try:
|
||||||
name, rower.user.email, amount)
|
job = myqueue(queuehigh,handle_send_email_transaction,
|
||||||
|
name, rower.user.email, amount)
|
||||||
|
except: # pragma: no cover
|
||||||
|
pass
|
||||||
|
|
||||||
return amount,True
|
return amount,True
|
||||||
else: # pragma: no cover
|
else: # pragma: no cover
|
||||||
@@ -220,7 +226,7 @@ def update_subscription(rower,data,method='up'):
|
|||||||
nonce_from_the_client = data['payment_method_nonce']
|
nonce_from_the_client = data['payment_method_nonce']
|
||||||
nonce = gateway.payment_method_nonce.find(nonce_from_the_client)
|
nonce = gateway.payment_method_nonce.find(nonce_from_the_client)
|
||||||
info = nonce.three_d_secure_info
|
info = nonce.three_d_secure_info
|
||||||
if nonce.type.lower() == 'creditcard':
|
if nonce.type.lower() == 'creditcard': # pragma: no cover
|
||||||
if info is None or not info.liability_shifted:
|
if info is None or not info.liability_shifted:
|
||||||
return False,0
|
return False,0
|
||||||
amount = data['amount']
|
amount = data['amount']
|
||||||
@@ -239,7 +245,7 @@ def update_subscription(rower,data,method='up'):
|
|||||||
|
|
||||||
if plan.paymenttype == 'single':
|
if plan.paymenttype == 'single':
|
||||||
gatewaydata['number_of_billing_cycles'] = 1
|
gatewaydata['number_of_billing_cycles'] = 1
|
||||||
else:
|
else: # pragma: no cover
|
||||||
gatewaydata['never_expires'] = True
|
gatewaydata['never_expires'] = True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -247,7 +253,7 @@ def update_subscription(rower,data,method='up'):
|
|||||||
rower.subscription_id,
|
rower.subscription_id,
|
||||||
gatewaydata
|
gatewaydata
|
||||||
)
|
)
|
||||||
except:
|
except: # pragma: no cover
|
||||||
return False,0
|
return False,0
|
||||||
|
|
||||||
if result.is_success:
|
if result.is_success:
|
||||||
@@ -270,14 +276,14 @@ def update_subscription(rower,data,method='up'):
|
|||||||
if rower.paidplan != 'coach':
|
if rower.paidplan != 'coach':
|
||||||
try:
|
try:
|
||||||
coachgroup = rower.mycoachgroup
|
coachgroup = rower.mycoachgroup
|
||||||
except CoachingGroup.DoesNotExist:
|
except CoachingGroup.DoesNotExist: # pragma: no cover
|
||||||
coachgroup = CoachingGroup()
|
coachgroup = CoachingGroup()
|
||||||
coachgroup.save()
|
coachgroup.save()
|
||||||
rower.mycoachgroup = coachgroup
|
rower.mycoachgroup = coachgroup
|
||||||
rower.save()
|
rower.save()
|
||||||
|
|
||||||
athletes = Rower.objects.filter(coachinggroups__in=[rower.mycoachgroup]).distinct()
|
athletes = Rower.objects.filter(coachinggroups__in=[rower.mycoachgroup]).distinct()
|
||||||
for athlete in athletes:
|
for athlete in athletes: # pragma: no cover
|
||||||
athlete.coachinggroups.remove(rower.mycoachgroup)
|
athlete.coachinggroups.remove(rower.mycoachgroup)
|
||||||
|
|
||||||
if method == 'up':
|
if method == 'up':
|
||||||
@@ -285,9 +291,9 @@ def update_subscription(rower,data,method='up'):
|
|||||||
|
|
||||||
if transactions:
|
if transactions:
|
||||||
amount = transactions[0].amount
|
amount = transactions[0].amount
|
||||||
else:
|
else: # pragma: no cover
|
||||||
amount = 0
|
amount = 0
|
||||||
else:
|
else: # pragma: no cover
|
||||||
amount = 0
|
amount = 0
|
||||||
|
|
||||||
|
|
||||||
@@ -302,7 +308,7 @@ def update_subscription(rower,data,method='up'):
|
|||||||
method)
|
method)
|
||||||
|
|
||||||
return True,amount
|
return True,amount
|
||||||
else:
|
else: # pragma: no cover
|
||||||
errors = result.errors.for_object("subscription")
|
errors = result.errors.for_object("subscription")
|
||||||
codes = [str(e.code) for e in errors]
|
codes = [str(e.code) for e in errors]
|
||||||
create_new = False
|
create_new = False
|
||||||
@@ -325,7 +331,7 @@ def create_subscription(rower,data):
|
|||||||
info = nonce.three_d_secure_info
|
info = nonce.three_d_secure_info
|
||||||
paymenttype = nonce.type
|
paymenttype = nonce.type
|
||||||
|
|
||||||
if nonce.type != 'PayPalAccount':
|
if nonce.type != 'PayPalAccount': # pragma: no cover
|
||||||
if info is None or not info.liability_shifted:
|
if info is None or not info.liability_shifted:
|
||||||
return False,0
|
return False,0
|
||||||
amount = data['amount']
|
amount = data['amount']
|
||||||
@@ -344,7 +350,7 @@ def create_subscription(rower,data):
|
|||||||
|
|
||||||
if result.is_success:
|
if result.is_success:
|
||||||
payment_method_token = result.payment_method.token
|
payment_method_token = result.payment_method.token
|
||||||
else:
|
else: # pragma: no cover
|
||||||
return False,0
|
return False,0
|
||||||
|
|
||||||
result = gateway.subscription.create({
|
result = gateway.subscription.create({
|
||||||
@@ -385,11 +391,11 @@ def create_subscription(rower,data):
|
|||||||
result.subscription.billing_period_end_date.strftime('%Y-%m-%d')
|
result.subscription.billing_period_end_date.strftime('%Y-%m-%d')
|
||||||
)
|
)
|
||||||
return True,plan.price
|
return True,plan.price
|
||||||
else:
|
else: # pragma: no cover
|
||||||
return False,0
|
return False,0
|
||||||
|
|
||||||
|
|
||||||
return False,0
|
return False,0 # pragma: no cover
|
||||||
|
|
||||||
def cancel_subscription(rower,id):
|
def cancel_subscription(rower,id):
|
||||||
themessages = []
|
themessages = []
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ class GroupedModelChoiceIterator(ModelChoiceIterator):
|
|||||||
super().__init__(field)
|
super().__init__(field)
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
if self.field.empty_label is not None:
|
if self.field.empty_label is not None: # pragma: no cover
|
||||||
yield ("", self.field.empty_label)
|
yield ("", self.field.empty_label)
|
||||||
queryset = self.queryset
|
queryset = self.queryset
|
||||||
# Can't use iterator() when queryset uses prefetch_related()
|
# Can't use iterator() when queryset uses prefetch_related()
|
||||||
@@ -25,7 +25,7 @@ class GroupedModelChoiceField(ModelChoiceField):
|
|||||||
def __init__(self, *args, choices_groupby, **kwargs):
|
def __init__(self, *args, choices_groupby, **kwargs):
|
||||||
if isinstance(choices_groupby, str):
|
if isinstance(choices_groupby, str):
|
||||||
choices_groupby = attrgetter(choices_groupby)
|
choices_groupby = attrgetter(choices_groupby)
|
||||||
elif not callable(choices_groupby):
|
elif not callable(choices_groupby): # pragma: no cover
|
||||||
raise TypeError('choices_groupby must either be a str or a callable accepting a single argument')
|
raise TypeError('choices_groupby must either be a str or a callable accepting a single argument')
|
||||||
self.iterator = partial(GroupedModelChoiceIterator, groupby=choices_groupby)
|
self.iterator = partial(GroupedModelChoiceIterator, groupby=choices_groupby)
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ columns = {
|
|||||||
'bikeCadenceInRPM':' Cadence (stokes/min)',
|
'bikeCadenceInRPM':' Cadence (stokes/min)',
|
||||||
}
|
}
|
||||||
|
|
||||||
def garmin_authorize():
|
def garmin_authorize(): # pragma: no cover
|
||||||
redirect_uri = oauth_data['redirect_uri']
|
redirect_uri = oauth_data['redirect_uri']
|
||||||
client_secret = oauth_data['client_secret']
|
client_secret = oauth_data['client_secret']
|
||||||
client_id = oauth_data['client_id']
|
client_id = oauth_data['client_id']
|
||||||
@@ -98,7 +98,7 @@ def garmin_authorize():
|
|||||||
authorization_url = garmin.authorization_url(base_uri)
|
authorization_url = garmin.authorization_url(base_uri)
|
||||||
return authorization_url,resource_owner_key,resource_owner_secret
|
return authorization_url,resource_owner_key,resource_owner_secret
|
||||||
|
|
||||||
def garmin_processcallback(redirect_response,resource_owner_key,resource_owner_secret):
|
def garmin_processcallback(redirect_response,resource_owner_key,resource_owner_secret): # pragma: no cover
|
||||||
garmin = OAuth1Session(oauth_data['client_id'],
|
garmin = OAuth1Session(oauth_data['client_id'],
|
||||||
client_secret=oauth_data['client_secret'],
|
client_secret=oauth_data['client_secret'],
|
||||||
)
|
)
|
||||||
@@ -124,7 +124,7 @@ def garmin_processcallback(redirect_response,resource_owner_key,resource_owner_s
|
|||||||
|
|
||||||
return garmintoken,garminrefreshtoken
|
return garmintoken,garminrefreshtoken
|
||||||
|
|
||||||
def garmin_open(user):
|
def garmin_open(user): # pragma: no cover
|
||||||
r = Rower.objects.get(user=user)
|
r = Rower.objects.get(user=user)
|
||||||
token = Rower.garmintoken
|
token = Rower.garmintoken
|
||||||
|
|
||||||
@@ -148,7 +148,7 @@ def get_garmin_file(r,callbackURL,starttime,fileType):
|
|||||||
|
|
||||||
return job.id
|
return job.id
|
||||||
|
|
||||||
def get_garmin_workout_list(user):
|
def get_garmin_workout_list(user): # pragma: no cover
|
||||||
r = Rower.objects.get(user=user)
|
r = Rower.objects.get(user=user)
|
||||||
if (r.garmintoken == '') or (r.garmintoken is None):
|
if (r.garmintoken == '') or (r.garmintoken is None):
|
||||||
s = "Token doesn't exist. Need to authorize"
|
s = "Token doesn't exist. Need to authorize"
|
||||||
@@ -166,7 +166,7 @@ def get_garmin_workout_list(user):
|
|||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def garmin_can_export_session(user):
|
def garmin_can_export_session(user): # pragma: no cover
|
||||||
result = get_garmin_permissions(user)
|
result = get_garmin_permissions(user)
|
||||||
if 'WORKOUT_IMPORT' in result:
|
if 'WORKOUT_IMPORT' in result:
|
||||||
return True
|
return True
|
||||||
@@ -184,42 +184,42 @@ def step_to_garmin(step,order=0):
|
|||||||
except KeyError:
|
except KeyError:
|
||||||
intensity = None
|
intensity = None
|
||||||
#durationvaluetype = ''
|
#durationvaluetype = ''
|
||||||
if durationtype == 'Time':
|
if durationtype == 'Time': # pragma: no cover
|
||||||
durationtype = 'TIME'
|
durationtype = 'TIME'
|
||||||
durationvalue = int(durationvalue/1000.)
|
durationvalue = int(durationvalue/1000.)
|
||||||
elif durationtype == 'Distance':
|
elif durationtype == 'Distance': # pragma: no cover
|
||||||
durationtype = 'DISTANCE'
|
durationtype = 'DISTANCE'
|
||||||
durationvalue = int(durationvalue/100)
|
durationvalue = int(durationvalue/100)
|
||||||
durationvaluetype = 'METER'
|
durationvaluetype = 'METER'
|
||||||
elif durationtype == 'HrLessThan':
|
elif durationtype == 'HrLessThan': # pragma: no cover
|
||||||
durationtype = 'HR_LESS_THAN'
|
durationtype = 'HR_LESS_THAN'
|
||||||
if durationvalue <= 100:
|
if durationvalue <= 100:
|
||||||
durationvaluetype = 'PERCENT'
|
durationvaluetype = 'PERCENT'
|
||||||
else:
|
else:
|
||||||
durationvaluetype = ''
|
durationvaluetype = ''
|
||||||
durationvalue -= 100
|
durationvalue -= 100
|
||||||
elif durationtype == 'HrGreaterThan':
|
elif durationtype == 'HrGreaterThan': # pragma: no cover
|
||||||
durationtype = 'HR_GREATER_THAN'
|
durationtype = 'HR_GREATER_THAN'
|
||||||
if durationvalue <= 100:
|
if durationvalue <= 100:
|
||||||
durationvaluetype = 'PERCENT'
|
durationvaluetype = 'PERCENT'
|
||||||
else:
|
else:
|
||||||
durationvaluetype = ''
|
durationvaluetype = ''
|
||||||
durationvalue -= 100
|
durationvalue -= 100
|
||||||
elif durationtype == 'PowerLessThan':
|
elif durationtype == 'PowerLessThan': # pragma: no cover
|
||||||
durationtype = 'POWER_LESS_THAN'
|
durationtype = 'POWER_LESS_THAN'
|
||||||
if durationvalue <= 1000:
|
if durationvalue <= 1000:
|
||||||
durationvaluetype = 'PERCENT'
|
durationvaluetype = 'PERCENT'
|
||||||
else:
|
else:
|
||||||
durationvaluetype = ''
|
durationvaluetype = ''
|
||||||
durationvalue -= 1000
|
durationvalue -= 1000
|
||||||
elif durationtype == 'PowerGreaterThan':
|
elif durationtype == 'PowerGreaterThan': # pragma: no cover
|
||||||
durationtype = 'POWER_GREATER_THAN'
|
durationtype = 'POWER_GREATER_THAN'
|
||||||
if durationvalue <= 1000:
|
if durationvalue <= 1000:
|
||||||
durationvaluetype = 'PERCENT'
|
durationvaluetype = 'PERCENT'
|
||||||
else:
|
else:
|
||||||
durationvaluetype = ''
|
durationvaluetype = ''
|
||||||
durationvalue -= 1000
|
durationvalue -= 1000
|
||||||
elif durationtype == 'Reps':
|
elif durationtype == 'Reps': # pragma: no cover
|
||||||
durationtype = 'REPS'
|
durationtype = 'REPS'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -337,7 +337,7 @@ def ps_to_garmin(ps,r):
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
def get_garmin_permissions(user):
|
def get_garmin_permissions(user): # pragma: no cover
|
||||||
r = Rower.objects.get(user=user)
|
r = Rower.objects.get(user=user)
|
||||||
if (r.garmintoken == '') or (r.garmintoken is None):
|
if (r.garmintoken == '') or (r.garmintoken is None):
|
||||||
s = "Token doesn't exist. Need to authorize"
|
s = "Token doesn't exist. Need to authorize"
|
||||||
@@ -358,7 +358,7 @@ def get_garmin_permissions(user):
|
|||||||
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def garmin_session_create(ps,user):
|
def garmin_session_create(ps,user): # pragma: no cover
|
||||||
if not ps.steps:
|
if not ps.steps:
|
||||||
return 0
|
return 0
|
||||||
if not garmin_can_export_session(user):
|
if not garmin_can_export_session(user):
|
||||||
@@ -391,7 +391,7 @@ def garmin_getworkout(garminid,r,activity):
|
|||||||
startdatetime = arrow.get(starttime)
|
startdatetime = arrow.get(starttime)
|
||||||
try:
|
try:
|
||||||
offset = activity['startTimeOffsetInSeconds']
|
offset = activity['startTimeOffsetInSeconds']
|
||||||
except KeyError:
|
except KeyError: # pragma: no cover
|
||||||
offset = 0
|
offset = 0
|
||||||
durationseconds = activity['durationInSeconds']
|
durationseconds = activity['durationInSeconds']
|
||||||
duration = dataprep.totaltime_sec_to_string(durationseconds)
|
duration = dataprep.totaltime_sec_to_string(durationseconds)
|
||||||
@@ -405,7 +405,7 @@ def garmin_getworkout(garminid,r,activity):
|
|||||||
try:
|
try:
|
||||||
averagehr = activity['averageHeartRateInBeatsPerMinute']
|
averagehr = activity['averageHeartRateInBeatsPerMinute']
|
||||||
maxhr = activity['maxHeartRateInBeatsPerMinute']
|
maxhr = activity['maxHeartRateInBeatsPerMinute']
|
||||||
except KeyError:
|
except KeyError: # pragma: no cover
|
||||||
averagehr = 0
|
averagehr = 0
|
||||||
maxhr = 0
|
maxhr = 0
|
||||||
try:
|
try:
|
||||||
@@ -421,11 +421,11 @@ def garmin_getworkout(garminid,r,activity):
|
|||||||
now = datetime.datetime.now(pytz.utc)
|
now = datetime.datetime.now(pytz.utc)
|
||||||
zones = [tz.zone for tz in map(pytz.timezone, pytz.all_timezones_set)
|
zones = [tz.zone for tz in map(pytz.timezone, pytz.all_timezones_set)
|
||||||
if now.astimezone(tz).utcoffset() == utc_offset]
|
if now.astimezone(tz).utcoffset() == utc_offset]
|
||||||
if r.defaulttimezone in zones:
|
if r.defaulttimezone in zones: # pragma: no cover
|
||||||
thetimezone = r.defaulttimezone
|
thetimezone = r.defaulttimezone
|
||||||
elif len(zones):
|
elif len(zones):
|
||||||
thetimezone = zones[0]
|
thetimezone = zones[0]
|
||||||
else:
|
else: # pragma: no cover
|
||||||
thetimezone = utc
|
thetimezone = utc
|
||||||
|
|
||||||
startdatetime = datetime.datetime(
|
startdatetime = datetime.datetime(
|
||||||
@@ -441,11 +441,11 @@ def garmin_getworkout(garminid,r,activity):
|
|||||||
w.starttime = w.startdatetime.time()
|
w.starttime = w.startdatetime.time()
|
||||||
try:
|
try:
|
||||||
w.duration = datetime.datetime.strptime(duration,"%H:%M:%S.%f").time()
|
w.duration = datetime.datetime.strptime(duration,"%H:%M:%S.%f").time()
|
||||||
except ValueError:
|
except ValueError: # pragma: no cover
|
||||||
w.duration = datetime.datetime.strptime(duration,"%H:%M:%S")
|
w.duration = datetime.datetime.strptime(duration,"%H:%M:%S")
|
||||||
try:
|
try:
|
||||||
w.workouttype = mytypes.garminmappinginv[activitytype]
|
w.workouttype = mytypes.garminmappinginv[activitytype]
|
||||||
except KeyError:
|
except KeyError: # pragma: no cover
|
||||||
w.workouttype = 'other'
|
w.workouttype = 'other'
|
||||||
w.name = name
|
w.name = name
|
||||||
w.date = date
|
w.date = date
|
||||||
@@ -460,7 +460,7 @@ def garmin_getworkout(garminid,r,activity):
|
|||||||
def garmin_workouts_from_details(data):
|
def garmin_workouts_from_details(data):
|
||||||
activities = data['activityDetails']
|
activities = data['activityDetails']
|
||||||
for activity in activities:
|
for activity in activities:
|
||||||
try:
|
try: # pragma: no cover
|
||||||
garmintoken = activity['userAccessToken']
|
garmintoken = activity['userAccessToken']
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return 0
|
return 0
|
||||||
@@ -503,7 +503,7 @@ def garmin_workouts_from_details(data):
|
|||||||
w.save()
|
w.save()
|
||||||
trimp,hrtss = dataprep.workout_trimp(w)
|
trimp,hrtss = dataprep.workout_trimp(w)
|
||||||
rscore,normp = dataprep.workout_rscore(w)
|
rscore,normp = dataprep.workout_rscore(w)
|
||||||
except Rower.DoesNotExist:
|
except Rower.DoesNotExist: # pragma: no cover
|
||||||
pass
|
pass
|
||||||
|
|
||||||
return 1
|
return 1
|
||||||
@@ -515,7 +515,7 @@ def garmin_workouts_from_summaries(activities):
|
|||||||
r = Rower.objects.get(garmintoken=garmintoken)
|
r = Rower.objects.get(garmintoken=garmintoken)
|
||||||
id = activity['summaryId']
|
id = activity['summaryId']
|
||||||
w = garmin_getworkout(id,r,activity)
|
w = garmin_getworkout(id,r,activity)
|
||||||
except Rower.DoesNotExist:
|
except Rower.DoesNotExist: # pragma: no cover
|
||||||
pass
|
pass
|
||||||
|
|
||||||
return 1
|
return 1
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ class OpaqueEncoder:
|
|||||||
"""Transcode an integer and return it as an 8-character hex string."""
|
"""Transcode an integer and return it as an 8-character hex string."""
|
||||||
return "%08x" % self.transcode(i)
|
return "%08x" % self.transcode(i)
|
||||||
|
|
||||||
def encode_base64(self, i):
|
def encode_base64(self, i): # pragma: no cover
|
||||||
"""Transcode an integer and return it as a 6-character base64 string."""
|
"""Transcode an integer and return it as a 6-character base64 string."""
|
||||||
return base64.b64encode(struct.pack('!L', self.transcode(i)), self.extra_chars)[:6]
|
return base64.b64encode(struct.pack('!L', self.transcode(i)), self.extra_chars)[:6]
|
||||||
|
|
||||||
@@ -56,7 +56,7 @@ class OpaqueEncoder:
|
|||||||
"""Decode an 8-character hex string, returning the original integer."""
|
"""Decode an 8-character hex string, returning the original integer."""
|
||||||
return self.transcode(int(str(s), 16))
|
return self.transcode(int(str(s), 16))
|
||||||
|
|
||||||
def decode_base64(self, s):
|
def decode_base64(self, s): # pragma: no cover
|
||||||
"""Decode a 6-character base64 string, returning the original integer."""
|
"""Decode a 6-character base64 string, returning the original integer."""
|
||||||
return self.transcode(struct.unpack('!L', base64.b64decode(s + '==', self.extra_chars))[0])
|
return self.transcode(struct.unpack('!L', base64.b64decode(s + '==', self.extra_chars))[0])
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from __future__ import unicode_literals
|
|||||||
from rowers.models import Rower,PaidPlan
|
from rowers.models import Rower,PaidPlan
|
||||||
|
|
||||||
# run once - copies plans to paypal
|
# run once - copies plans to paypal
|
||||||
def planstopaypal():
|
def planstopaypal(): # pragma: no cover
|
||||||
plans = PaidPlan.objects.all()
|
plans = PaidPlan.objects.all()
|
||||||
|
|
||||||
for plan in plans:
|
for plan in plans:
|
||||||
@@ -14,32 +14,8 @@ def planstopaypal():
|
|||||||
plan.external_id = None
|
plan.external_id = None
|
||||||
plan.save()
|
plan.save()
|
||||||
|
|
||||||
#def initiaterowerplans():
|
|
||||||
# rowers = Rower.objects.filter(paymenttype = 'recurring',paidplan = None)
|
|
||||||
# for r in rowers:
|
|
||||||
# r.paymentprocessor = 'paypal'
|
|
||||||
# r.save()
|
|
||||||
|
|
||||||
#def setrowerplans():
|
|
||||||
# rowers = Rower.objects.all()
|
|
||||||
|
|
||||||
# for r in rowers:
|
def is_existing_customer(rower): # pragma: no cover
|
||||||
# paidplans = PaidPlan.objects.filter(
|
|
||||||
# shortname = r.rowerplan,
|
|
||||||
# paymenttype = r.paymenttype,
|
|
||||||
# clubsize = r.clubsize,
|
|
||||||
# paymentprocessor=r.paymentprocessor)
|
|
||||||
|
|
||||||
# if paidplans:
|
|
||||||
# r.paidplan = paidplans[0]
|
|
||||||
# r.save()
|
|
||||||
# else:
|
|
||||||
# try:
|
|
||||||
# print 'Could not set plan for ',r.user.username
|
|
||||||
# except:
|
|
||||||
# pass
|
|
||||||
|
|
||||||
def is_existing_customer(rower):
|
|
||||||
if rower.country is not None and rower.customer_id is not None and rower.country != '':
|
if rower.country is not None and rower.customer_id is not None and rower.country != '':
|
||||||
if rower.subscription_id is None or rower.subscription_id == '':
|
if rower.subscription_id is None or rower.subscription_id == '':
|
||||||
return False
|
return False
|
||||||
@@ -47,4 +23,3 @@ def is_existing_customer(rower):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|||||||
@@ -392,7 +392,7 @@ def can_view_workout(user,workout):
|
|||||||
return True
|
return True
|
||||||
if user.is_anonymous: # pragma: no cover
|
if user.is_anonymous: # pragma: no cover
|
||||||
return False
|
return False
|
||||||
return user == workout.user.user
|
return user == workout.user.user # pragma: no cover
|
||||||
|
|
||||||
can_change_workout = is_workout_user
|
can_change_workout = is_workout_user
|
||||||
|
|
||||||
@@ -493,12 +493,12 @@ def can_view_plan(user,plan):
|
|||||||
def can_change_plan(user,plan):
|
def can_change_plan(user,plan):
|
||||||
if user.is_anonymous: # pragma: no cover
|
if user.is_anonymous: # pragma: no cover
|
||||||
return False
|
return False
|
||||||
return user == plan.manager.user
|
return user == plan.manager.user # pragma: no cover
|
||||||
|
|
||||||
# below untested
|
# below untested
|
||||||
@rules.predicate
|
@rules.predicate
|
||||||
def can_delete_plan(user,plan):
|
def can_delete_plan(user,plan):
|
||||||
if user.is_anonymous:
|
if user.is_anonymous: # pragma: no cover
|
||||||
return False
|
return False
|
||||||
return user == plan.manager.user
|
return user == plan.manager.user
|
||||||
|
|
||||||
@@ -699,7 +699,7 @@ def can_delete_logo(user,logo):
|
|||||||
if user.is_anonymous: # pragma: no cover
|
if user.is_anonymous: # pragma: no cover
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return logo.user == user
|
return logo.user == user # pragma: no cover
|
||||||
|
|
||||||
@rules.predicate
|
@rules.predicate
|
||||||
def can_change_race(user,race):
|
def can_change_race(user,race):
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ def get_token(code):
|
|||||||
return imports_get_token(code,oauth_data)
|
return imports_get_token(code,oauth_data)
|
||||||
|
|
||||||
# Make authorization URL including random string
|
# Make authorization URL including random string
|
||||||
def make_authorization_url(request):
|
def make_authorization_url(request): # pragma: no cover
|
||||||
return imports_make_authorization_url(oauth_data)
|
return imports_make_authorization_url(oauth_data)
|
||||||
|
|
||||||
# Get list of workouts available on Runkeeper
|
# Get list of workouts available on Runkeeper
|
||||||
@@ -94,7 +94,7 @@ def get_runkeeper_workout_list(user):
|
|||||||
# Get workout summary data by Runkeeper ID
|
# Get workout summary data by Runkeeper ID
|
||||||
def get_workout(user,runkeeperid,do_async=False):
|
def get_workout(user,runkeeperid,do_async=False):
|
||||||
r = Rower.objects.get(user=user)
|
r = Rower.objects.get(user=user)
|
||||||
if (r.runkeepertoken == '') or (r.runkeepertoken is None):
|
if (r.runkeepertoken == '') or (r.runkeepertoken is None): # pragma: no cover
|
||||||
return custom_exception_handler(401,s)
|
return custom_exception_handler(401,s)
|
||||||
s = "Token doesn't exist. Need to authorize"
|
s = "Token doesn't exist. Need to authorize"
|
||||||
else:
|
else:
|
||||||
@@ -123,7 +123,7 @@ def createrunkeeperworkoutdata(w):
|
|||||||
filename = w.csvfilename
|
filename = w.csvfilename
|
||||||
try:
|
try:
|
||||||
row = rowingdata(csvfile=filename)
|
row = rowingdata(csvfile=filename)
|
||||||
except:
|
except: # pragma: no cover
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
averagehr = int(row.df[' HRCur (bpm)'].mean())
|
averagehr = int(row.df[' HRCur (bpm)'].mean())
|
||||||
@@ -151,9 +151,9 @@ def createrunkeeperworkoutdata(w):
|
|||||||
try:
|
try:
|
||||||
lat = row.df[' latitude'].values
|
lat = row.df[' latitude'].values
|
||||||
lon = row.df[' longitude'].values
|
lon = row.df[' longitude'].values
|
||||||
if not lat.std() and not lon.std():
|
if not lat.std() and not lon.std(): # pragma: no cover
|
||||||
haslatlon = 0
|
haslatlon = 0
|
||||||
except KeyError:
|
except KeyError: # pragma: no cover
|
||||||
haslatlon = 0
|
haslatlon = 0
|
||||||
|
|
||||||
t = t.tolist()
|
t = t.tolist()
|
||||||
@@ -236,7 +236,7 @@ def getidfromresponse(response):
|
|||||||
|
|
||||||
return int(id)
|
return int(id)
|
||||||
|
|
||||||
def geturifromid(access_token,id):
|
def geturifromid(access_token,id): # pragma: no cover
|
||||||
authorizationstring = str('Bearer ' + access_token)
|
authorizationstring = str('Bearer ' + access_token)
|
||||||
headers = {'Authorization': authorizationstring,
|
headers = {'Authorization': authorizationstring,
|
||||||
'user-agent': 'sanderroosendaal',
|
'user-agent': 'sanderroosendaal',
|
||||||
@@ -271,21 +271,21 @@ def get_userid(access_token):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
me_json = response.json()
|
me_json = response.json()
|
||||||
except:
|
except: # pragma: no cover
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
try:
|
try:
|
||||||
res = me_json['userID']
|
res = me_json['userID']
|
||||||
except KeyError:
|
except KeyError: # pragma: no cover
|
||||||
res = ''
|
res = ''
|
||||||
|
|
||||||
return str(res)
|
return str(res)
|
||||||
|
|
||||||
def default(o):
|
def default(o): # pragma: no cover
|
||||||
if isinstance(o, numpy.int64): return int(o)
|
if isinstance(o, numpy.int64): return int(o)
|
||||||
raise TypeError
|
raise TypeError
|
||||||
|
|
||||||
def workout_runkeeper_upload(user,w,asynchron=False):
|
def workout_runkeeper_upload(user,w,asynchron=False): # pragma: no cover
|
||||||
message = "Uploading to Runkeeper"
|
message = "Uploading to Runkeeper"
|
||||||
rkid = 0
|
rkid = 0
|
||||||
|
|
||||||
@@ -351,7 +351,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
|||||||
workouttype = 'other'
|
workouttype = 'other'
|
||||||
try:
|
try:
|
||||||
comments = data['notes']
|
comments = data['notes']
|
||||||
except:
|
except: # pragma: no cover
|
||||||
comments = ''
|
comments = ''
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -364,14 +364,14 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
|||||||
try:
|
try:
|
||||||
rowdatetime = iso8601.parse_date(data['start_time'])
|
rowdatetime = iso8601.parse_date(data['start_time'])
|
||||||
except iso8601.ParseError:
|
except iso8601.ParseError:
|
||||||
try:
|
try: # pragma: no cover
|
||||||
rowdatetime = datetime.strptime(data['start_time'],"%Y-%m-%d %H:%M:%S")
|
rowdatetime = datetime.strptime(data['start_time'],"%Y-%m-%d %H:%M:%S")
|
||||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
try:
|
try:
|
||||||
rowdatetime = parser.parse(data['start_time'])
|
rowdatetime = parser.parse(data['start_time'])
|
||||||
#rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
#rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||||
except:
|
except: # pragma: no cover
|
||||||
rowdatetime = datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
|
rowdatetime = datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
|
||||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||||
starttimeunix = arrow.get(rowdatetime).timestamp()
|
starttimeunix = arrow.get(rowdatetime).timestamp()
|
||||||
@@ -399,14 +399,14 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
|||||||
latcoord = res[1]
|
latcoord = res[1]
|
||||||
loncoord = res[2]
|
loncoord = res[2]
|
||||||
|
|
||||||
except:
|
except: # pragma: no cover
|
||||||
times_location = times_distance
|
times_location = times_distance
|
||||||
latcoord = np.zeros(len(times_distance))
|
latcoord = np.zeros(len(times_distance))
|
||||||
loncoord = np.zeros(len(times_distance))
|
loncoord = np.zeros(len(times_distance))
|
||||||
if workouttype in types.otwtypes:
|
if workouttype in types.otwtypes:
|
||||||
workouttype = 'rower'
|
workouttype = 'rower'
|
||||||
|
|
||||||
try:
|
try: # pragma: no cover
|
||||||
res = splitrunkeeperdata(data['cadence'],'timestamp','cadence')
|
res = splitrunkeeperdata(data['cadence'],'timestamp','cadence')
|
||||||
times_spm = res[0]
|
times_spm = res[0]
|
||||||
spm = res[1]
|
spm = res[1]
|
||||||
@@ -418,7 +418,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
|||||||
res = splitrunkeeperdata(data['heart_rate'],'timestamp','heart_rate')
|
res = splitrunkeeperdata(data['heart_rate'],'timestamp','heart_rate')
|
||||||
hr = res[1]
|
hr = res[1]
|
||||||
times_hr = res[0]
|
times_hr = res[0]
|
||||||
except KeyError:
|
except KeyError: # pragma: no cover
|
||||||
times_hr = times_distance
|
times_hr = times_distance
|
||||||
hr = 0*times_distance
|
hr = 0*times_distance
|
||||||
|
|
||||||
@@ -435,7 +435,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
|||||||
lonseries = pd.Series(loncoord,index=times_location)
|
lonseries = pd.Series(loncoord,index=times_location)
|
||||||
try:
|
try:
|
||||||
lonseries = lonseries.groupby(lonseries.index).first()
|
lonseries = lonseries.groupby(lonseries.index).first()
|
||||||
except TypeError:
|
except TypeError: # pragma: no cover
|
||||||
lonseries = 0.0*distseries
|
lonseries = 0.0*distseries
|
||||||
|
|
||||||
spmseries = pd.Series(spm,index=times_spm)
|
spmseries = pd.Series(spm,index=times_spm)
|
||||||
@@ -443,7 +443,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
|||||||
hrseries = pd.Series(hr,index=times_hr)
|
hrseries = pd.Series(hr,index=times_hr)
|
||||||
try:
|
try:
|
||||||
hrseries = hrseries.groupby(hrseries.index).first()
|
hrseries = hrseries.groupby(hrseries.index).first()
|
||||||
except TypeError:
|
except TypeError: # pragma: no cover
|
||||||
hrseries = 0*distseries
|
hrseries = 0*distseries
|
||||||
|
|
||||||
|
|
||||||
@@ -484,7 +484,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
|||||||
unixtime = cum_time+starttimeunix
|
unixtime = cum_time+starttimeunix
|
||||||
try:
|
try:
|
||||||
unixtime[0] = starttimeunix
|
unixtime[0] = starttimeunix
|
||||||
except IndexError:
|
except IndexError: # pragma: no cover
|
||||||
return (0,'No data to import')
|
return (0,'No data to import')
|
||||||
|
|
||||||
df['TimeStamp (sec)'] = unixtime
|
df['TimeStamp (sec)'] = unixtime
|
||||||
|
|||||||
@@ -99,7 +99,8 @@ class BraintreeUnits(TestCase):
|
|||||||
res = create_customer(self.r)
|
res = create_customer(self.r)
|
||||||
self.assertEqual(res,1)
|
self.assertEqual(res,1)
|
||||||
|
|
||||||
def test_update_subscription(self):
|
@patch('rowers.views.racesviews.myqueue')
|
||||||
|
def test_update_subscription(self, mocked_myqueue):
|
||||||
data = {
|
data = {
|
||||||
'plan':self.pp.id,
|
'plan':self.pp.id,
|
||||||
'payment_method_nonce':'aap',
|
'payment_method_nonce':'aap',
|
||||||
@@ -112,7 +113,8 @@ class BraintreeUnits(TestCase):
|
|||||||
self.assertTrue(success)
|
self.assertTrue(success)
|
||||||
self.assertEqual(amount,25)
|
self.assertEqual(amount,25)
|
||||||
|
|
||||||
def test_create_subscription(self):
|
@patch('rowers.views.racesviews.myqueue')
|
||||||
|
def test_create_subscription(self, mocked_myqueue):
|
||||||
data = {
|
data = {
|
||||||
'plan':self.p2.id,
|
'plan':self.p2.id,
|
||||||
'payment_method_nonce':'aap',
|
'payment_method_nonce':'aap',
|
||||||
|
|||||||
@@ -559,7 +559,7 @@ def rower_prefs_view(request,userid=0,message=""):
|
|||||||
if powerform.is_valid():
|
if powerform.is_valid():
|
||||||
cd = powerform.cleaned_data
|
cd = powerform.cleaned_data
|
||||||
hrftp = cd['hrftp']
|
hrftp = cd['hrftp']
|
||||||
if hrftp == 0:
|
if hrftp == 0: # pragma: no cover
|
||||||
hrftp = int((r.an+r.tr)/2.)
|
hrftp = int((r.an+r.tr)/2.)
|
||||||
ftp = cd['ftp']
|
ftp = cd['ftp']
|
||||||
otwslack = cd['otwslack']
|
otwslack = cd['otwslack']
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import sys
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
use_sqlite = CFG['use_sqlite']
|
use_sqlite = CFG['use_sqlite']
|
||||||
except KeyError:
|
except KeyError: # pragma: no cover
|
||||||
use_sqlite = False
|
use_sqlite = False
|
||||||
|
|
||||||
if 'test' in sys.argv:
|
if 'test' in sys.argv:
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ from django.utils import timezone
|
|||||||
from rowers.database import *
|
from rowers.database import *
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
def current_day():
|
def current_day(): # pragma: no cover
|
||||||
return (datetime.datetime.now(tz=timezone.utc)).date()
|
return (datetime.datetime.now(tz=timezone.utc)).date()
|
||||||
|
|
||||||
class Response(models.Model):
|
class Response(models.Model):
|
||||||
|
|||||||
Reference in New Issue
Block a user