class TimeoutTest(TestCase): def setUp(self): self.fb = Fitbit('x', 'y') self.fb_timeout = Fitbit('x', 'y', timeout=10) self.test_url = 'invalid://do.not.connect' def test_fb_without_timeout(self): with mock.patch.object(self.fb.client.session, 'request') as request: mock_response = mock.Mock() mock_response.status_code = 200 mock_response.content = b'{}' request.return_value = mock_response result = self.fb.make_request(self.test_url) request.assert_called_once() self.assertNotIn('timeout', request.call_args[1]) self.assertEqual({}, result) def test_fb_with_timeout__timing_out(self): with mock.patch.object(self.fb_timeout.client.session, 'request') as request: request.side_effect = requests.Timeout('Timed out') with self.assertRaisesRegexp(Timeout, 'Timed out'): self.fb_timeout.make_request(self.test_url) request.assert_called_once() self.assertEqual(10, request.call_args[1]['timeout']) def test_fb_with_timeout__not_timing_out(self): with mock.patch.object(self.fb_timeout.client.session, 'request') as request: mock_response = mock.Mock() mock_response.status_code = 200 mock_response.content = b'{}' request.return_value = mock_response result = self.fb_timeout.make_request(self.test_url) request.assert_called_once() self.assertEqual(10, request.call_args[1]['timeout']) self.assertEqual({}, result)
def test_auto_refresh_token_exception(self): """Test of auto_refresh with Unauthorized exception""" # 1. first call to _request causes a HTTPUnauthorized # 2. the token_refresh call is faked # 3. the second call to _request returns a valid value refresh_cb = mock.MagicMock() kwargs = copy.copy(self.client_kwargs) kwargs.update({ 'access_token': 'fake_access_token', 'refresh_token': 'fake_refresh_token', 'refresh_cb': refresh_cb, }) fb = Fitbit(**kwargs) profile_url = Fitbit.API_ENDPOINT + '/1/user/-/profile.json' with requests_mock.mock() as m: m.get(profile_url, [{ 'text': json.dumps({ "errors": [{ "errorType": "expired_token", "message": "Access token expired:" }] }), 'status_code': 401 }, { 'text': '{"user":{"aboutMe": "python-fitbit developer"}}', 'status_code': 200 }]) token = { 'access_token': 'fake_return_access_token', 'refresh_token': 'fake_return_refresh_token' } m.post(fb.client.refresh_token_url, text=json.dumps(token)) retval = fb.make_request(profile_url) self.assertEqual(m.request_history[1].path, '/oauth2/token') self.assertEqual( m.request_history[1].headers['Authorization'], _basic_auth_str( self.client_kwargs['client_id'], self.client_kwargs['client_secret'] ) ) self.assertEqual(retval['user']['aboutMe'], "python-fitbit developer") self.assertEqual("fake_return_access_token", token['access_token']) self.assertEqual("fake_return_refresh_token", token['refresh_token']) refresh_cb.assert_called_once_with(token)
def test_auto_refresh_token_exception(self): """Test of auto_refresh with Unauthorized exception""" # 1. first call to _request causes a HTTPUnauthorized # 2. the token_refresh call is faked # 3. the second call to _request returns a valid value refresh_cb = mock.MagicMock() kwargs = copy.copy(self.client_kwargs) kwargs.update({ 'access_token': 'fake_access_token', 'refresh_token': 'fake_refresh_token', 'refresh_cb': refresh_cb, }) fb = Fitbit(**kwargs) profile_url = Fitbit.API_ENDPOINT + '/1/user/-/profile.json' with requests_mock.mock() as m: m.get(profile_url, [{ 'text': json.dumps({ "errors": [{ "errorType": "expired_token", "message": "Access token expired:" }] }), 'status_code': 401 }, { 'text': '{"user":{"aboutMe": "python-fitbit developer"}}', 'status_code': 200 }]) token = { 'access_token': 'fake_return_access_token', 'refresh_token': 'fake_return_refresh_token' } m.post(fb.client.refresh_token_url, text=json.dumps(token)) retval = fb.make_request(profile_url) self.assertEqual(m.request_history[1].path, '/oauth2/token') self.assertEqual( m.request_history[1].headers['Authorization'], _basic_auth_str(self.client_kwargs['client_id'], self.client_kwargs['client_secret'])) self.assertEqual(retval['user']['aboutMe'], "python-fitbit developer") self.assertEqual("fake_return_access_token", token['access_token']) self.assertEqual("fake_return_refresh_token", token['refresh_token']) refresh_cb.assert_called_once_with(token)
def run(): client_id, client_secret = _get_client_details() access_token, refresh_token, expires_at = _get_user_details() # print(f'Running Fitbit request with details: {client_id} {client_secret}' # f' {access_token} {refresh_token} {expires_at}') auth2_client = Fitbit(client_id, client_secret, oauth2=True, access_token=access_token, refresh_token=refresh_token, expires_at=expires_at, refresh_cb=refresh_callback) fitbit_url = FITBIT_API + _get_api_call(1) json_response = auth2_client.make_request(fitbit_url) _write_results(json_response,RESULT_FILE) length = len(json_response["activities-heart-intraday"]['dataset']) heart_min_data = json_response["activities-heart-intraday"]['dataset'] HR_hour_data = {} HR_min_data = {} for i in range(0,length): if(i%60 == 0): if heart_min_data[i]["time"].split(":")[0][0] == '0': HR_min_data[heart_min_data[i]["time"].split(":")[0][1]] = [heart_min_data[i]["value"]] else: HR_min_data[heart_min_data[i]["time"].split(":")[0]] = [heart_min_data[i]["value"]] else: if heart_min_data[i]["time"].split(":")[0][0] == '0': HR_min_data[heart_min_data[i]["time"].split(":")[0][1]].append(heart_min_data[i]["value"]) else: HR_min_data[heart_min_data[i]["time"].split(":")[0]].append(heart_min_data[i]["value"]) for i,j in HR_min_data.items(): HR_hour_data[i] = int(sum(j)/len(j)) print(HR_hour_data) fitbit_url = FITBIT_API + _get_api_call(2) json_response = auth2_client.make_request(fitbit_url) _write_results(json_response,RESULT_FILE2) sleep_data = {} for i in json_response["sleep"]: sleep_data[i['dateOfSleep']]= i['minutesAsleep'] print(sleep_data) fitbit_url = FITBIT_API + _get_api_call(3) json_response = auth2_client.make_request(fitbit_url) _write_results(json_response,RESULT_FILE3) calories = {} for date in json_response["activities-log-calories"]: calories[date['dateTime']]= int(date['value']) print(calories) print(json_response) fitbit_url = FITBIT_API + _get_api_call(4) json_response = auth2_client.make_request(fitbit_url) _write_results(json_response,RESULT_FILE4) steps_date = {} weekly_steps = {} print(json_response["activities-log-steps"]) for date in json_response["activities-log-steps"]: steps_date[date['dateTime']]= int(date['value']) print(steps_date) for i in steps_date: if i != 0: date = i weekday = datetime.datetime.strptime(date, '%Y-%m-%d').weekday() weekly_steps[weekdays[weekday]] = steps_date[i] print(weekly_steps)