From 78f9c5bf8c03062560307b8ac92502af72c3a0bc Mon Sep 17 00:00:00 2001 From: Sander Roosendaal Date: Sat, 15 Jan 2022 16:38:59 +0100 Subject: [PATCH] tests for Polar import --- rowers/polarstuff.py | 24 ++++----- rowers/tests/mocks.py | 60 ++++++++++++++++++++- rowers/tests/test_imports.py | 66 ++++++++++++++++++++++++ rowers/tests/testdata/polar_response.tcx | 1 + rowers/views/statements.py | 2 +- 5 files changed, 135 insertions(+), 18 deletions(-) create mode 100644 rowers/tests/testdata/polar_response.tcx diff --git a/rowers/polarstuff.py b/rowers/polarstuff.py index 0e0a3ad6..9c67d7f5 100644 --- a/rowers/polarstuff.py +++ b/rowers/polarstuff.py @@ -34,6 +34,12 @@ from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.urls import reverse, reverse_lazy +from rowers.utils import myqueue +import django_rq +queue = django_rq.get_queue('default') +queuelow = django_rq.get_queue('low') +queuehigh = django_rq.get_queue('high') + # Project # from .models import Profile from rowingdata import rowingdata @@ -77,7 +83,6 @@ def get_token(code): # pragma: no cover try: headers = { 'Authorization': 'Basic %s' % base64.b64encode(auth_string) } - print(headers,'aa') except TypeError: headers = { 'Authorization': 'Basic %s' % base64.b64encode( bytes(auth_string,'utf-8')).decode('utf-8') } @@ -203,27 +208,16 @@ def get_polar_workouts(user): dologging('polar.log',url) dologging('polar.log',authorizationstring) dologging('polar.log',str(response.status_code)) - dologging('polar.log',response.reason) - dologging('polar.log',response.text) if response.status_code == 201: - - uploadoptions = { - 'makeprivate':False, - } - - bodyyaml = yaml.safe_dump( - uploadoptions, - default_flow_style=False - ) - transactionid = response.json()['transaction-id'] url = baseurl+'/users/{userid}/exercise-transactions/{transactionid}'.format( transactionid = transactionid, userid = r.polaruserid ) + dologging('polar.log',url) response = requests.get(url, headers=headers) @@ -256,14 +250,14 @@ def get_polar_workouts(user): } url = settings.UPLOAD_SERVICE_URL - + dologging('polar.log',json_data) + dologging('polar.log',url) job = myqueue(queuehigh, handle_request_post, url, json_data ) - exercise_dict['filename'] = filename else: exercise_dict['filename'] = '' diff --git a/rowers/tests/mocks.py b/rowers/tests/mocks.py index 23796818..06ac59c2 100644 --- a/rowers/tests/mocks.py +++ b/rowers/tests/mocks.py @@ -757,7 +757,42 @@ def mocked_requests(*args, **kwargs): nkimpellerworkoutlist = json.load(infile) polar_json = { - 'available-user-data': [] + "transaction-id":240522162, + "resource-uri":"https://polaraccesslink.com/v3/users/40273947/exercise-transactions/240522162" + } + + polar_exercise_list = { + "exercises": [ + "https://www.polaraccesslink.com/v3/users/12/exercise-transactions/34/exercises/56", + "https://www.polaraccesslink.com/v3/users/12/exercise-transactions/34/exercises/120" + ] + } + + polar_exercise_dict = { + "id": 1937529874, + "upload-time": "2008-10-13T10:40:02Z", + "polar-user": "https://www.polaraccesslink/v3/users/1", + "transaction-id": 179879, + "device": "Polar M400", + "device-id": "1111AAAA", + "start-time": "2008-10-13T10:40:02Z", + "start-time-utc-offset": 180, + "duration": "PT2H44M", + "calories": 530, + "distance": 1600, + "heart-rate": { + "average": 129, + "maximum": 147 + }, + "training-load": 143.22, + "sport": "OTHER", + "has-route": True, + "club-id": 999, + "club-name": "Polar Club", + "detailed-sport-info": "WATERSPORTS_WATERSKI", + "fat-percentage": 60, + "carbohydrate-percentage": 38, + "protein-percentage": 2 } with open('rowers/tests/testdata/c2workoutlist.txt') as f: @@ -997,6 +1032,15 @@ def mocked_requests(*args, **kwargs): garmintester = re.compile(r'.*?garmin\.com') fakturoidtester = re.compile(r'.*?fakturoid\.cz') + polarlistregex = r'.*?polaraccesslink\.com\/.*\/(\d+)$' + polarlisttester = re.compile(polarlistregex) + + polarexerciseregex = r'.*?polaraccesslink\.com\/.*\/(\d+)\/exercises\/(\d+)$' + polarexercisetester = re.compile(polarexerciseregex) + + polartcxregex = r'.*?polaraccesslink\.com\/.*\/(\d+)\/tcx' + polartcxtester = re.compile(polartcxregex) + c2importregex = r'.*?concept2.com\/api\/users\/me\/results\/\d+' c2importtester = re.compile(c2importregex) @@ -1091,8 +1135,20 @@ def mocked_requests(*args, **kwargs): return MockResponse(json_data,200) if polartester.match(args[0]): + if polartcxtester.match(args[0]): + filename = 'rowers/tests/testdata/polar_response.tcx' + return MockContentResponse(filename,200) + elif polarexercisetester.match(args[0]): + json_data = polar_exercise_dict + return MockResponse(json_data,200) + elif polarlisttester.match(args[0]): + json_data = polar_exercise_list + return MockResponse(json_data,200) + + # getting user data json_data = polar_json - return MockResponse(json_data,200) + + return MockResponse(json_data,201) if tptester.match(args[0]): if 'token' in args[0]: diff --git a/rowers/tests/test_imports.py b/rowers/tests/test_imports.py index d46de827..7bee6d14 100644 --- a/rowers/tests/test_imports.py +++ b/rowers/tests/test_imports.py @@ -16,6 +16,7 @@ from rowers import dataprep from rowers import tasks from rowers import c2stuff from rowers import stravastuff +from rowers import polarstuff import urllib import json @@ -755,6 +756,71 @@ class NKObjects(DjangoTestCase): w = Workout.objects.get(id=1) #self.assertTrue(w.impeller) + +@override_settings(TESTING=True) +class PolarObjects(DjangoTestCase): + def setUp(self): + self.c = Client() + self.u = User.objects.create_user('john', + 'sander@ds.ds', + 'koeinsloot') + + self.u.first_name = 'John' + self.u.last_name = 'Sander' + self.u.save() + self.r = Rower.objects.create(user=self.u,gdproptin=True,surveydone=True, + gdproptindate=timezone.now() + ) + + self.r.polartoken = '12' + self.r.polarrefreshtoken = '123' + self.r.polartokenexpirydate = arrow.get(datetime.datetime.now()+datetime.timedelta(days=100)).datetime + + + self.r.save() + self.c.login(username='john',password='koeinsloot') + self.nu = datetime.datetime.now() + + filename = 'rowers/tests/testdata/testdata.csv' + + rr = rrower(hrmax=self.r.max,hrut2=self.r.ut2, + hrut1=self.r.ut1,hrat=self.r.at, + hrtr=self.r.tr,hran=self.r.an,ftp=self.r.ftp) + row = rdata(csvfile=filename,rower=rr) + totaldist = row.df['cum_dist'].max() + totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min() + totaltime = totaltime+row.df.loc[:,' ElapsedTime (sec)'].iloc[0] + + + hours = int(totaltime/3600.) + minutes = int((totaltime - 3600.*hours)/60.) + seconds = int(totaltime - 3600.*hours - 60.*minutes) + tenths = int(10*(totaltime - 3600.*hours - 60.*minutes - seconds)) + + duration = "%s:%s:%s.%s" % (hours,minutes,seconds,tenths) + + + workoutdate = row.rowdatetime.strftime('%Y-%m-%d') + workoutstarttime = row.rowdatetime.strftime('%H:%M:%S') + + self.w = Workout.objects.create( + name='testworkout',workouttype='water', + user=self.r,date=self.nu.strftime('%Y-%m-%d'), + starttime=workoutstarttime, + startdatetime=row.rowdatetime, + duration=duration,distance=totaldist, + csvfilename=filename + ) + + @patch('rowers.polarstuff.requests.post', side_effect=mocked_requests) + @patch('rowers.polarstuff.requests.get', side_effect=mocked_requests) + def test_polar_auto_import(self, mock_get, mock_post): + self.r.polar_auto_import = True + self.r.save() + + res = polarstuff.get_polar_workouts(self.r.user) + self.assertEqual(len(res),2) + #@pytest.mark.django_db @override_settings(TESTING=True) class RP3Objects(DjangoTestCase): diff --git a/rowers/tests/testdata/polar_response.tcx b/rowers/tests/testdata/polar_response.tcx new file mode 100644 index 00000000..1d70807f --- /dev/null +++ b/rowers/tests/testdata/polar_response.tcx @@ -0,0 +1 @@ +2022-01-12T20:06:17.938Z58.038.167987823486330.57967364788055420ActiveManual52.235860016.899503710.0Present0.0Present0.0Present0.0Present0.0Present0.0Present0.0Present0.0Present0.0Present0.0Present0.0Present0.0Present0.0Present0.0Present52.235917696.899470470.0Present52.235920196.899516420.0Present52.235918456.899538583.151771306991577Present52.235929896.899524734.678346157073975Present52.235931436.899527716.264686107635498Present52.235919886.899522046.530743598937988Present52.235918416.899513077.873045444488525Present52.235921716.899534728.507495880126953Present52.2359226.8995453910.031787872314453Present52.235915736.8995403710.761489868164062Present52.235912946.8995276211.539093971252441Present52.235912946.8995276212.463118553161621Present52.23591326.8995161612.463118553161621Present52.235917396.8995173213.246828079223633Present52.235907216.8995253413.719016075134277Present52.235905516.8995094914.976725578308105Present52.235907026.8995132416.075969696044922Present52.235899066.8995200816.382522583007812Present52.235891676.8995300517.383403778076172Present52.235895146.8995290518.451637268066406Present52.235885446.8995265718.84432601928711Present52.23588396.8995218519.937347412109375Present52.235888856.8995132420.302602767944336Present52.235894876.8995140221.10831069946289Present52.235896636.8995198321.7799072265625Present52.235907296.8995148522.222436904907227Present52.235914476.8995095423.456392288208008Present52.235929796.8994990524.333784103393555Present52.235936786.8995145226.18254280090332Present52.235928256.8995167627.495241165161133Present52.235928646.8995214928.457462310791016Present52.235913346.8995383628.783039093017578Present52.235916326.8995415130.8389949798584Present52.235921786.8995463431.234224319458008Present52.23592696.899553631.925573348999023Present52.235925576.8995387432.6816291809082Present52.235922176.8995350733.70756912231445Present52.235922136.8995401934.161170959472656Present52.23591966.8995333934.51085662841797Present52.235918046.8995270135.053855895996094Present52.235916866.8995199535.52294158935547Present52.235923836.8995139736.02320861816406Present52.235916036.8995147236.89948654174805Present37.76799392700195Present38.16798782348633Present0.34815367725160384Polar Flow app024600Polar Flow Mobile Viewer00ENXXX-XXXXX-XX \ No newline at end of file diff --git a/rowers/views/statements.py b/rowers/views/statements.py index 7aa031c8..98071518 100644 --- a/rowers/views/statements.py +++ b/rowers/views/statements.py @@ -260,7 +260,7 @@ from oauth2_provider.models import Application,Grant,AccessToken import django_rq queue = django_rq.get_queue('default') queuelow = django_rq.get_queue('low') -queuehigh = django_rq.get_queue('low') +queuehigh = django_rq.get_queue('high') import redis import threading