Ejemplo n.º 1
0
class TestMisfitExceptions(unittest.TestCase):
    def setUp(self):
        self.misfit = Misfit('FAKE_ID', 'FAKE_SECRET', 'FAKE_TOKEN')

    def test_not_found(self):
        with HTTMock(not_found):
            self.assertRaises(MisfitNotFoundError, self.misfit.profile, '404')

    def test_invalid_parameters(self):
        with HTTMock(invalid_parameters):
            self.assertRaises(MisfitBadRequest, self.misfit.goal,
                              'BAD_START_DATE', 'BAD_END_DATE')

    def test_bad_gateway(self):
        with HTTMock(bad_gateway):
            self.assertRaises(MisfitBadGateway, self.misfit.profile)

    def test_unauthorized(self):
        with HTTMock(unauthorized):
            self.assertRaises(MisfitUnauthorized, self.misfit.profile)

    def test_forbidden(self):
        with HTTMock(forbidden):
            self.assertRaises(MisfitForbidden, self.misfit.profile)

    @freeze_time("2014-12-12 22:00:01")
    def test_rate_limit(self):
        with HTTMock(rate_limit):
            try:
                self.misfit.profile()
            except MisfitRateLimitError:
                headers = sys.exc_info()[1].response.headers
                self.assertEqual(headers['x-ratelimit-limit'], '150')
                self.assertEqual(headers['x-ratelimit-remaining'], '148')
                reset = arrow.get(headers['x-ratelimit-reset'])
                self.assertEqual((reset - arrow.now()).seconds, 2577)
            else:
                self.assertFail('Should have thrown MisfitRateLimitError')

    def test_unknown_error1(self):
        with HTTMock(unknown_error1):
            self.assertRaises(MisfitUnknownError, self.misfit.profile)

    def test_unknown_error2(self):
        with HTTMock(unknown_error2):
            self.assertRaises(MisfitUnknownError, self.misfit.profile)
Ejemplo n.º 2
0
class MyFitness():
    """
    This class creates a misfit object which can be used by the user
    to access his/her profile, retrieve historical data on his/her goals,
    daity activity, performance and analysis.
    Later, the class will be extended to allow the user to look at his/her
    friends' data
    """
    def __init__(self,path):
        """
        Initialize my fitness object object
        path: str, path to the directory which contains credentials file
        """
        credentials = pd.read_csv(os.path.join(path,'credentials.csv'))
        self._client_id = credentials['client_id'][0]
        self._client_secret = credentials['client_secret'][0]
        self._access_token = credentials['access_token'][0]
        self.misfit = Misfit(self._client_id, self._client_secret, self._access_token)

    def getProfile(self):
        """
        This method returns data on the user's profile
        """
        print "Fetching user's profile ... ",
        profile = self.misfit.profile().data
        print "Done!"
        return profile

    def getGoals(self,start_date = '2015-10-1', end_date = time.strftime("%Y-%m-%d")):
        """
        This method return goals between
        start_date: str, starting date
        end_date: str, end date
        dates should be given in string  format as yyyy-mm-d or format("%Y-%m-%d") 
        """
        goals = self.misfit.goal(start_date,end_date)
        goals_dict = {'date':[],'targetPoints':[],'points':[]}

        print "Fetching user's goals ... "
        for i in range(0,len(goals)):
            goal = goals[i]
            goals_dict['date'].append(str(goal.date.date()))
            goals_dict['targetPoints'].append(goal.targetPoints)
            goals_dict['points'].append(goal.points)

        print len(goals), " goals found :-)"

        return pd.DataFrame(goals_dict)

    def deviceInfo(self):
        """Use this method to get information on the user's device"""
        deviceInfo = self.misfit.device().data
        return deviceInfo

    def activityDetails(self,start_date = '2015-10-1', end_date = time.strftime("%Y-%m-%d")):
        """
        Use this method to get information on the user's sessions
        """
        sessions = self.misfit.session(start_date, end_date)
        sessionDetails = {'activityType':[], 'distance':[],'steps':[], 'startTime':[],
                          'duration':[], 'calories':[],'points':[]}
        for i in range(0,len(sessions)):
            sdata = sessions[i].data
            sessionDetails['activityType'].append(sdata['activityType'])
            sessionDetails['distance'].append(sdata['distance'])
            sessionDetails['steps'].append(sdata['steps'])
            sessionDetails['startTime'].append(sdata['startTime'])
            sessionDetails['duration'].append(sdata['duration'])
            sessionDetails['calories'].append(sdata['calories'])
            sessionDetails['points'].append(sdata['points'])
        return pd.DataFrame(sessionDetails)

    def getSummary(self, start_date = '2015-10-01', end_date = time.strftime("%Y-%m-%d")):
        """Use this method to get summary of the user's activity"""
        summary = self.misfit.summary(start_date, end_date)
        return summary

    
    def analyzePerformance(self):
        pass