Private
Public Access
1
0

more payment view coverage tests

This commit is contained in:
Sander Roosendaal
2021-04-25 17:41:04 +02:00
parent e19158926d
commit df86eaac0c
11 changed files with 448 additions and 169 deletions

View File

@@ -58,10 +58,11 @@ from rowers.models import Rower,PaidPlan, CoachingGroup
from rowers.utils import ProcessorCustomerError from rowers.utils import ProcessorCustomerError
def process_webhook(notification): def process_webhook(notification):
with open('braintreewebhooks.log','a') as f: if not settings.TESTING: # pragma: no cover
t = time.localtime() with open('braintreewebhooks.log','a') as f:
timestamp = time.strftime('%b-%d-%Y_%H%M', t) t = time.localtime()
f.write(timestamp+' '+notification.kind+'\n') timestamp = time.strftime('%b-%d-%Y_%H%M', t)
f.write(timestamp+' '+notification.kind+'\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':

View File

@@ -79,11 +79,11 @@ def update_team(t,name,manager,private,notes,viewing):
def create_team(name,manager,private='open',notes='',viewing='allmembers'): def create_team(name,manager,private='open',notes='',viewing='allmembers'):
# needs some error testing # needs some error testing
if user_is_basic(manager.rower.user): if user_is_basic(manager.rower.user): # pragma: no cover
return (0,'You need to upgrade to a paid plan to establish a team') return (0,'You need to upgrade to a paid plan to establish a team')
if not is_coach(manager): if not is_coach(manager):
ts = Team.objects.filter(manager=manager) ts = Team.objects.filter(manager=manager)
if len(ts)>=1: if len(ts)>=1: # pragma: no cover
return (0,'You need to upgrade to the Coach plan to have more than one team') return (0,'You need to upgrade to the Coach plan to have more than one team')
try: try:
@@ -102,13 +102,13 @@ def remove_team(id):
send_team_delete_mail(t,r) send_team_delete_mail(t,r)
return t.delete() return t.delete()
return (1,'Updated rower team expiry') return (1,'Updated rower team expiry') # pragma: no cover
def add_coach(coach,rower): def add_coach(coach,rower):
# get coaching group # get coaching group
coachgroup = coach.mycoachgroup coachgroup = coach.mycoachgroup
if coachgroup is None: if coachgroup is None: # pragma: no cover
coachgroup = CoachingGroup(name=coach.user.first_name) coachgroup = CoachingGroup(name=coach.user.first_name)
coachgroup.save() coachgroup.save()
coach.mycoachgroup = coachgroup coach.mycoachgroup = coachgroup
@@ -118,14 +118,14 @@ def add_coach(coach,rower):
rower.coachinggroups.add(coach.mycoachgroup) rower.coachinggroups.add(coach.mycoachgroup)
return (1,"Added Coach") return (1,"Added Coach")
else: else: # pragma: no cover
return (0,"Maximum number of athletes reached") return (0,"Maximum number of athletes reached")
def add_member(id,rower): def add_member(id,rower):
t= Team.objects.get(id=id) t= Team.objects.get(id=id)
try: try:
rower.team.add(t) rower.team.add(t)
except ValidationError as e: except ValidationError as e: # pragma: no cover
return(0,"Couldn't add member: "+str(e.message)) return(0,"Couldn't add member: "+str(e.message))
# code to add all workouts # code to add all workouts
@@ -135,12 +135,12 @@ def add_member(id,rower):
# code to add plannedsessions # code to add plannedsessions
plannedsessions = PlannedSession.objects.filter(team=t,enddate__gte=timezone.now().date()) plannedsessions = PlannedSession.objects.filter(team=t,enddate__gte=timezone.now().date())
for ps in plannedsessions: for ps in plannedsessions: # pragma: no cover
res = ps.rower.add(rower) res = ps.rower.add(rower)
# set_teamplanexpires(rower) # set_teamplanexpires(rower)
# code for Stuck At Home Team (temporary) # code for Stuck At Home Team (temporary)
if id == 52 and rower.rowerplan == 'basic': if id == 52 and rower.rowerplan == 'basic': # pragma: no cover
rower.protrialexpires = ddate(2020,9,1) rower.protrialexpires = ddate(2020,9,1)
rower.save() rower.save()
@@ -157,10 +157,10 @@ def remove_member(id,rower):
# set_teamplanexpires(rower) # set_teamplanexpires(rower)
return (id,'Member removed') return (id,'Member removed')
def remove_coach(coach,rower): def remove_coach(coach,rower): # pragma: no cover
try: try:
coachgroup = coach.mycoachgroup coachgroup = coach.mycoachgroup
except CoachingGroup.DoesNotExist: except CoachingGroup.DoesNotExist: # pragma: no cover
coachgroup = CoachingGroup() coachgroup = CoachingGroup()
coachgroup.save() coachgroup.save()
coach.mycoachgroup = coachgroup coach.mycoachgroup = coachgroup
@@ -195,7 +195,7 @@ def coach_getcoachees(coach):
def coach_remove_athlete(coach,rower): def coach_remove_athlete(coach,rower):
try: try:
coachgroup = coach.mycoachgroup coachgroup = coach.mycoachgroup
except CoachingGroup.DoesNotExist: except CoachingGroup.DoesNotExist: # pragma: no cover
coachgroup = CoachingGroup() coachgroup = CoachingGroup()
coachgroup.save() coachgroup.save()
coach.mycoachgroup = coachgroup coach.mycoachgroup = coachgroup
@@ -211,12 +211,12 @@ def mgr_remove_member(id,manager,rower):
remove_member(id,rower) remove_member(id,rower)
send_email_member_dropped(id,rower) send_email_member_dropped(id,rower)
return (id,'Member removed') return (id,'Member removed')
else: else: # pragma: no cover
return (0,'You are not the team manager') return (0,'You are not the team manager')
return (0,'') return (0,'') # pragma: no cover
def count_invites(manager): def count_invites(manager): # pragma: no cover
ts = Team.objects.filter(manager=manager) ts = Team.objects.filter(manager=manager)
count = 0 count = 0
for t in ts: for t in ts:
@@ -225,7 +225,7 @@ def count_invites(manager):
return count return count
def count_club_members(manager): def count_club_members(manager): # pragma: no cover
ts = Team.objects.filter(manager=manager) ts = Team.objects.filter(manager=manager)
return Rower.objects.filter(team__in=ts).distinct().count() return Rower.objects.filter(team__in=ts).distinct().count()
@@ -233,13 +233,13 @@ def count_club_members(manager):
# Medium level functionality # Medium level functionality
# request by user to be coached by coach # request by user to be coached by coach
def create_coaching_request(coach,user): def create_coaching_request(coach,user): # pragma: no cover
if coach in rower_get_coaches(user.rower): if coach in rower_get_coaches(user.rower):
return (0,'Already coached by that coach') return (0,'Already coached by that coach')
codes = [i.code for i in CoachRequest.objects.all()] codes = [i.code for i in CoachRequest.objects.all()]
code = uuid.uuid4().hex[:10].upper() code = uuid.uuid4().hex[:10].upper()
while code in codes: while code in codes: # pragma: no cover
code = uuid.uuid4().hex[:10].upper() code = uuid.uuid4().hex[:10].upper()
if 'coach' in coach.rowerplan: if 'coach' in coach.rowerplan:
@@ -250,7 +250,7 @@ def create_coaching_request(coach,user):
return (rekwest.id,'The request was created') return (rekwest.id,'The request was created')
else: else: # pragma: no cover
return (0,'That person is not a coach') return (0,'That person is not a coach')
def send_coachrequest_email(rekwest): def send_coachrequest_email(rekwest):
@@ -280,14 +280,14 @@ def send_coacheerequest_email(rekwest):
def create_request(team,user): def create_request(team,user):
r2 = Rower.objects.get(user=user) r2 = Rower.objects.get(user=user)
r = Rower.objects.get(user=team.manager) r = Rower.objects.get(user=team.manager)
if r2 in Rower.objects.filter(team=team): if r2 in Rower.objects.filter(team=team): # pragma: no cover
return (0,'Already a member of that team') return (0,'Already a member of that team')
# if count_club_members(team.manager)+count_invites(team.manager) <= r.clubsize: # if count_club_members(team.manager)+count_invites(team.manager) <= r.clubsize:
codes = [i.code for i in TeamRequest.objects.all()] codes = [i.code for i in TeamRequest.objects.all()]
code = uuid.uuid4().hex[:10].upper() code = uuid.uuid4().hex[:10].upper()
# prevent duplicates # prevent duplicates
while code in codes: while code in codes: # pragma: no cover
code = uuid.uuid4().hex[:10].upper() code = uuid.uuid4().hex[:10].upper()
u = User.objects.get(id=user) u = User.objects.get(id=user)
@@ -298,7 +298,7 @@ def create_request(team,user):
return (rekwest.id,'The request was created') return (rekwest.id,'The request was created')
return (0,'Something went wrong in create_request') return (0,'Something went wrong in create_request') # pragma: no cover
def get_coach_club_size(coach): def get_coach_club_size(coach):
rs = Rower.objects.filter(coachinggroups__in=[coach.mycoachgroup]) rs = Rower.objects.filter(coachinggroups__in=[coach.mycoachgroup])
@@ -313,12 +313,12 @@ def get_coach_club_size(coach):
def create_coaching_offer(coach,user): def create_coaching_offer(coach,user):
r = user.rower r = user.rower
if coach in rower_get_coaches(user.rower): if coach in rower_get_coaches(user.rower): # pragma: no cover
return (0,'You are already coaching this person.') return (0,'You are already coaching this person.')
codes = [i.code for i in CoachOffer.objects.all()] codes = [i.code for i in CoachOffer.objects.all()]
code = uuid.uuid4().hex[:10].upper() code = uuid.uuid4().hex[:10].upper()
while code in codes: while code in codes: # pragma: no cover
code = uuid.uuid4().hex[:10].upper() code = uuid.uuid4().hex[:10].upper()
if 'coach' in coach.rowerplan and get_coach_club_size(coach)<coach.clubsize: if 'coach' in coach.rowerplan and get_coach_club_size(coach)<coach.clubsize:
@@ -328,10 +328,10 @@ def create_coaching_offer(coach,user):
send_coacheerequest_email(rekwest) send_coacheerequest_email(rekwest)
return (rekwest.id,'The request was created') return (rekwest.id,'The request was created')
elif get_coach_club_size(coach)>=coach.clubsize: elif get_coach_club_size(coach)>=coach.clubsize: # pragma: no cover
return(0,'You have reached the maximum number of athletes') return(0,'You have reached the maximum number of athletes')
else: else: # pragma: no cover
return (0,'You are not a coach') return (0,'You are not a coach')
@@ -345,26 +345,26 @@ def create_invite(team,manager,user=None,email=''):
try: try:
r2 = Rower.objects.get(user=user) r2 = Rower.objects.get(user=user)
email = r2.user.email email = r2.user.email
except Rower.DoesNotExist: except Rower.DoesNotExist: # pragma: no cover
return (0,'Rower does not exist') return (0,'Rower does not exist')
if r2 in Rower.objects.filter(team=team): if r2 in Rower.objects.filter(team=team):
return (0,'Already member of that team') return (0,'Already member of that team')
elif email==None or email=='': elif email==None or email=='': # pragma: no cover
return (0,'Invalid request - missing email or user') return (0,'Invalid request - missing email or user')
else: else:
try: try:
r2 = Rower.objects.get(user__email=email) r2 = Rower.objects.get(user__email=email)
user = User.objects.get(rower=r2) user = User.objects.get(rower=r2)
except Rower.DoesNotExist: except Rower.DoesNotExist: # pragma: no cover
user=None user=None
except Rower.MultipleObjectsReturned: except Rower.MultipleObjectsReturned: # pragma: no cover
return (0,'There is more than one user with that email address') return (0,'There is more than one user with that email address')
# if count_club_members(team.manager)+count_invites(team.manager) <= r.clubsize: # if count_club_members(team.manager)+count_invites(team.manager) <= r.clubsize:
codes = [i.code for i in TeamInvite.objects.all()] codes = [i.code for i in TeamInvite.objects.all()]
code = uuid.uuid4().hex[:10].upper() code = uuid.uuid4().hex[:10].upper()
# prevent duplicates # prevent duplicates
while code in codes: while code in codes: # pragma: no cover
code = uuid.uuid4().hex[:10].upper() code = uuid.uuid4().hex[:10].upper()
invite = TeamInvite(team=team,code=code,user=user,email=email) invite = TeamInvite(team=team,code=code,user=user,email=email)
@@ -372,12 +372,12 @@ def create_invite(team,manager,user=None,email=''):
return (invite.id,'Invitation created') return (invite.id,'Invitation created')
return (0,'Nothing done') return (0,'Nothing done') # pragma: no cover
def revoke_request(user,id): def revoke_request(user,id):
try: try:
rekwest = TeamRequest.objects.get(id=id) rekwest = TeamRequest.objects.get(id=id)
except TeamRequest.DoesNotExist: except TeamRequest.DoesNotExist: # pragma: no cover
return (0,'The request is invalid') return (0,'The request is invalid')
t = rekwest.team t = rekwest.team
@@ -385,13 +385,13 @@ def revoke_request(user,id):
if rekwest.user==user: if rekwest.user==user:
rekwest.delete() rekwest.delete()
return (1,'Request revoked') return (1,'Request revoked')
else: else: # pragma: no cover
return (0,'You are not the requestor') return (0,'You are not the requestor')
def reject_revoke_coach_offer(user,id): def reject_revoke_coach_offer(user,id):
try: try:
rekwest = CoachOffer.objects.get(id=id) rekwest = CoachOffer.objects.get(id=id)
except CoachOffer.DoesNotExist: except CoachOffer.DoesNotExist: # pragma: no cover
return (0,'The request is invalid') return (0,'The request is invalid')
if rekwest.coach.user == user: if rekwest.coach.user == user:
@@ -402,13 +402,13 @@ def reject_revoke_coach_offer(user,id):
send_coachoffer_rejected_email(rekwest) send_coachoffer_rejected_email(rekwest)
rekwest.delete() rekwest.delete()
return (1,'Request removed') return (1,'Request removed')
else: else: # pragma: no cover
return (0,'Not permitted') return (0,'Not permitted')
def reject_revoke_coach_request(user,id): def reject_revoke_coach_request(user,id):
try: try:
rekwest = CoachRequest.objects.get(id=id) rekwest = CoachRequest.objects.get(id=id)
except CoachRequest.DoesNotExist: except CoachRequest.DoesNotExist: # pragma: no cover
return (0,'The request is invalid') return (0,'The request is invalid')
if rekwest.coach.user == user: if rekwest.coach.user == user:
@@ -418,59 +418,59 @@ def reject_revoke_coach_request(user,id):
elif rekwest.user == user: elif rekwest.user == user:
rekwest.delete() rekwest.delete()
return (1,'Request rejected') return (1,'Request rejected')
else: else: # pragma: no cover
return (0,'Not permitted') return (0,'Not permitted')
def revoke_invite(manager,id): def revoke_invite(manager,id):
try: try:
invite = TeamInvite.objects.get(id=id) invite = TeamInvite.objects.get(id=id)
except TeamInvite.DoesNotExist: except TeamInvite.DoesNotExist: # pragma: no cover
return (0,'The invitation is invalid') return (0,'The invitation is invalid')
if is_team_manager(manager,invite.team): if is_team_manager(manager,invite.team):
invite.delete() invite.delete()
return (1,'Invitation revoked') return (1,'Invitation revoked')
else: else: # pragma: no cover
return (0,'You are not the team manager') return (0,'You are not the team manager')
def reject_request(manager,id): def reject_request(manager,id):
try: try:
rekwest = TeamRequest.objects.get(id=id) rekwest = TeamRequest.objects.get(id=id)
except TeamRequest.DoesNotExist: except TeamRequest.DoesNotExist: # pragma: no cover
return (0,'The request is invalid') return (0,'The request is invalid')
if is_team_manager(manager,rekwest.team): if is_team_manager(manager,rekwest.team):
send_request_reject_email(rekwest) send_request_reject_email(rekwest)
rekwest.delete() rekwest.delete()
return (1,'Request rejected') return (1,'Request rejected')
else: else: # pragma: no cover
return (0,'You are not the manager for this request') return (0,'You are not the manager for this request')
def reject_invitation(user,id): def reject_invitation(user,id):
try: try:
invite = TeamInvite.objects.get(id=id) invite = TeamInvite.objects.get(id=id)
except TeamInvite.DoesNotExist: except TeamInvite.DoesNotExist: # pragma: no cover
return (0,'The invitation is invalid') return (0,'The invitation is invalid')
if invite.user==user: if invite.user==user:
send_invite_reject_email(invite) send_invite_reject_email(invite)
invite.delete() invite.delete()
return (1,'Invitation rejected') return (1,'Invitation rejected')
else: else: # pragma: no cover
return (0,'This request was not for you') return (0,'This request was not for you')
def send_invite_email(id): def send_invite_email(id):
try: try:
invitation = TeamInvite.objects.get(id=id) invitation = TeamInvite.objects.get(id=id)
except TeamInvite.DoesNotExist: except TeamInvite.DoesNotExist: # pragma: no cover
return (0,'Invitation doesn not exist') return (0,'Invitation doesn not exist')
if invitation.user: if invitation.user:
email = invitation.user.email email = invitation.user.email
name = invitation.user.first_name + " " + invitation.user.last_name name = invitation.user.first_name + " " + invitation.user.last_name
else: else: # pragma: no cover
email = invitation.email email = invitation.email
name = '' name = ''
@@ -510,7 +510,7 @@ def send_email_member_dropped(teamid,rower):
return (1,'Member dropped email sent') return (1,'Member dropped email sent')
def send_request_accept_email(rekwest): def send_request_accept_email(rekwest): # pragma: no cover
id = rekwest.id id = rekwest.id
email = rekwest.user.email email = rekwest.user.email
teamname = rekwest.team.name teamname = rekwest.team.name
@@ -542,7 +542,7 @@ def send_invite_reject_email(invitation):
email = invitation.team.manager.email email = invitation.team.manager.email
if invitation.user: if invitation.user:
name = invitation.user.first_name+' '+invitation.user.last_name name = invitation.user.first_name+' '+invitation.user.last_name
else: else: # pragma: no cover
name = invitation.email name = invitation.email
teamname = invitation.team.name teamname = invitation.team.name
@@ -555,7 +555,7 @@ def send_invite_reject_email(invitation):
return (1,'Invitation email sent') return (1,'Invitation email sent')
def send_invite_accept_email(invitation): def send_invite_accept_email(invitation): # pragma: no cover
id = invitation.id id = invitation.id
email = invitation.team.manager.email email = invitation.team.manager.email
if invitation.user: if invitation.user:
@@ -572,7 +572,7 @@ def send_invite_accept_email(invitation):
return (1,'Invitation email sent') return (1,'Invitation email sent')
def send_team_message(team,message): def send_team_message(team,message): # pragma: no cover
rowers = team.rower.all() rowers = team.rower.all()
managername = team.manager.first_name + " " + team.manager.last_name managername = team.manager.first_name + " " + team.manager.last_name
@@ -598,7 +598,7 @@ def send_request_email(rekwest):
return (1,'Invitation email sent') return (1,'Invitation email sent')
def process_request_code(manager,code): def process_request_code(manager,code): # pragma: no cover
code = code.upper() code = code.upper()
try: try:
@@ -623,7 +623,7 @@ def process_request_code(manager,code):
rekwest.delete() rekwest.delete()
return (result,'The member was added') return (result,'The member was added')
def process_invite_code(user,code): def process_invite_code(user,code): # pragma: no cover
code = code.upper() code = code.upper()
try: try:
invitation = TeamInvite.objects.get(code=code) invitation = TeamInvite.objects.get(code=code)
@@ -646,7 +646,7 @@ def process_invite_code(user,code):
invitation.delete() invitation.delete()
return (result,'You were added to the team') return (result,'You were added to the team')
def remove_expired_invites(): def remove_expired_invites(): # pragma: no cover
issuedate = timezone.now()-timedelta(days=inviteduration) issuedate = timezone.now()-timedelta(days=inviteduration)
issuedate = datetime.date(issuedate) issuedate = datetime.date(issuedate)
invitations = TeamInvite.objects.filter(issuedate__lt=issuedate) invitations = TeamInvite.objects.filter(issuedate__lt=issuedate)
@@ -660,14 +660,14 @@ def process_coachrequest_code(coach,code):
try: try:
rekwest = CoachRequest.objects.get(code=code) rekwest = CoachRequest.objects.get(code=code)
except CoachRequest.DoesNotExist: except CoachRequest.DoesNotExist: # pragma: no cover
return (0,'The request has been revoked or is invalid') return (0,'The request has been revoked or is invalid')
if rekwest.coach != coach: if rekwest.coach != coach: # pragma: no cover
return (0,'The request is invalid') return (0,'The request is invalid')
result = add_coach(coach,rekwest.user.rower) result = add_coach(coach,rekwest.user.rower)
if not result: if not result: # pragma: no cover
return result return result
else: else:
send_coachrequest_accepted_email(rekwest) send_coachrequest_accepted_email(rekwest)
@@ -681,14 +681,14 @@ def process_coachoffer_code(user,code):
try: try:
rekwest = CoachOffer.objects.get(code=code) rekwest = CoachOffer.objects.get(code=code)
except CoachOffer.DoesNotExist: except CoachOffer.DoesNotExist: # pragma: no cover
return (0,'The request has been revoked or is invalid') return (0,'The request has been revoked or is invalid')
if rekwest.user != user: if rekwest.user != user: # pragma: no cover
return (0,'The request is invalid') return (0,'The request is invalid')
result = add_coach(rekwest.coach,rekwest.user.rower) result = add_coach(rekwest.coach,rekwest.user.rower)
if not result: if not result: # pragma: no cover
return result return result
else: else:
send_coachoffer_accepted_email(rekwest) send_coachoffer_accepted_email(rekwest)

View File

@@ -94,7 +94,7 @@ def icon(s):
return 'fa-chart-line' return 'fa-chart-line'
@register.filter @register.filter
def datarows(data): def datarows(data): # pragma: no cover
return range(len(data)) return range(len(data))
@register.filter @register.filter
@@ -457,7 +457,7 @@ def currency(word):
def rkuserid(user): def rkuserid(user):
try: try:
thetoken = runkeeper_open(user) thetoken = runkeeper_open(user)
except NoTokenError: except NoTokenError: # pragma: no cover
return 0 return 0
rkuserid = runkeeperstuff.get_userid(thetoken) rkuserid = runkeeperstuff.get_userid(thetoken)
@@ -547,12 +547,12 @@ def mayeditplan(obj,request):
if obj.manager is not None: if obj.manager is not None:
return request.user == obj.manager.user return request.user == obj.manager.user
rr = Rower.objects.get(user=request.user) rr = Rower.objects.get(user=request.user) # pragma: no cover
if is_coach_user(request.user,obj.rower) and rr.rowerplan not in ['basic','pro']: if is_coach_user(request.user,obj.rower) and rr.rowerplan not in ['basic','pro']: # pragma: no cover
mayedit = True mayedit = True
return mayedit return mayedit # pragma: no cover
@register.filter @register.filter
def iterrows(df): # pragma: no cover def iterrows(df): # pragma: no cover

View File

@@ -627,6 +627,16 @@ class payment_method():
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.token = 'liesjeleerdelotje' self.token = 'liesjeleerdelotje'
class notification():
def __init__(self, *args, **kwargs):
print('notifucation')
self.kind = 'subscription_canceled'
class webhook_notification():
def parse(*args, **kwargs):
print(args,kwargs,'parse')
return notification()
# mock braintree gateway # mock braintree gateway
class MockBraintreeGateway: class MockBraintreeGateway:
def __init__(self,*args, **kwargs): def __init__(self,*args, **kwargs):
@@ -636,6 +646,7 @@ class MockBraintreeGateway:
self.transaction = transaction() self.transaction = transaction()
self.subscription = subscription() self.subscription = subscription()
self.payment_method = payment_method() self.payment_method = payment_method()
self.webhook_notification = webhook_notification()
def mocked_gateway(*args, **kwargs): def mocked_gateway(*args, **kwargs):
@@ -1218,3 +1229,6 @@ class MockOAuth1Session:
def post(*args, **kwargs): def post(*args, **kwargs):
return MockResponse({},200) return MockResponse({},200)
def mocked_invoiceid(*args,**kwargs):
return 1

View File

@@ -11,6 +11,8 @@ from django_countries import countries
from rowers.braintreestuff import mocktest from rowers.braintreestuff import mocktest
import urllib
class PaymentTest(TestCase): class PaymentTest(TestCase):
def setUp(self): def setUp(self):
@@ -55,9 +57,122 @@ class PaymentTest(TestCase):
self.c = Client() self.c = Client()
self.password = faker.word() self.password = faker.word()
s = b"""filename: britishrowing.json
name: British Rowing Training Plan Beginner Week 1
trainingDays:
- order: 1
workouts:
- workoutName: Week 1 Session 1
steps:
- stepId: 0
wkt_step_name: Warmup
durationType: Time
durationValue: 300000
intensity: Warmup
description: ""
- stepId: 1
wkt_step_name: Intervals
durationType: Time
durationValue: 60000
intensity: Active
description: ""
- stepId: 2
wkt_step_name: Interval Rest
durationType: Time
durationValue: 60000
intensity: Rest
description: ""
- stepId: 3
wkt_step_name: Rep
durationType: RepeatUntilStepsCmplt
durationValue: 1
targetValue: 5
- stepId: 4
wkt_step_name: Cooldown
durationType: Time
durationValue: 300000
intensity: Cooldown
description: ""
sport: ""
description: ""
- order: 4
workouts:
- workoutName: Week 1 Session 2
steps:
- stepId: 0
wkt_step_name: Warmup
durationType: Time
durationValue: 300000
intensity: Warmup
description: ""
- stepId: 1
wkt_step_name: Interval
durationType: Time
durationValue: 300000
intensity: Active
description: ""
- stepId: 2
wkt_step_name: Interval Rest
durationType: Time
durationValue: 180000
intensity: Rest
description: ""
- stepId: 3
wkt_step_name: Rep
durationType: RepeatUntilStepsCmplt
durationValue: 1
targetValue: 5
- stepId: 4
wkt_step_name: Cooldown
durationType: Time
durationValue: 300000
intensity: Cooldown
description: ""
sport: ""
description: ""
duration: 7
description: ""
"""
self.file_data = {'yaml': SimpleUploadedFile('britishrowing.yml', s)}
with open('media/temp.yml','wb') as f:
f.write(s)
self.instantplan = InstantPlan(
uuid = "79b0dacf-9b49-4f33-9acf-e2e6734e22dc",
url = "https://thepeteplan.wordpress.com/beginner-training/",
name = faker.word(),
goal = faker.word(),
duration = 42,
description = faker.word(),
target = faker.word(),
hoursperweek = 3,
sessionsperweek = 3,
price = 0,
yaml = 'temp.yml',
)
self.instantplan.save()
# def tearDown(self): # def tearDown(self):
# settings.DEBUG = False # settings.DEBUG = False
@patch('rowers.braintreestuff.gateway',side_effect=MockBraintreeGateway)
def test_braintree_webhook(self,mocked_gateway):
url = reverse('braintree_webhook_view')
response = self.c.get(url)
self.assertEqual(response.status_code,200)
form_data = {
'bt_signature':'aap',
'bt_payload':'noot,'
}
response = self.c.post(url,form_data)
self.assertEqual(response.status_code,200)
@patch('rowers.views.braintreestuff.create_customer',side_effect=mock_create_customer) @patch('rowers.views.braintreestuff.create_customer',side_effect=mock_create_customer)
@patch('rowers.views.braintreestuff.gateway',side_effect=MockBraintreeGateway) @patch('rowers.views.braintreestuff.gateway',side_effect=MockBraintreeGateway)
def test_billing_view(self,mocked_create_customer,mocked_gateway): def test_billing_view(self,mocked_create_customer,mocked_gateway):
@@ -284,6 +399,100 @@ class PaymentTest(TestCase):
self.assertEqual(response.status_code,200) self.assertEqual(response.status_code,200)
@patch('rowers.views.braintreestuff.gateway', side_effect=MockBraintreeGateway)
@patch('rowers.fakturoid.create_invoice',side_effect=mocked_invoiceid)
def test_purchase_trainingplan_view(self, mocked_gateway,mocked_invoiceid):
u = UserFactory()
r = Rower.objects.create(user=u,
birthdate=faker.profile()['birthdate'],
gdproptin=True,surveydone=True,
gdproptindate=timezone.now(),
rowerplan='plan',
paymentprocessor='braintree',
street_address = faker.street_address(),
city = faker.city(),
postal_code = faker.postalcode(),
country = faker.country(),
)
r.save()
r.country = 'NL'
r.customer_id = 34
r.subscription_id = 34
r.save()
u.set_password(self.password)
u.save()
login = self.c.login(username=u.username, password=self.password)
self.assertTrue(login)
url = reverse('buy_trainingplan_view',kwargs={'id':self.instantplan.id})
response = self.c.get(url)
self.assertEqual(response.status_code,200)
enddate = datetime.datetime.now()+datetime.timedelta(days=30)
startdate = datetime.datetime.now()
form_data = {
'enddate':enddate.strftime('%Y-%m-%d'),
'startdate':startdate.strftime('%Y-%m-%d'),
'notes':'no notes',
'datechoice':'enddate',
'name':'no name',
}
response = self.c.post(url,form_data)
pars = {
'name':'no name',
'enddate':enddate.strftime('%Y-%m-%d'),
'notes':'no notes',
'status':True,
'rower':r.id,
}
params = urllib.parse.urlencode(pars)
expected_url = reverse('confirm_trainingplan_purchase_view',kwargs={'id':self.instantplan.id})
expected_url = expected_url + "?%s" % params
self.assertRedirects(response,expected_url=expected_url,status_code=302,target_status_code=200)
url = expected_url
response = self.c.get(url)
self.assertEqual(response.status_code,200)
url = reverse('purchase_checkouts_view')
form_data = {
'amount':'25.00',
'plan': self.instantplan.id,
'payment_method_nonce': 'aap',
'tac':'tac',
'paymenttype': 'CreditCard',
'notes':'no notes',
'enddate':enddate.strftime('%Y-%m-%d'),
'status':True,
}
form = TrainingPlanBillingForm(form_data)
if not form.is_valid():
print(form.errors)
self.assertTrue(form.is_valid())
response = self.c.post(url,form_data,follow=True)
self.assertEqual(response.status_code,200)
expected_url = reverse('plannedsessions_view')
startdate = enddate-datetime.timedelta(days=self.instantplan.duration)
timeperiod = startdate.strftime('%Y-%m-%d')+'/'+enddate.strftime('%Y-%m-%d')
expected_url = expected_url+'?when='+timeperiod
self.assertRedirects(response,
expected_url = expected_url,
status_code=302,target_status_code=200)
@patch('rowers.views.braintreestuff.gateway',side_effect=MockBraintreeGateway) @patch('rowers.views.braintreestuff.gateway',side_effect=MockBraintreeGateway)
def test_planstobasic_view(self,mocked_gateway): def test_planstobasic_view(self,mocked_gateway):
u = UserFactory() u = UserFactory()

View File

@@ -49,6 +49,12 @@ class DataTest(TestCase):
'tr':167, 'tr':167,
'an':180, 'an':180,
'weightcategory':'lwt', 'weightcategory':'lwt',
'hrrestname':'rest',
'hrut2name':'ut2',
'hrut1name':'ut1',
'hrtrname':'tr',
'hranname':'an',
'hrmaxname':'max',
} }
form = RowerForm(data=form_data) form = RowerForm(data=form_data)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
@@ -64,6 +70,12 @@ class DataTest(TestCase):
'an':180, 'an':180,
'tr':167, 'tr':167,
'weightcategory':'lwt', 'weightcategory':'lwt',
'hrrestname':'rest',
'hrut2name':'ut2',
'hrut1name':'ut1',
'hrtrname':'tr',
'hranname':'an',
'hrmaxname':'max',
} }
form = RowerForm(data=form_data) form = RowerForm(data=form_data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
@@ -78,6 +90,12 @@ class DataTest(TestCase):
'an':180, 'an':180,
'tr':167, 'tr':167,
'weightcategory':'lwt', 'weightcategory':'lwt',
'hrrestname':'rest',
'hrut2name':'ut2',
'hrut1name':'ut1',
'hrtrname':'tr',
'hranname':'an',
'hrmaxname':'max',
} }
form = RowerForm(data=form_data) form = RowerForm(data=form_data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
@@ -92,6 +110,12 @@ class DataTest(TestCase):
'an':180, 'an':180,
'tr':167, 'tr':167,
'weightcategory':'lwt', 'weightcategory':'lwt',
'hrrestname':'rest',
'hrut2name':'ut2',
'hrut1name':'ut1',
'hrtrname':'tr',
'hranname':'an',
'hrmaxname':'max',
} }
form = RowerForm(data=form_data) form = RowerForm(data=form_data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
@@ -106,6 +130,12 @@ class DataTest(TestCase):
'an':180, 'an':180,
'tr':167, 'tr':167,
'weightcategory':'lwt', 'weightcategory':'lwt',
'hrrestname':'rest',
'hrut2name':'ut2',
'hrut1name':'ut1',
'hrtrname':'tr',
'hranname':'an',
'hrmaxname':'max',
} }
form = RowerForm(data=form_data) form = RowerForm(data=form_data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
@@ -120,6 +150,12 @@ class DataTest(TestCase):
'an':180, 'an':180,
'tr':167, 'tr':167,
'weightcategory':'lwt', 'weightcategory':'lwt',
'hrrestname':'rest',
'hrut2name':'ut2',
'hrut1name':'ut1',
'hrtrname':'tr',
'hranname':'an',
'hrmaxname':'max',
} }
form = RowerForm(data=form_data) form = RowerForm(data=form_data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())

View File

@@ -114,6 +114,25 @@ class TeamTest(TestCase):
except (IOError, FileNotFoundError,OSError): except (IOError, FileNotFoundError,OSError):
pass pass
def test_team_leave_view(self):
res = add_member(self.t.id,self.users[1].rower)
login = self.c.login(username=self.u.username, password = self.password)
self.assertTrue(login)
url = reverse('team_leave_view',kwargs={'id':self.t.id})
response = self.c.get(url,follow=True)
expected_url = reverse('rower_teams_view')
self.assertRedirects(response,expected_url=expected_url,status_code=302,target_status_code=200)
def test_team_delete_view(self):
login = self.c.login(username=self.u.username, password = self.password)
self.assertTrue(login)
url = reverse('team_delete_view',kwargs={'team_id':self.t.id})
response = self.c.get(url,follow=True)
expected_url = reverse('rower_teams_view')
self.assertRedirects(response,expected_url=expected_url,status_code=302,target_status_code=200)
def test_manager_drop_member(self): def test_manager_drop_member(self):
res = add_member(self.t.id,self.users[1].rower) res = add_member(self.t.id,self.users[1].rower)
login = self.c.login(username=self.u.username, password = self.password) login = self.c.login(username=self.u.username, password = self.password)

View File

@@ -50,7 +50,7 @@ from rowers.utils import (
def cleanbody(body): def cleanbody(body):
try: try:
body = body.decode('utf-8') body = body.decode('utf-8')
except AttributeError: except AttributeError: # pragma: no cover
pass pass
regex = r".*---\n([\s\S]*?)\.\.\..*" regex = r".*---\n([\s\S]*?)\.\.\..*"
@@ -72,7 +72,7 @@ def matchsource(line):
testert = '^source.*(%s)' % s testert = '^source.*(%s)' % s
tester = re.compile(testert) tester = re.compile(testert)
if tester.match(line.lower()): if tester.match(line.lower()): # pragma: no cover
return tester.match(line.lower()).group(1) return tester.match(line.lower()).group(1)
# currently only matches one chart # currently only matches one chart
@@ -88,7 +88,7 @@ def matchchart(line):
tester3 = re.compile(tester3t) tester3 = re.compile(tester3t)
tester4 = re.compile(tester4t) tester4 = re.compile(tester4t)
if tester.match(line.lower()): if tester.match(line.lower()): # pragma: no cover
if tester2.match(line.lower()): if tester2.match(line.lower()):
return 'distanceplot' return 'distanceplot'
if tester3.match(line.lower()): if tester3.match(line.lower()):
@@ -112,7 +112,7 @@ def matchrace(line):
words = line.split() words = line.split()
try: try:
return int(words[1]) return int(words[1])
except: except: # pragma: no cover
return None return None
return None return None
@@ -129,7 +129,7 @@ def matchsync(line):
tester = re.compile(tester) tester = re.compile(tester)
if tester.match(line.lower()): if tester.match(line.lower()): # pragma: no cover
testers = [ testers = [
('upload_to_C2',re.compile(tester2)), ('upload_to_C2',re.compile(tester2)),
('upload_totp',re.compile(tester3)), ('upload_totp',re.compile(tester3)),
@@ -148,7 +148,7 @@ def getstravaid(uploadoptions,body):
stravaid = 0 stravaid = 0
tester = re.compile('^(stravaid)(.*?)(\d+)') tester = re.compile('^(stravaid)(.*?)(\d+)')
for line in body.splitlines(): for line in body.splitlines():
if tester.match(line.lower()): if tester.match(line.lower()): # pragma: no cover
stravaid = tester.match(line.lower()).group(3) stravaid = tester.match(line.lower()).group(3)
uploadoptions['stravaid'] = int(stravaid) uploadoptions['stravaid'] = int(stravaid)
@@ -183,7 +183,7 @@ def gettypeoptions_body2(uploadoptions,body):
def getprivateoptions_body2(uploadoptions,body): def getprivateoptions_body2(uploadoptions,body):
tester = re.compile('^(priva)') tester = re.compile('^(priva)')
for line in body.splitlines(): for line in body.splitlines():
if tester.match(line.lower()): if tester.match(line.lower()): # pragma: no cover
v = True v = True
negs = ['false','False','None','no'] negs = ['false','False','None','no']
for neg in negs: for neg in negs:
@@ -199,7 +199,7 @@ def getprivateoptions_body2(uploadoptions,body):
def getworkoutsources(uploadoptions,body): def getworkoutsources(uploadoptions,body):
for line in body.splitlines(): for line in body.splitlines():
workoutsource = matchsource(line) workoutsource = matchsource(line)
if workoutsource: if workoutsource: # pragma: no cover
uploadoptions['workoutsource'] = workoutsource uploadoptions['workoutsource'] = workoutsource
return uploadoptions return uploadoptions
@@ -207,7 +207,7 @@ def getworkoutsources(uploadoptions,body):
def getplotoptions_body2(uploadoptions,body): def getplotoptions_body2(uploadoptions,body):
for line in body.splitlines(): for line in body.splitlines():
chart = matchchart(line) chart = matchchart(line)
if chart: if chart: # pragma: no cover
uploadoptions['make_plot'] = True uploadoptions['make_plot'] = True
uploadoptions['plottype'] = chart uploadoptions['plottype'] = chart
@@ -236,12 +236,12 @@ def getsyncoptions_body2(uploadoptions,body):
result = list(set(result)) result = list(set(result))
for r in result: for r in result: # pragma: no cover
uploadoptions[r] = True uploadoptions[r] = True
return uploadoptions return uploadoptions
def getsyncoptions(uploadoptions,values): def getsyncoptions(uploadoptions,values): # pragma: no cover
try: try:
value = values.lower() value = values.lower()
values = [values] values = [values]
@@ -269,7 +269,7 @@ def getsyncoptions(uploadoptions,values):
return uploadoptions return uploadoptions
def getplotoptions(uploadoptions,value): def getplotoptions(uploadoptions,value): # pragma: no cover
try: try:
v = value.lower() v = value.lower()
if v in ['pieplot','timeplot','distanceplot']: if v in ['pieplot','timeplot','distanceplot']:
@@ -290,7 +290,7 @@ def getplotoptions(uploadoptions,value):
return uploadoptions return uploadoptions
def gettype(uploadoptions,value,key): def gettype(uploadoptions,value,key): # pragma: no cover
workouttype = 'rower' workouttype = 'rower'
for typ,verb in workouttypes_ordered.items(): for typ,verb in workouttypes_ordered.items():
if value == typ: if value == typ:
@@ -304,7 +304,7 @@ def gettype(uploadoptions,value,key):
return uploadoptions return uploadoptions
def getboattype(uploadoptions,value,key): def getboattype(uploadoptions,value,key): # pragma: no cover
boattype = '1x' boattype = '1x'
for type,verb in boattypes: for type,verb in boattypes:
if value == type: if value == type:
@@ -316,12 +316,12 @@ def getboattype(uploadoptions,value,key):
return uploadoptions return uploadoptions
def getuser(uploadoptions,value,key): def getuser(uploadoptions,value,key): # pragma: no cover
uploadoptions['username'] = value uploadoptions['username'] = value
return uploadoptions return uploadoptions
def getrace(uploadoptions,value,key): def getrace(uploadoptions,value,key): # pragma: no cover
try: try:
raceid = int(value) raceid = int(value)
uploadoptions['raceid'] = raceid uploadoptions['raceid'] = raceid
@@ -330,7 +330,7 @@ def getrace(uploadoptions,value,key):
return uploadoptions return uploadoptions
def getsource(uploadoptions,value,key): def getsource(uploadoptions,value,key): # pragma: no cover
workoutsource = 'unknown' workoutsource = 'unknown'
for type,verb in workoutsources: for type,verb in workoutsources:
if value == type: if value == type:
@@ -342,7 +342,7 @@ def getsource(uploadoptions,value,key):
return uploadoptions return uploadoptions
def getboolean(uploadoptions,value,key): def getboolean(uploadoptions,value,key): # pragma: no cover
b = True b = True
if not value: if not value:
b = False b = False
@@ -361,10 +361,10 @@ def upload_options(body):
body = cleanbody(body) body = cleanbody(body)
try: try:
yml = (yaml.safe_load(body)) yml = (yaml.safe_load(body))
if yml and 'fromuploadform' in yml: if yml and 'fromuploadform' in yml: # pragma: no cover
return yml return yml
try: try:
for key, value in yml.iteritems(): for key, value in yml.iteritems(): # pragma: no cover
lowkey = key.lower() lowkey = key.lower()
if lowkey == 'sync' or lowkey == 'synchronization' or lowkey == 'export': if lowkey == 'sync' or lowkey == 'synchronization' or lowkey == 'export':
uploadoptions = getsyncoptions(uploadoptions,value) uploadoptions = getsyncoptions(uploadoptions,value)
@@ -395,7 +395,7 @@ def upload_options(body):
uploadoptions = getworkoutsources(uploadoptions,body) uploadoptions = getworkoutsources(uploadoptions,body)
uploadoptions = getuseroptions_body2(uploadoptions,body) uploadoptions = getuseroptions_body2(uploadoptions,body)
uploadoptions = getraceoptions_body2(uploadoptions,body) uploadoptions = getraceoptions_body2(uploadoptions,body)
except IOError: except IOError: # pragma: no cover
pm = exc.problem_mark pm = exc.problem_mark
strpm = str(pm) strpm = str(pm)
pbm = "Your email has an issue on line {} at position {}. The error is: ".format( pbm = "Your email has an issue on line {} at position {}. The error is: ".format(
@@ -404,7 +404,7 @@ def upload_options(body):
)+strpm )+strpm
return {'error':pbm} return {'error':pbm}
if uploadoptions == {}: if uploadoptions == {}: # pragma: no cover
uploadoptions['message'] = 'No parsing issue. No valid commands detected' uploadoptions['message'] = 'No parsing issue. No valid commands detected'
return uploadoptions return uploadoptions
@@ -445,7 +445,7 @@ def make_plot(r,w,f1,f2,plottype,title,imagename='',plotnr=0):
} }
axis = r.staticgrids axis = r.staticgrids
if axis == None: if axis == None: # pragma: no cover
gridtrue = False gridtrue = False
axis = 'both' axis = 'both'
else: else:
@@ -482,7 +482,7 @@ def make_plot(r,w,f1,f2,plottype,title,imagename='',plotnr=0):
width=width,height=height) width=width,height=height)
i.save() i.save()
else: else: # pragma: no cover
return 0,'You have reached the maximum number of static images for this workout. Delete an image first' return 0,'You have reached the maximum number of static images for this workout. Delete an image first'
return i.id,job.id return i.id,job.id
@@ -500,24 +500,24 @@ def set_workouttype(w,options):
try: try:
w.workouttype = options['workouttype'] w.workouttype = options['workouttype']
w.save() w.save()
except KeyError: except KeyError: # pragma: no cover
pass pass
try: try:
w.boattype = options['boattype'] w.boattype = options['boattype']
w.save() w.save()
except KeyError: except KeyError: # pragma: no cover
pass pass
return 1 return 1
def set_workoutsource(w,options): def set_workoutsource(w,options): # pragma: no cover
try: try:
w.workoutsource = options['workoutsource'] w.workoutsource = options['workoutsource']
w.save() w.save()
except KeyError: except KeyError: # pragma: no cover
pass pass
def make_private(w,options): def make_private(w,options): # pragma: no cover
if 'makeprivate' in options and options['makeprivate']: if 'makeprivate' in options and options['makeprivate']:
w.privacy = 'hidden' w.privacy = 'hidden'
w.save() w.save()
@@ -533,7 +533,7 @@ def do_sync(w,options, quick=False):
upload_to_strava = False upload_to_strava = False
try: try:
if options['stravaid'] != 0 and options['stravaid'] != '': if options['stravaid'] != 0 and options['stravaid'] != '': # pragma: no cover
w.uploadedtostrava = options['stravaid'] w.uploadedtostrava = options['stravaid']
upload_to_strava = False upload_to_strava = False
do_strava_export = False do_strava_export = False
@@ -542,27 +542,27 @@ def do_sync(w,options, quick=False):
pass pass
try: try:
if options['nkid'] != 0 and options['nkid'] != '': if options['nkid'] != 0 and options['nkid'] != '': # pragma: no cover
w.uploadedtonk = options['nkid'] w.uploadedtonk = options['nkid']
w.save() w.save()
except KeyError: except KeyError:
pass pass
try: try:
if options['inboard'] != 0 and options['inboard'] != '': if options['inboard'] != 0 and options['inboard'] != '': # pragma: no cover
w.inboard = options['inboard'] w.inboard = options['inboard']
except KeyError: except KeyError:
pass pass
try: try:
if options['oarlength'] != 0 and options['oarlength'] != '': if options['oarlength'] != 0 and options['oarlength'] != '': # pragma: no cover
w.oarlength = options['oarlength'] w.oarlength = options['oarlength']
except KeyError: except KeyError:
pass pass
try: try:
if options['garminid'] != 0 and options['garminid'] != '': if options['garminid'] != 0 and options['garminid'] != '': # pragma: no cover
w.uploadedtogarmin = options['garminid'] w.uploadedtogarmin = options['garminid']
w.save() w.save()
except KeyError: except KeyError:
@@ -575,7 +575,7 @@ def do_sync(w,options, quick=False):
upload_to_c2 = False upload_to_c2 = False
try: try:
if options['c2id'] != 0 and options['c2id'] != '': if options['c2id'] != 0 and options['c2id'] != '': # pragma: no cover
w.uploadedtoc2 = options['c2id'] w.uploadedtoc2 = options['c2id']
upload_to_c2 = False upload_to_c2 = False
do_c2_export = False do_c2_export = False
@@ -584,7 +584,7 @@ def do_sync(w,options, quick=False):
pass pass
try: try:
if options['rp3id'] != 0 and options['rp3id'] != '': if options['rp3id'] != 0 and options['rp3id'] != '': # pragma: no cover
w.uploadedtorp3 = options['rp3id'] w.uploadedtorp3 = options['rp3id']
w.save() w.save()
except KeyError: except KeyError:
@@ -599,15 +599,15 @@ def do_sync(w,options, quick=False):
except NoTokenError: except NoTokenError:
id = 0 id = 0
message = "Something went wrong with the Concept2 sync" message = "Something went wrong with the Concept2 sync"
except: except: # pragma: no cover
pass pass
if do_strava_export: if do_strava_export: # pragma: no cover
try: try:
message,id = stravastuff.workout_strava_upload( message,id = stravastuff.workout_strava_upload(
w.user.user,w,quick=quick,asynchron=True, w.user.user,w,quick=quick,asynchron=True,
) )
except NoTokenError: except NoTokenError: # pragma: no cover
id = 0 id = 0
message = "Please connect to Strava first" message = "Please connect to Strava first"
except: except:
@@ -626,7 +626,7 @@ def do_sync(w,options, quick=False):
message,id = sporttracksstuff.workout_sporttracks_upload( message,id = sporttracksstuff.workout_sporttracks_upload(
w.user.user,w,asynchron=True, w.user.user,w,asynchron=True,
) )
with open('st_export.log','a') as logfile: with open('st_export.log','a') as logfile: # pragma: no cover
logfile.write(str(timezone.now())+': ') logfile.write(str(timezone.now())+': ')
logfile.write('Workout uploaded '+str(w.id)+'\n') logfile.write('Workout uploaded '+str(w.id)+'\n')
except NoTokenError: except NoTokenError:
@@ -637,7 +637,7 @@ def do_sync(w,options, quick=False):
id = 0 id = 0
if ('upload_to_RunKeeper' in options and options['upload_to_RunKeeper']) or (w.user.runkeeper_auto_export): if ('upload_to_RunKeeper' in options and options['upload_to_RunKeeper']) or (w.user.runkeeper_auto_export): # pragma: no cover
try: try:
message,id = runkeeperstuff.workout_runkeeper_upload( message,id = runkeeperstuff.workout_runkeeper_upload(
w.user.user,w,asynchron=True, w.user.user,w,asynchron=True,
@@ -646,7 +646,7 @@ def do_sync(w,options, quick=False):
message = "Please connect to Runkeeper first" message = "Please connect to Runkeeper first"
id = 0 id = 0
if ('upload_to_MapMyFitness' in options and options['upload_to_MapMyFitness']) or (w.user.mapmyfitness_auto_export): if ('upload_to_MapMyFitness' in options and options['upload_to_MapMyFitness']) or (w.user.mapmyfitness_auto_export): # pragma: no cover
try: try:
message,id = underarmourstuff.workout_ua_upload( message,id = underarmourstuff.workout_ua_upload(
w.user.user,w w.user.user,w
@@ -656,7 +656,7 @@ def do_sync(w,options, quick=False):
id = 0 id = 0
if ('upload_to_TrainingPeaks' in options and options['upload_to_TrainingPeaks']) or (w.user.trainingpeaks_auto_export): if ('upload_to_TrainingPeaks' in options and options['upload_to_TrainingPeaks']) or (w.user.trainingpeaks_auto_export): # pragma: no cover
try: try:
message,id = tpstuff.workout_tp_upload( message,id = tpstuff.workout_tp_upload(
w.user.user,w w.user.user,w

View File

@@ -15,7 +15,7 @@ def braintree_webhook_view(request):
f.write(timestamp+' /rowers/braintree/\n') f.write(timestamp+' /rowers/braintree/\n')
if request.method == 'POST': if request.method == 'POST':
result = braintreestuff.webhook(request) result = braintreestuff.webhook(request)
if result == 4: if result == 4: # pragma: no cover
raise PermissionDenied("Not allowed") raise PermissionDenied("Not allowed")
return HttpResponse('') return HttpResponse('')
@@ -23,7 +23,7 @@ def braintree_webhook_view(request):
def paidplans_view(request): def paidplans_view(request):
if not request.user.is_anonymous: if not request.user.is_anonymous:
r = request.user.rower r = request.user.rower
if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring': if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring': # pragma: no cover
messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed') messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')
else: else:
r = None r = None
@@ -36,7 +36,7 @@ def paidplans_view(request):
@login_required() @login_required()
def billing_view(request): def billing_view(request):
if not PAYMENT_PROCESSING_ON: if not PAYMENT_PROCESSING_ON: # pragma: no cover
url = reverse('promembership') url = reverse('promembership')
return HttpResponseRedirect(url) return HttpResponseRedirect(url)
@@ -45,7 +45,7 @@ def billing_view(request):
if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring': if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring':
messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed') messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')
if payments.is_existing_customer(r): if payments.is_existing_customer(r): # pragma: no cover
url = reverse(upgrade_view) url = reverse(upgrade_view)
return HttpResponseRedirect(url) return HttpResponseRedirect(url)
@@ -63,7 +63,7 @@ def billing_view(request):
plan = planselectform.cleaned_data['plan'] plan = planselectform.cleaned_data['plan']
try: try:
customer_id = braintreestuff.create_customer(r) customer_id = braintreestuff.create_customer(r)
except ProcessorCustomerError: except ProcessorCustomerError: # pragma: no cover
messages.error(request,"Something went wrong registering you as a customer.") messages.error(request,"Something went wrong registering you as a customer.")
url = reverse(billing_view) url = reverse(billing_view)
return HttpResponseRedirect(url) return HttpResponseRedirect(url)

View File

@@ -49,11 +49,11 @@ def team_view(request,team_id=0,userid=0):
teams.send_invite_email(inviteid) teams.send_invite_email(inviteid)
successmessage = text successmessage = text
messages.info(request,successmessage) messages.info(request,successmessage)
else: else: # pragma: no cover
message = text message = text
messages.error(request,message) messages.error(request,message)
groupmessageform = TeamMessageForm() groupmessageform = TeamMessageForm()
elif request.method == 'POST' and request.user == t.manager and 'message' in request.POST: elif request.method == 'POST' and request.user == t.manager and 'message' in request.POST: # pragma: no cover
groupmessageform = TeamMessageForm(request.POST) groupmessageform = TeamMessageForm(request.POST)
inviteform = TeamInviteForm() inviteform = TeamInviteForm()
if groupmessageform.is_valid(): if groupmessageform.is_valid():
@@ -110,7 +110,7 @@ def team_view(request,team_id=0,userid=0):
def team_leaveconfirm_view(request,id=0): def team_leaveconfirm_view(request,id=0):
try: try:
t = Team.objects.get(id=id) t = Team.objects.get(id=id)
except Team.DoesNotExist: except Team.DoesNotExist: # pragma: no cover # pragma: no cover
raise Http404("Team doesn't exist") raise Http404("Team doesn't exist")
myteams, memberteams, otherteams = get_teams(request) myteams, memberteams, otherteams = get_teams(request)
@@ -181,7 +181,7 @@ def get_teams(request):
return myteams, memberteams, otherteams return myteams, memberteams, otherteams
@login_required() @login_required()
def rower_teams_view(request): def rower_teams_view(request): # pragma: no cover
if request.method == 'POST': if request.method == 'POST':
form = TeamInviteCodeForm(request.POST) form = TeamInviteCodeForm(request.POST)
if form.is_valid(): if form.is_valid():
@@ -239,7 +239,7 @@ def rower_teams_view(request):
user__in=invitedathletes).exclude( user__in=invitedathletes).exclude(
user=request.user user=request.user
).exclude(coachinggroups__in=[request.user.rower.mycoachgroup]) ).exclude(coachinggroups__in=[request.user.rower.mycoachgroup])
elif request.user.rower.rowerplan == 'freecoach': elif request.user.rower.rowerplan == 'freecoach': # pragma: no cover
potentialathletes = Rower.objects.filter( potentialathletes = Rower.objects.filter(
team__in=myteams).exclude( team__in=myteams).exclude(
user__in=invitedathletes).exclude( user__in=invitedathletes).exclude(
@@ -295,7 +295,7 @@ def invitation_revoke_view(request,id):
if res: if res:
messages.info(request,text) messages.info(request,text)
successmessage = text successmessage = text
else: else: # pragma: no cover
message = text message = text
messages.error(request,text) messages.error(request,text)
@@ -310,7 +310,7 @@ def manager_member_drop_view(request,teamid,userid,
res, text = teams.mgr_remove_member(teamid,request.user,rower) res, text = teams.mgr_remove_member(teamid,request.user,rower)
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
url = reverse(rower_teams_view) url = reverse(rower_teams_view)
@@ -321,7 +321,7 @@ def manager_member_drop_view(request,teamid,userid,
def manager_requests_view(request,code=None): def manager_requests_view(request,code=None):
if code: if code:
res,text = teams.process_request_code(request.user,code) res,text = teams.process_request_code(request.user,code)
if res: if res: # pragma: no cover
messages.info(request,text) messages.info(request,text)
else: else:
messages.error(request,text) messages.error(request,text)
@@ -335,9 +335,9 @@ def athlete_drop_coach_confirm_view(request,id):
r = getrower(request.user) r = getrower(request.user)
try: try:
coach = Rower.objects.get(id=id) coach = Rower.objects.get(id=id)
except Rower.DoesNotExist: except Rower.DoesNotExist: # pragma: no cover # pragma: no cover
raise Http404("This rower doesn't exist") raise Http404("This rower doesn't exist")
if coach not in teams.rower_get_coaches(r): if coach not in teams.rower_get_coaches(r): # pragma: no cover
raise PermissionDenied("You are not allowed to do this") raise PermissionDenied("You are not allowed to do this")
breadcrumbs = [ breadcrumbs = [
@@ -362,9 +362,9 @@ def coach_drop_athlete_confirm_view(request,id):
r = getrower(request.user) r = getrower(request.user)
try: try:
rower = Rower.objects.get(id=id) rower = Rower.objects.get(id=id)
except Rower.DoesNotExist: except Rower.DoesNotExist: # pragma: no cover # pragma: no cover
raise Http404("This rower doesn't exist") raise Http404("This rower doesn't exist")
if rower not in teams.coach_getcoachees(r): if rower not in teams.coach_getcoachees(r): # pragma: no cover
raise PermissionDenied("You are not allowed to do this") raise PermissionDenied("You are not allowed to do this")
breadcrumbs = [ breadcrumbs = [
@@ -389,16 +389,16 @@ def coach_drop_athlete_view(request,id):
r = getrower(request.user) r = getrower(request.user)
try: try:
rower = Rower.objects.get(id=id) rower = Rower.objects.get(id=id)
except Rower.DoesNotExist: except Rower.DoesNotExist: # pragma: no cover
raise Http404("This rower doesn't exist") raise Http404("This rower doesn't exist")
if rower not in teams.coach_getcoachees(r): if rower not in teams.coach_getcoachees(r): # pragma: no cover
raise PermissionDenied("You are not allowed to do this") raise PermissionDenied("You are not allowed to do this")
res,text = teams.coach_remove_athlete(r,rower) res,text = teams.coach_remove_athlete(r,rower)
if res: if res:
messages.info(request,'You are not coaching this athlete any more') messages.info(request,'You are not coaching this athlete any more')
else: else: # pragma: no cover
messages.error(request,'There was an error dropping the athlete from your list') messages.error(request,'There was an error dropping the athlete from your list')
url = reverse('rower_teams_view') url = reverse('rower_teams_view')
@@ -410,16 +410,16 @@ def athlete_drop_coach_view(request,id):
r = getrower(request.user) r = getrower(request.user)
try: try:
coach = Rower.objects.get(id=id) coach = Rower.objects.get(id=id)
except Rower.DoesNotExist: except Rower.DoesNotExist: # pragma: no cover
raise Http404("This coach doesn't exist") raise Http404("This coach doesn't exist")
if coach not in teams.rower_get_coaches(r): if coach not in teams.rower_get_coaches(r): # pragma: no cover
raise PermissionDenied("You are not allowed to do this") raise PermissionDenied("You are not allowed to do this")
res,text = teams.coach_remove_athlete(coach,r) res,text = teams.coach_remove_athlete(coach,r)
if res: if res:
messages.info(request,'Removal successful') messages.info(request,'Removal successful')
else: else: # pragma: no cover
messages.error(request,'There was an error dropping the coach from your list') messages.error(request,'There was an error dropping the coach from your list')
url = reverse('rower_teams_view') url = reverse('rower_teams_view')
@@ -430,7 +430,7 @@ def athlete_drop_coach_view(request,id):
def team_requestmembership_view(request,teamid,userid): def team_requestmembership_view(request,teamid,userid):
try: try:
t = Team.objects.get(id=teamid) t = Team.objects.get(id=teamid)
except Team.DoesNotExist: except Team.DoesNotExist: # pragma: no cover
raise Http404("Team doesn't exist") raise Http404("Team doesn't exist")
r = getrequestrower(request,userid=userid) r = getrequestrower(request,userid=userid)
@@ -446,7 +446,7 @@ def team_requestmembership_view(request,teamid,userid):
res,text = teams.create_request(t,userid) res,text = teams.create_request(t,userid)
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
@@ -467,9 +467,9 @@ def request_coaching_view(request,coachid):
res,text = teams.create_coaching_request(coach,request.user) res,text = teams.create_coaching_request(coach,request.user)
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
else: else: # pragma: no cover
messages.error(request,'That person is not a coach') messages.error(request,'That person is not a coach')
url = reverse('rower_teams_view') url = reverse('rower_teams_view')
@@ -480,7 +480,7 @@ def request_coaching_view(request,coachid):
def offer_coaching_view(request,userid): def offer_coaching_view(request,userid):
try: try:
u = User.objects.get(id=userid) u = User.objects.get(id=userid)
except User.DoesNotExist: except User.DoesNotExist: # pragma: no cover
raise Http404("This user doesn't exist") raise Http404("This user doesn't exist")
coach = getrequestrower(request) coach = getrequestrower(request)
@@ -489,7 +489,7 @@ def offer_coaching_view(request,userid):
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
url = reverse('rower_teams_view') url = reverse('rower_teams_view')
@@ -502,7 +502,7 @@ def reject_revoke_coach_request(request,id=0):
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
url = reverse('rower_teams_view') url = reverse('rower_teams_view')
@@ -515,7 +515,7 @@ def reject_revoke_coach_offer(request,id=0):
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
url = reverse('rower_teams_view') url = reverse('rower_teams_view')
@@ -529,7 +529,7 @@ def request_revoke_view(request,id=0):
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
url = reverse(rower_teams_view) url = reverse(rower_teams_view)
@@ -542,7 +542,7 @@ def request_reject_view(request,id=0):
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
url = reverse(rower_teams_view) url = reverse(rower_teams_view)
@@ -555,7 +555,7 @@ def invitation_reject_view(request,id=0):
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
url = reverse(rower_teams_view) url = reverse(rower_teams_view)
@@ -568,7 +568,7 @@ def rower_invitations_view(request,code=None,message='',successmessage=''):
if code: if code:
teams.remove_expired_invites() teams.remove_expired_invites()
res,text = teams.process_invite_code(request.user,code) res,text = teams.process_invite_code(request.user,code)
if res: if res: # pragma: no cover
messages.info(request,text) messages.info(request,text)
teamid=res teamid=res
url = reverse(team_view,kwargs={ url = reverse(team_view,kwargs={
@@ -591,7 +591,7 @@ def team_edit_view(request, team_id=0):
t = get_object_or_404(Team,pk=team_id) t = get_object_or_404(Team,pk=team_id)
if request.method == 'POST': if request.method == 'POST': # pragma: no cover
teamcreateform = TeamForm(request.POST,instance=t) teamcreateform = TeamForm(request.POST,instance=t)
if teamcreateform.is_valid(): if teamcreateform.is_valid():
cd = teamcreateform.cleaned_data cd = teamcreateform.cleaned_data
@@ -666,7 +666,7 @@ def team_create_view(request):
res,message=teams.create_team(name,manager,private,notes, res,message=teams.create_team(name,manager,private,notes,
viewing) viewing)
if not res: if not res: # pragma: no cover
messages.error(request,message) messages.error(request,message)
url = reverse('paidplans_view') url = reverse('paidplans_view')
return HttpResponseRedirect(url) return HttpResponseRedirect(url)
@@ -792,7 +792,7 @@ def rower_accept_coachoffer_view(request,code=None):
res, text = teams.process_coachoffer_code(request.user,code) res, text = teams.process_coachoffer_code(request.user,code)
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
url = reverse('rower_teams_view') url = reverse('rower_teams_view')
@@ -804,7 +804,7 @@ def coach_accept_coachrequest_view(request,code=None):
res, text = teams.process_coachrequest_code(request.user.rower,code) res, text = teams.process_coachrequest_code(request.user.rower,code)
if res: if res:
messages.info(request,text) messages.info(request,text)
else: else: # pragma: no cover
messages.error(request,text) messages.error(request,text)
url = reverse('rower_teams_view') url = reverse('rower_teams_view')

View File

@@ -16,7 +16,7 @@ def deactivate_user(request):
if user_form.is_valid(): if user_form.is_valid():
if not user_form.cleaned_data['is_active']: if not user_form.cleaned_data['is_active']:
r = Rower.objects.get(user=user) r = Rower.objects.get(user=user)
if r.paidplan is not None and r.paidplan.paymentprocessor == 'braintree': if r.paidplan is not None and r.paidplan.paymentprocessor == 'braintree': # pragma: no cover
try: try:
subscriptions = braintreestuff.find_subscriptions(r) subscriptions = braintreestuff.find_subscriptions(r)
for subscription in subscriptions: for subscription in subscriptions:
@@ -44,7 +44,7 @@ def deactivate_user(request):
return render(request, "userprofile_deactivate.html", { return render(request, "userprofile_deactivate.html", {
"user_form": user_form, "user_form": user_form,
}) })
else: else: # pragma: no cover
raise PermissionDenied raise PermissionDenied
@login_required() @login_required()
@@ -54,7 +54,7 @@ def user_gdpr_optin(request):
r.gdproptindate = None r.gdproptindate = None
r.save() r.save()
nexturl = request.GET.get('next','/rowers/list-workouts/') nexturl = request.GET.get('next','/rowers/list-workouts/')
if r.gdproptin: if r.gdproptin: # pragma: no cover
return HttpResponseRedirect(nexturl) return HttpResponseRedirect(nexturl)
return render(request,'gdpr_optin.html',{ return render(request,'gdpr_optin.html',{
@@ -88,7 +88,7 @@ def remove_user(request):
email = user.email email = user.email
r = Rower.objects.get(user=user) r = Rower.objects.get(user=user)
if r.paidplan is not None and r.paidplan.paymentprocessor == 'braintree': if r.paidplan is not None and r.paidplan.paymentprocessor == 'braintree': # pragma: no cover
try: try:
subscriptions = braintreestuff.find_subscriptions(r) subscriptions = braintreestuff.find_subscriptions(r)
for subscription in subscriptions: for subscription in subscriptions:
@@ -115,12 +115,12 @@ def remove_user(request):
return render(request, "userprofile_delete.html", { return render(request, "userprofile_delete.html", {
"user_form": user_form, "user_form": user_form,
}) })
else: else: # pragma: no cover
raise PermissionDenied raise PermissionDenied
@login_required() @login_required()
def survey(request): def survey(request): # pragma: no cover
r = getrower(request.user) r = getrower(request.user)
@@ -148,7 +148,7 @@ def survey(request):
def start_trial_view(request): def start_trial_view(request):
r = getrower(request.user) r = getrower(request.user)
if not can_start_trial(request.user): if not can_start_trial(request.user): # pragma: no cover
messages.error(request,'You do not qualify for a trial') messages.error(request,'You do not qualify for a trial')
url = '/rowers/paidplans' url = '/rowers/paidplans'
return HttpResponseRedirect(url) return HttpResponseRedirect(url)
@@ -182,7 +182,7 @@ def start_trial_view(request):
def start_plantrial_view(request): def start_plantrial_view(request):
r = getrower(request.user) r = getrower(request.user)
if not can_start_plantrial(request.user): if not can_start_plantrial(request.user): # pragma: no cover
messages.error(request,'You do not qualify for a trial') messages.error(request,'You do not qualify for a trial')
url = '/rowers/paidplans' url = '/rowers/paidplans'
return HttpResponseRedirect(url) return HttpResponseRedirect(url)
@@ -239,7 +239,7 @@ def rower_favoritecharts_view(request,userid=0):
if aantal==0: if aantal==0:
FavoriteChartFormSet = formset_factory(FavoriteForm,formset=BaseFavoriteFormSet,extra=1) FavoriteChartFormSet = formset_factory(FavoriteForm,formset=BaseFavoriteFormSet,extra=1)
if request.method == 'POST' and 'staticgrids' in request.POST: if request.method == 'POST' and 'staticgrids' in request.POST: # pragma: no cover
staticchartform = StaticChartRowerForm(request.POST,instance=r) staticchartform = StaticChartRowerForm(request.POST,instance=r)
if staticchartform.is_valid(): if staticchartform.is_valid():
r.staticgrids = staticchartform.cleaned_data.get('staticgrids') r.staticgrids = staticchartform.cleaned_data.get('staticgrids')
@@ -252,7 +252,7 @@ def rower_favoritecharts_view(request,userid=0):
r.usersmooth = staticchartform.cleaned_data.get('usersmooth') r.usersmooth = staticchartform.cleaned_data.get('usersmooth')
r.save() r.save()
if request.method == 'POST' and 'save_data' in request.POST: if request.method == 'POST' and 'save_data' in request.POST: # pragma: no cover
datasettingsform = DataRowerForm(request.POST,instance=r) datasettingsform = DataRowerForm(request.POST,instance=r)
if datasettingsform.is_valid(): if datasettingsform.is_valid():
cd = datasettingsform.cleaned_data cd = datasettingsform.cleaned_data
@@ -262,7 +262,7 @@ def rower_favoritecharts_view(request,userid=0):
r.save() r.save()
messages.info(request,"We have updated your data settings") messages.info(request,"We have updated your data settings")
if request.method == 'POST' and 'defaults_data' in request.POST: if request.method == 'POST' and 'defaults_data' in request.POST: # pragma: no cover
defaultsmooth = Rower._meta.get_field('dosmooth').get_default() defaultsmooth = Rower._meta.get_field('dosmooth').get_default()
defaultautojoin = Rower._meta.get_field('autojoin').get_default() defaultautojoin = Rower._meta.get_field('autojoin').get_default()
defaultergcalcpower = Rower._meta.get_field('erg_recalculatepower').get_default() defaultergcalcpower = Rower._meta.get_field('erg_recalculatepower').get_default()
@@ -273,7 +273,7 @@ def rower_favoritecharts_view(request,userid=0):
datasettingsform = DataRowerForm(instance=r) datasettingsform = DataRowerForm(instance=r)
messages.info(request,"We have reset your data settings to the default values") messages.info(request,"We have reset your data settings to the default values")
if request.method == 'POST' and 'form-TOTAL_FORMS' in request.POST: if request.method == 'POST' and 'form-TOTAL_FORMS' in request.POST: # pragma: no cover
favorites_formset = FavoriteChartFormSet(request.POST) favorites_formset = FavoriteChartFormSet(request.POST)
if favorites_formset.is_valid(): if favorites_formset.is_valid():
new_instances = [] new_instances = []
@@ -344,7 +344,7 @@ def rower_exportsettings_view(request,userid=0):
form = RowerExportForm(request.POST) form = RowerExportForm(request.POST)
if form.is_valid(): if form.is_valid():
cd = form.cleaned_data cd = form.cleaned_data
if r.rowerplan == 'basic': if r.rowerplan == 'basic': # pragma: no cover
messages.error(request,'These settings can only be set if you are a user on one of the <a href="/rowers/paidplans">paid plans</a>.') messages.error(request,'These settings can only be set if you are a user on one of the <a href="/rowers/paidplans">paid plans</a>.')
for attr, value in cd.items(): for attr, value in cd.items():
@@ -355,7 +355,7 @@ def rower_exportsettings_view(request,userid=0):
doset = False doset = False
except KeyError: except KeyError:
doset = True doset = True
if r.rowerplan == 'basic': if r.rowerplan == 'basic': # pragma: no cover
doset = False doset = False
if not doset: if not doset:
before = getattr(r,attr) before = getattr(r,attr)
@@ -426,7 +426,7 @@ def rower_edit_view(request,rowerid=0,userid=0,message=""):
sex = cd['sex'] sex = cd['sex']
try: try:
offercoaching = cd['offercoaching'] offercoaching = cd['offercoaching']
except KeyError: except KeyError: # pragma: no cover
offercoaching = False offercoaching = False
autojoin = cd['autojoin'] autojoin = cd['autojoin']
adaptiveclass = cd['adaptiveclass'] adaptiveclass = cd['adaptiveclass']
@@ -440,7 +440,7 @@ def rower_edit_view(request,rowerid=0,userid=0,message=""):
fav_analysis = cd['fav_analysis'] fav_analysis = cd['fav_analysis']
usersmooth = cd['usersmooth'] usersmooth = cd['usersmooth']
u = r.user u = r.user
if u.email != email and len(email): if u.email != email and len(email): # pragma: no cover
resetbounce = True resetbounce = True
else: else:
resetbounce = False resetbounce = False
@@ -470,7 +470,7 @@ def rower_edit_view(request,rowerid=0,userid=0,message=""):
r.usersmooth = usersmooth r.usersmooth = usersmooth
if resetbounce and r.emailbounced: if resetbounce and r.emailbounced: # pragma: no cover
r.emailbounced = False r.emailbounced = False
r.save() r.save()
@@ -607,7 +607,7 @@ def rower_prefs_view(request,userid=0,message=""):
r.save() r.save()
successmessage = "Your Power Zone data were changed" successmessage = "Your Power Zone data were changed"
messages.info(request,successmessage) messages.info(request,successmessage)
elif request.method == 'POST' and 'cprange' in request.POST: elif request.method == 'POST' and 'cprange' in request.POST: # pragma: no cover
cpform = RowerCPForm(request.POST) cpform = RowerCPForm(request.POST)
if cpform.is_valid(): if cpform.is_valid():
cd = cpform.cleaned_data cd = cpform.cleaned_data
@@ -638,7 +638,7 @@ def rower_prefs_view(request,userid=0,message=""):
# this views is called when you press a button on the User edit page # this views is called when you press a button on the User edit page
# the button is only there when you have granted access to an app # the button is only there when you have granted access to an app
@login_required() @login_required()
def rower_revokeapp_view(request,id=0): def rower_revokeapp_view(request,id=0): # pragma: no cover
try: try:
tokens = AccessToken.objects.filter(user=request.user,application=id) tokens = AccessToken.objects.filter(user=request.user,application=id)
refreshtokens = AccessToken.objects.filter(user=request.user,application=id) refreshtokens = AccessToken.objects.filter(user=request.user,application=id)
@@ -662,7 +662,7 @@ def rower_update_empower_view(
request, request,
startdate=timezone.now()-datetime.timedelta(days=365), startdate=timezone.now()-datetime.timedelta(days=365),
enddate=timezone.now() enddate=timezone.now()
): ): # pragma: no cover
try: try:
r = getrower(request.user) r = getrower(request.user)
except Rower.DoesNotExist: except Rower.DoesNotExist: