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
def process_webhook(notification):
with open('braintreewebhooks.log','a') as f:
t = time.localtime()
timestamp = time.strftime('%b-%d-%Y_%H%M', t)
f.write(timestamp+' '+notification.kind+'\n')
if not settings.TESTING: # pragma: no cover
with open('braintreewebhooks.log','a') as f:
t = time.localtime()
timestamp = time.strftime('%b-%d-%Y_%H%M', t)
f.write(timestamp+' '+notification.kind+'\n')
if notification.kind == 'subscription_charged_successfully':
return send_invoice(notification.subscription)
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'):
# 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')
if not is_coach(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')
try:
@@ -102,13 +102,13 @@ def remove_team(id):
send_team_delete_mail(t,r)
return t.delete()
return (1,'Updated rower team expiry')
return (1,'Updated rower team expiry') # pragma: no cover
def add_coach(coach,rower):
# get coaching group
coachgroup = coach.mycoachgroup
if coachgroup is None:
if coachgroup is None: # pragma: no cover
coachgroup = CoachingGroup(name=coach.user.first_name)
coachgroup.save()
coach.mycoachgroup = coachgroup
@@ -118,14 +118,14 @@ def add_coach(coach,rower):
rower.coachinggroups.add(coach.mycoachgroup)
return (1,"Added Coach")
else:
else: # pragma: no cover
return (0,"Maximum number of athletes reached")
def add_member(id,rower):
t= Team.objects.get(id=id)
try:
rower.team.add(t)
except ValidationError as e:
except ValidationError as e: # pragma: no cover
return(0,"Couldn't add member: "+str(e.message))
# code to add all workouts
@@ -135,12 +135,12 @@ def add_member(id,rower):
# code to add plannedsessions
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)
# set_teamplanexpires(rower)
# 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.save()
@@ -157,10 +157,10 @@ def remove_member(id,rower):
# set_teamplanexpires(rower)
return (id,'Member removed')
def remove_coach(coach,rower):
def remove_coach(coach,rower): # pragma: no cover
try:
coachgroup = coach.mycoachgroup
except CoachingGroup.DoesNotExist:
except CoachingGroup.DoesNotExist: # pragma: no cover
coachgroup = CoachingGroup()
coachgroup.save()
coach.mycoachgroup = coachgroup
@@ -195,7 +195,7 @@ def coach_getcoachees(coach):
def coach_remove_athlete(coach,rower):
try:
coachgroup = coach.mycoachgroup
except CoachingGroup.DoesNotExist:
except CoachingGroup.DoesNotExist: # pragma: no cover
coachgroup = CoachingGroup()
coachgroup.save()
coach.mycoachgroup = coachgroup
@@ -211,12 +211,12 @@ def mgr_remove_member(id,manager,rower):
remove_member(id,rower)
send_email_member_dropped(id,rower)
return (id,'Member removed')
else:
else: # pragma: no cover
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)
count = 0
for t in ts:
@@ -225,7 +225,7 @@ def count_invites(manager):
return count
def count_club_members(manager):
def count_club_members(manager): # pragma: no cover
ts = Team.objects.filter(manager=manager)
return Rower.objects.filter(team__in=ts).distinct().count()
@@ -233,13 +233,13 @@ def count_club_members(manager):
# Medium level functionality
# 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):
return (0,'Already coached by that coach')
codes = [i.code for i in CoachRequest.objects.all()]
code = uuid.uuid4().hex[:10].upper()
while code in codes:
while code in codes: # pragma: no cover
code = uuid.uuid4().hex[:10].upper()
if 'coach' in coach.rowerplan:
@@ -250,7 +250,7 @@ def create_coaching_request(coach,user):
return (rekwest.id,'The request was created')
else:
else: # pragma: no cover
return (0,'That person is not a coach')
def send_coachrequest_email(rekwest):
@@ -280,14 +280,14 @@ def send_coacheerequest_email(rekwest):
def create_request(team,user):
r2 = Rower.objects.get(user=user)
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')
# if count_club_members(team.manager)+count_invites(team.manager) <= r.clubsize:
codes = [i.code for i in TeamRequest.objects.all()]
code = uuid.uuid4().hex[:10].upper()
# prevent duplicates
while code in codes:
while code in codes: # pragma: no cover
code = uuid.uuid4().hex[:10].upper()
u = User.objects.get(id=user)
@@ -298,7 +298,7 @@ def create_request(team,user):
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):
rs = Rower.objects.filter(coachinggroups__in=[coach.mycoachgroup])
@@ -313,12 +313,12 @@ def get_coach_club_size(coach):
def create_coaching_offer(coach,user):
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.')
codes = [i.code for i in CoachOffer.objects.all()]
code = uuid.uuid4().hex[:10].upper()
while code in codes:
while code in codes: # pragma: no cover
code = uuid.uuid4().hex[:10].upper()
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)
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')
else:
else: # pragma: no cover
return (0,'You are not a coach')
@@ -345,26 +345,26 @@ def create_invite(team,manager,user=None,email=''):
try:
r2 = Rower.objects.get(user=user)
email = r2.user.email
except Rower.DoesNotExist:
except Rower.DoesNotExist: # pragma: no cover
return (0,'Rower does not exist')
if r2 in Rower.objects.filter(team=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')
else:
try:
r2 = Rower.objects.get(user__email=email)
user = User.objects.get(rower=r2)
except Rower.DoesNotExist:
except Rower.DoesNotExist: # pragma: no cover
user=None
except Rower.MultipleObjectsReturned:
except Rower.MultipleObjectsReturned: # pragma: no cover
return (0,'There is more than one user with that email address')
# if count_club_members(team.manager)+count_invites(team.manager) <= r.clubsize:
codes = [i.code for i in TeamInvite.objects.all()]
code = uuid.uuid4().hex[:10].upper()
# prevent duplicates
while code in codes:
while code in codes: # pragma: no cover
code = uuid.uuid4().hex[:10].upper()
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 (0,'Nothing done')
return (0,'Nothing done') # pragma: no cover
def revoke_request(user,id):
try:
rekwest = TeamRequest.objects.get(id=id)
except TeamRequest.DoesNotExist:
except TeamRequest.DoesNotExist: # pragma: no cover
return (0,'The request is invalid')
t = rekwest.team
@@ -385,13 +385,13 @@ def revoke_request(user,id):
if rekwest.user==user:
rekwest.delete()
return (1,'Request revoked')
else:
else: # pragma: no cover
return (0,'You are not the requestor')
def reject_revoke_coach_offer(user,id):
try:
rekwest = CoachOffer.objects.get(id=id)
except CoachOffer.DoesNotExist:
except CoachOffer.DoesNotExist: # pragma: no cover
return (0,'The request is invalid')
if rekwest.coach.user == user:
@@ -402,13 +402,13 @@ def reject_revoke_coach_offer(user,id):
send_coachoffer_rejected_email(rekwest)
rekwest.delete()
return (1,'Request removed')
else:
else: # pragma: no cover
return (0,'Not permitted')
def reject_revoke_coach_request(user,id):
try:
rekwest = CoachRequest.objects.get(id=id)
except CoachRequest.DoesNotExist:
except CoachRequest.DoesNotExist: # pragma: no cover
return (0,'The request is invalid')
if rekwest.coach.user == user:
@@ -418,59 +418,59 @@ def reject_revoke_coach_request(user,id):
elif rekwest.user == user:
rekwest.delete()
return (1,'Request rejected')
else:
else: # pragma: no cover
return (0,'Not permitted')
def revoke_invite(manager,id):
try:
invite = TeamInvite.objects.get(id=id)
except TeamInvite.DoesNotExist:
except TeamInvite.DoesNotExist: # pragma: no cover
return (0,'The invitation is invalid')
if is_team_manager(manager,invite.team):
invite.delete()
return (1,'Invitation revoked')
else:
else: # pragma: no cover
return (0,'You are not the team manager')
def reject_request(manager,id):
try:
rekwest = TeamRequest.objects.get(id=id)
except TeamRequest.DoesNotExist:
except TeamRequest.DoesNotExist: # pragma: no cover
return (0,'The request is invalid')
if is_team_manager(manager,rekwest.team):
send_request_reject_email(rekwest)
rekwest.delete()
return (1,'Request rejected')
else:
else: # pragma: no cover
return (0,'You are not the manager for this request')
def reject_invitation(user,id):
try:
invite = TeamInvite.objects.get(id=id)
except TeamInvite.DoesNotExist:
except TeamInvite.DoesNotExist: # pragma: no cover
return (0,'The invitation is invalid')
if invite.user==user:
send_invite_reject_email(invite)
invite.delete()
return (1,'Invitation rejected')
else:
else: # pragma: no cover
return (0,'This request was not for you')
def send_invite_email(id):
try:
invitation = TeamInvite.objects.get(id=id)
except TeamInvite.DoesNotExist:
except TeamInvite.DoesNotExist: # pragma: no cover
return (0,'Invitation doesn not exist')
if invitation.user:
email = invitation.user.email
name = invitation.user.first_name + " " + invitation.user.last_name
else:
else: # pragma: no cover
email = invitation.email
name = ''
@@ -510,7 +510,7 @@ def send_email_member_dropped(teamid,rower):
return (1,'Member dropped email sent')
def send_request_accept_email(rekwest):
def send_request_accept_email(rekwest): # pragma: no cover
id = rekwest.id
email = rekwest.user.email
teamname = rekwest.team.name
@@ -542,7 +542,7 @@ def send_invite_reject_email(invitation):
email = invitation.team.manager.email
if invitation.user:
name = invitation.user.first_name+' '+invitation.user.last_name
else:
else: # pragma: no cover
name = invitation.email
teamname = invitation.team.name
@@ -555,7 +555,7 @@ def send_invite_reject_email(invitation):
return (1,'Invitation email sent')
def send_invite_accept_email(invitation):
def send_invite_accept_email(invitation): # pragma: no cover
id = invitation.id
email = invitation.team.manager.email
if invitation.user:
@@ -572,7 +572,7 @@ def send_invite_accept_email(invitation):
return (1,'Invitation email sent')
def send_team_message(team,message):
def send_team_message(team,message): # pragma: no cover
rowers = team.rower.all()
managername = team.manager.first_name + " " + team.manager.last_name
@@ -598,7 +598,7 @@ def send_request_email(rekwest):
return (1,'Invitation email sent')
def process_request_code(manager,code):
def process_request_code(manager,code): # pragma: no cover
code = code.upper()
try:
@@ -623,7 +623,7 @@ def process_request_code(manager,code):
rekwest.delete()
return (result,'The member was added')
def process_invite_code(user,code):
def process_invite_code(user,code): # pragma: no cover
code = code.upper()
try:
invitation = TeamInvite.objects.get(code=code)
@@ -646,7 +646,7 @@ def process_invite_code(user,code):
invitation.delete()
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 = datetime.date(issuedate)
invitations = TeamInvite.objects.filter(issuedate__lt=issuedate)
@@ -660,14 +660,14 @@ def process_coachrequest_code(coach,code):
try:
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')
if rekwest.coach != coach:
if rekwest.coach != coach: # pragma: no cover
return (0,'The request is invalid')
result = add_coach(coach,rekwest.user.rower)
if not result:
if not result: # pragma: no cover
return result
else:
send_coachrequest_accepted_email(rekwest)
@@ -681,14 +681,14 @@ def process_coachoffer_code(user,code):
try:
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')
if rekwest.user != user:
if rekwest.user != user: # pragma: no cover
return (0,'The request is invalid')
result = add_coach(rekwest.coach,rekwest.user.rower)
if not result:
if not result: # pragma: no cover
return result
else:
send_coachoffer_accepted_email(rekwest)

View File

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

View File

@@ -627,6 +627,16 @@ class payment_method():
def __init__(self, *args, **kwargs):
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
class MockBraintreeGateway:
def __init__(self,*args, **kwargs):
@@ -636,6 +646,7 @@ class MockBraintreeGateway:
self.transaction = transaction()
self.subscription = subscription()
self.payment_method = payment_method()
self.webhook_notification = webhook_notification()
def mocked_gateway(*args, **kwargs):
@@ -1218,3 +1229,6 @@ class MockOAuth1Session:
def post(*args, **kwargs):
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
import urllib
class PaymentTest(TestCase):
def setUp(self):
@@ -55,9 +57,122 @@ class PaymentTest(TestCase):
self.c = Client()
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):
# 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.gateway',side_effect=MockBraintreeGateway)
def test_billing_view(self,mocked_create_customer,mocked_gateway):
@@ -284,6 +399,100 @@ class PaymentTest(TestCase):
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)
def test_planstobasic_view(self,mocked_gateway):
u = UserFactory()

View File

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

View File

@@ -114,6 +114,25 @@ class TeamTest(TestCase):
except (IOError, FileNotFoundError,OSError):
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):
res = add_member(self.t.id,self.users[1].rower)
login = self.c.login(username=self.u.username, password = self.password)

View File

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

View File

@@ -15,7 +15,7 @@ def braintree_webhook_view(request):
f.write(timestamp+' /rowers/braintree/\n')
if request.method == 'POST':
result = braintreestuff.webhook(request)
if result == 4:
if result == 4: # pragma: no cover
raise PermissionDenied("Not allowed")
return HttpResponse('')
@@ -23,7 +23,7 @@ def braintree_webhook_view(request):
def paidplans_view(request):
if not request.user.is_anonymous:
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')
else:
r = None
@@ -36,7 +36,7 @@ def paidplans_view(request):
@login_required()
def billing_view(request):
if not PAYMENT_PROCESSING_ON:
if not PAYMENT_PROCESSING_ON: # pragma: no cover
url = reverse('promembership')
return HttpResponseRedirect(url)
@@ -45,7 +45,7 @@ def billing_view(request):
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')
if payments.is_existing_customer(r):
if payments.is_existing_customer(r): # pragma: no cover
url = reverse(upgrade_view)
return HttpResponseRedirect(url)
@@ -63,7 +63,7 @@ def billing_view(request):
plan = planselectform.cleaned_data['plan']
try:
customer_id = braintreestuff.create_customer(r)
except ProcessorCustomerError:
except ProcessorCustomerError: # pragma: no cover
messages.error(request,"Something went wrong registering you as a customer.")
url = reverse(billing_view)
return HttpResponseRedirect(url)

View File

@@ -49,11 +49,11 @@ def team_view(request,team_id=0,userid=0):
teams.send_invite_email(inviteid)
successmessage = text
messages.info(request,successmessage)
else:
else: # pragma: no cover
message = text
messages.error(request,message)
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)
inviteform = TeamInviteForm()
if groupmessageform.is_valid():
@@ -110,7 +110,7 @@ def team_view(request,team_id=0,userid=0):
def team_leaveconfirm_view(request,id=0):
try:
t = Team.objects.get(id=id)
except Team.DoesNotExist:
except Team.DoesNotExist: # pragma: no cover # pragma: no cover
raise Http404("Team doesn't exist")
myteams, memberteams, otherteams = get_teams(request)
@@ -181,7 +181,7 @@ def get_teams(request):
return myteams, memberteams, otherteams
@login_required()
def rower_teams_view(request):
def rower_teams_view(request): # pragma: no cover
if request.method == 'POST':
form = TeamInviteCodeForm(request.POST)
if form.is_valid():
@@ -239,7 +239,7 @@ def rower_teams_view(request):
user__in=invitedathletes).exclude(
user=request.user
).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(
team__in=myteams).exclude(
user__in=invitedathletes).exclude(
@@ -295,7 +295,7 @@ def invitation_revoke_view(request,id):
if res:
messages.info(request,text)
successmessage = text
else:
else: # pragma: no cover
message = 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)
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
url = reverse(rower_teams_view)
@@ -321,7 +321,7 @@ def manager_member_drop_view(request,teamid,userid,
def manager_requests_view(request,code=None):
if code:
res,text = teams.process_request_code(request.user,code)
if res:
if res: # pragma: no cover
messages.info(request,text)
else:
messages.error(request,text)
@@ -335,9 +335,9 @@ def athlete_drop_coach_confirm_view(request,id):
r = getrower(request.user)
try:
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")
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")
breadcrumbs = [
@@ -362,9 +362,9 @@ def coach_drop_athlete_confirm_view(request,id):
r = getrower(request.user)
try:
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")
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")
breadcrumbs = [
@@ -389,16 +389,16 @@ def coach_drop_athlete_view(request,id):
r = getrower(request.user)
try:
rower = Rower.objects.get(id=id)
except Rower.DoesNotExist:
except Rower.DoesNotExist: # pragma: no cover
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")
res,text = teams.coach_remove_athlete(r,rower)
if res:
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')
url = reverse('rower_teams_view')
@@ -410,16 +410,16 @@ def athlete_drop_coach_view(request,id):
r = getrower(request.user)
try:
coach = Rower.objects.get(id=id)
except Rower.DoesNotExist:
except Rower.DoesNotExist: # pragma: no cover
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")
res,text = teams.coach_remove_athlete(coach,r)
if res:
messages.info(request,'Removal successful')
else:
else: # pragma: no cover
messages.error(request,'There was an error dropping the coach from your list')
url = reverse('rower_teams_view')
@@ -430,7 +430,7 @@ def athlete_drop_coach_view(request,id):
def team_requestmembership_view(request,teamid,userid):
try:
t = Team.objects.get(id=teamid)
except Team.DoesNotExist:
except Team.DoesNotExist: # pragma: no cover
raise Http404("Team doesn't exist")
r = getrequestrower(request,userid=userid)
@@ -446,7 +446,7 @@ def team_requestmembership_view(request,teamid,userid):
res,text = teams.create_request(t,userid)
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
@@ -467,9 +467,9 @@ def request_coaching_view(request,coachid):
res,text = teams.create_coaching_request(coach,request.user)
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
else:
else: # pragma: no cover
messages.error(request,'That person is not a coach')
url = reverse('rower_teams_view')
@@ -480,7 +480,7 @@ def request_coaching_view(request,coachid):
def offer_coaching_view(request,userid):
try:
u = User.objects.get(id=userid)
except User.DoesNotExist:
except User.DoesNotExist: # pragma: no cover
raise Http404("This user doesn't exist")
coach = getrequestrower(request)
@@ -489,7 +489,7 @@ def offer_coaching_view(request,userid):
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
url = reverse('rower_teams_view')
@@ -502,7 +502,7 @@ def reject_revoke_coach_request(request,id=0):
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
url = reverse('rower_teams_view')
@@ -515,7 +515,7 @@ def reject_revoke_coach_offer(request,id=0):
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
url = reverse('rower_teams_view')
@@ -529,7 +529,7 @@ def request_revoke_view(request,id=0):
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
url = reverse(rower_teams_view)
@@ -542,7 +542,7 @@ def request_reject_view(request,id=0):
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
url = reverse(rower_teams_view)
@@ -555,7 +555,7 @@ def invitation_reject_view(request,id=0):
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
url = reverse(rower_teams_view)
@@ -568,7 +568,7 @@ def rower_invitations_view(request,code=None,message='',successmessage=''):
if code:
teams.remove_expired_invites()
res,text = teams.process_invite_code(request.user,code)
if res:
if res: # pragma: no cover
messages.info(request,text)
teamid=res
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)
if request.method == 'POST':
if request.method == 'POST': # pragma: no cover
teamcreateform = TeamForm(request.POST,instance=t)
if teamcreateform.is_valid():
cd = teamcreateform.cleaned_data
@@ -666,7 +666,7 @@ def team_create_view(request):
res,message=teams.create_team(name,manager,private,notes,
viewing)
if not res:
if not res: # pragma: no cover
messages.error(request,message)
url = reverse('paidplans_view')
return HttpResponseRedirect(url)
@@ -792,7 +792,7 @@ def rower_accept_coachoffer_view(request,code=None):
res, text = teams.process_coachoffer_code(request.user,code)
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
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)
if res:
messages.info(request,text)
else:
else: # pragma: no cover
messages.error(request,text)
url = reverse('rower_teams_view')

View File

@@ -16,7 +16,7 @@ def deactivate_user(request):
if user_form.is_valid():
if not user_form.cleaned_data['is_active']:
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:
subscriptions = braintreestuff.find_subscriptions(r)
for subscription in subscriptions:
@@ -44,7 +44,7 @@ def deactivate_user(request):
return render(request, "userprofile_deactivate.html", {
"user_form": user_form,
})
else:
else: # pragma: no cover
raise PermissionDenied
@login_required()
@@ -54,7 +54,7 @@ def user_gdpr_optin(request):
r.gdproptindate = None
r.save()
nexturl = request.GET.get('next','/rowers/list-workouts/')
if r.gdproptin:
if r.gdproptin: # pragma: no cover
return HttpResponseRedirect(nexturl)
return render(request,'gdpr_optin.html',{
@@ -88,7 +88,7 @@ def remove_user(request):
email = user.email
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:
subscriptions = braintreestuff.find_subscriptions(r)
for subscription in subscriptions:
@@ -115,12 +115,12 @@ def remove_user(request):
return render(request, "userprofile_delete.html", {
"user_form": user_form,
})
else:
else: # pragma: no cover
raise PermissionDenied
@login_required()
def survey(request):
def survey(request): # pragma: no cover
r = getrower(request.user)
@@ -148,7 +148,7 @@ def survey(request):
def start_trial_view(request):
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')
url = '/rowers/paidplans'
return HttpResponseRedirect(url)
@@ -182,7 +182,7 @@ def start_trial_view(request):
def start_plantrial_view(request):
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')
url = '/rowers/paidplans'
return HttpResponseRedirect(url)
@@ -239,7 +239,7 @@ def rower_favoritecharts_view(request,userid=0):
if aantal==0:
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)
if staticchartform.is_valid():
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.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)
if datasettingsform.is_valid():
cd = datasettingsform.cleaned_data
@@ -262,7 +262,7 @@ def rower_favoritecharts_view(request,userid=0):
r.save()
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()
defaultautojoin = Rower._meta.get_field('autojoin').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)
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)
if favorites_formset.is_valid():
new_instances = []
@@ -344,7 +344,7 @@ def rower_exportsettings_view(request,userid=0):
form = RowerExportForm(request.POST)
if form.is_valid():
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>.')
for attr, value in cd.items():
@@ -355,7 +355,7 @@ def rower_exportsettings_view(request,userid=0):
doset = False
except KeyError:
doset = True
if r.rowerplan == 'basic':
if r.rowerplan == 'basic': # pragma: no cover
doset = False
if not doset:
before = getattr(r,attr)
@@ -426,7 +426,7 @@ def rower_edit_view(request,rowerid=0,userid=0,message=""):
sex = cd['sex']
try:
offercoaching = cd['offercoaching']
except KeyError:
except KeyError: # pragma: no cover
offercoaching = False
autojoin = cd['autojoin']
adaptiveclass = cd['adaptiveclass']
@@ -440,7 +440,7 @@ def rower_edit_view(request,rowerid=0,userid=0,message=""):
fav_analysis = cd['fav_analysis']
usersmooth = cd['usersmooth']
u = r.user
if u.email != email and len(email):
if u.email != email and len(email): # pragma: no cover
resetbounce = True
else:
resetbounce = False
@@ -470,7 +470,7 @@ def rower_edit_view(request,rowerid=0,userid=0,message=""):
r.usersmooth = usersmooth
if resetbounce and r.emailbounced:
if resetbounce and r.emailbounced: # pragma: no cover
r.emailbounced = False
r.save()
@@ -607,7 +607,7 @@ def rower_prefs_view(request,userid=0,message=""):
r.save()
successmessage = "Your Power Zone data were changed"
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)
if cpform.is_valid():
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
# the button is only there when you have granted access to an app
@login_required()
def rower_revokeapp_view(request,id=0):
def rower_revokeapp_view(request,id=0): # pragma: no cover
try:
tokens = 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,
startdate=timezone.now()-datetime.timedelta(days=365),
enddate=timezone.now()
):
): # pragma: no cover
try:
r = getrower(request.user)
except Rower.DoesNotExist: