예제 #1
0
    def testAutomaticRewardActiveTransportation(self):
        #Create test data -- code copied from TestTimeGrouping
        key = (2016, 5, 3)
        test_section_list = []
        #
        # Since PST is UTC-7, all of these will be in the same UTC day
        # 13:00, 17:00, 21:00
        # so we expect the local date and UTC bins to be the same
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 6, tzinfo=tz.gettz(PST)), PST))
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 10, tzinfo=tz.gettz(PST)), PST))
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 14, tzinfo=tz.gettz(PST)), PST))

        self._fillModeDistanceDuration(test_section_list)
        #logging.debug("durations = %s" % [s.data.duration for s in test_section_list])

        summary_ts = earmt.group_by_timestamp(
            self.testUUID,
            arrow.Arrow(2016, 5, 1).timestamp,
            arrow.Arrow(2016, 6, 1).timestamp, None, earmts.get_distance)
        logging.debug(
            "in testAutomaticRewardActiveTransportation, result = %s" %
            summary_ts)

        #Get user data before scoring
        user_before = list(edb.get_habitica_db().find(
            {'user_id': self.testUUID}))[0]['metrics_data']
        self.assertEqual(int(user_before['bike_count']), 0)
        habits_before = proxy.habiticaProxy(self.testUUID, 'GET',
                                            "/api/v3/tasks/user?type=habits",
                                            None).json()
        bike_pts_before = [
            habit['history'] for habit in habits_before['data']
            if habit['text'] == "Bike"
        ]
        #Score points
        autocheck.reward_active_transportation(self.testUUID)
        #Get user data after scoring and check results
        user_after = list(edb.get_habitica_db().find(
            {'user_id': self.testUUID}))[0]['metrics_data']
        self.assertEqual(int(user_after['bike_count']), 1500)
        habits_after = proxy.habiticaProxy(self.testUUID, 'GET',
                                           "/api/v3/tasks/user?type=habits",
                                           None).json()
        bike_pts_after = [
            habit['history'] for habit in habits_after['data']
            if habit['text'] == "Bike"
        ]
        self.assertTrue(len(bike_pts_after[0]) - len(bike_pts_before[0]) == 2)
예제 #2
0
    def testGroupedByOneLocalDayMultiUTCDay(self):
        key = (2016, 5, 3)
        test_section_list = []

        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,6, tzinfo=tz.gettz(PST)),
                                    PST))
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,10, tzinfo=tz.gettz(PST)),
                                    PST))
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,23, tzinfo=tz.gettz(PST)),
                                    PST))

        self._fillModeDistanceDuration(test_section_list)
        logging.debug("durations = %s" %
                      [s.data.duration for s in test_section_list])

        # There's only one local date, so it will be consistent with
        # results in testGroupedByOneLocalDayOneUTCDay
        summary_ld_dict = earmt.group_by_local_date(self.testUUID,
                                               ecwl.LocalDate({'year': 2016, 'month': 5}),
                                               ecwl.LocalDate({'year': 2016, 'month': 6}),
                                               earmt.LocalFreq.DAILY, [earmts.get_count])

        summary_ld = summary_ld_dict["result"][0]
        summary_ld_last = summary_ld_dict["last_ts_processed"]
        self.assertEqual(summary_ld_last,
                         arrow.Arrow(2016,5,3,23, tzinfo=tz.gettz(PST)).timestamp)
        self.assertEqual(len(summary_ld), 1) # spans one day
        self.assertEqual(summary_ld[0].BICYCLING, 3)
        self.assertEqual(summary_ld[0].ts, 1462258800)
        self.assertEqual(summary_ld[0].local_dt.day, 3)

        summary_ts_dict = earmt.group_by_timestamp(self.testUUID,
                                           arrow.Arrow(2016,5,1).timestamp,
                                           arrow.Arrow(2016,6,1).timestamp,
                                           'd', [earmts.get_count])
        summary_ts = summary_ts_dict["result"][0]
        summary_ts_last = summary_ts_dict["last_ts_processed"]

        # But 23:00 PDT is 6am on the 4th in UTC,
        # so the results are different for this
        self.assertEqual(summary_ts_last,
                         arrow.Arrow(2016,5,3,23, tzinfo=tz.gettz(PST)).timestamp)
        self.assertEqual(len(summary_ts), 2) # spans two days in UTC
        self.assertEqual(summary_ts[0].BICYCLING, 2) # 2 trips on the first day
        self.assertEqual(summary_ts[1].BICYCLING, 1) # 1 trips on the second day
        self.assertEqual(summary_ts[0].local_dt.day, 3) # because it is the second in UTC
        self.assertEqual(summary_ts[1].local_dt.day, 4) # because it is the second in UTC
        self.assertEqual(summary_ts[0].ts, 1462233600) # timestamp for midnight 3nd May
        self.assertEqual(summary_ts[1].ts, 1462320000) # timestamp for midnight 4rd May
예제 #3
0
    def testGroupedByOneLocalDayMultiUTCDay(self):
        key = (2016, 5, 3)
        test_section_list = []

        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,6, tzinfo=tz.gettz(PST)),
                                    PST))
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,10, tzinfo=tz.gettz(PST)),
                                    PST))
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,23, tzinfo=tz.gettz(PST)),
                                    PST))

        self._fillModeDistanceDuration(test_section_list)
        logging.debug("durations = %s" %
                      [s.data.duration for s in test_section_list])

        # There's only one local date, so it will be consistent with
        # results in testGroupedByOneLocalDayOneUTCDay
        summary_ld_dict = earmt.group_by_local_date(self.testUUID,
                                               ecwl.LocalDate({'year': 2016, 'month': 5}),
                                               ecwl.LocalDate({'year': 2016, 'month': 6}),
                                               earmt.LocalFreq.DAILY, [earmts.get_count])

        summary_ld = summary_ld_dict["result"][0]
        summary_ld_last = summary_ld_dict["last_ts_processed"]
        self.assertEqual(summary_ld_last,
                         arrow.Arrow(2016,5,3,23, tzinfo=tz.gettz(PST)).timestamp)
        self.assertEqual(len(summary_ld), 1) # spans one day
        self.assertEqual(summary_ld[0].BICYCLING, 3)
        self.assertEqual(summary_ld[0].ts, 1462258800)
        self.assertEqual(summary_ld[0].local_dt.day, 3)

        summary_ts_dict = earmt.group_by_timestamp(self.testUUID,
                                           arrow.Arrow(2016,5,1).timestamp,
                                           arrow.Arrow(2016,6,1).timestamp,
                                           'd', [earmts.get_count])
        summary_ts = summary_ts_dict["result"][0]
        summary_ts_last = summary_ts_dict["last_ts_processed"]

        # But 23:00 PDT is 6am on the 4th in UTC,
        # so the results are different for this
        self.assertEqual(summary_ts_last,
                         arrow.Arrow(2016,5,3,23, tzinfo=tz.gettz(PST)).timestamp)
        self.assertEqual(len(summary_ts), 2) # spans two days in UTC
        self.assertEqual(summary_ts[0].BICYCLING, 2) # 2 trips on the first day
        self.assertEqual(summary_ts[1].BICYCLING, 1) # 1 trips on the second day
        self.assertEqual(summary_ts[0].local_dt.day, 3) # because it is the second in UTC
        self.assertEqual(summary_ts[1].local_dt.day, 4) # because it is the second in UTC
        self.assertEqual(summary_ts[0].ts, 1462233600) # timestamp for midnight 3nd May
        self.assertEqual(summary_ts[1].ts, 1462320000) # timestamp for midnight 4rd May
예제 #4
0
    def testGroupedByOneLocalDayOneUTCDay(self):
        key = (2016, 5, 3)
        test_section_list = []
        #
        # Since PST is UTC-7, all of these will be in the same UTC day
        # 13:00, 17:00, 21:00
        # so we expect the local date and UTC bins to be the same
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,6, tzinfo=tz.gettz(PST)),
                                    PST))
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,10, tzinfo=tz.gettz(PST)),
                                    PST))
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,14, tzinfo=tz.gettz(PST)),
                                    PST))

        self._fillModeDistanceDuration(test_section_list)
        logging.debug("durations = %s" %
                      [s.data.duration for s in test_section_list])

        summary_ts_dict = earmt.group_by_timestamp(self.testUUID,
                                           arrow.Arrow(2016,5,1).timestamp,
                                           arrow.Arrow(2016,6,1).timestamp,
                                           'd', [earmts.get_count])
        summary_ld_dict = earmt.group_by_local_date(self.testUUID,
                                               ecwl.LocalDate({'year': 2016, 'month': 5}),
                                               ecwl.LocalDate({'year': 2016, 'month': 6}),
                                               earmt.LocalFreq.DAILY, [earmts.get_count])

        summary_ts_last = summary_ts_dict["last_ts_processed"]
        summary_ld_last = summary_ld_dict["last_ts_processed"]

        summary_ts = summary_ts_dict["result"][0]
        summary_ld = summary_ld_dict["result"][0]

        self.assertEqual(summary_ts_last, arrow.Arrow(2016,5,3,14, tzinfo=tz.gettz(PST)).timestamp)
        self.assertEqual(summary_ld_last, arrow.Arrow(2016,5,3,14, tzinfo=tz.gettz(PST)).timestamp)

        self.assertEqual(len(summary_ts), len(summary_ld)) # local date and UTC results are the same
        self.assertEqual(len(summary_ts), 1) # spans one day
        self.assertEqual(summary_ts[0].BICYCLING, summary_ld[0].BICYCLING)
        self.assertEqual(summary_ts[0].BICYCLING, 3)
        # Note that the timestamps are not guaranteed to be equal since
        # the UTC range starts at midnight UTC while the local time range
        # starts at midnight PDT
        # self.assertEqual(summary_ts[0].ts, summary_ld[0].ts)
        self.assertEqual(summary_ts[0].ts, 1462233600)
        self.assertEqual(summary_ld[0].ts, 1462258800)
        self.assertEqual(summary_ts[0].local_dt.day, 3)
        self.assertEqual(summary_ts[0].local_dt.day, summary_ld[0].local_dt.day)
예제 #5
0
    def testGroupedByOneLocalDayOneUTCDay(self):
        key = (2016, 5, 3)
        test_section_list = []
        #
        # Since PST is UTC-7, all of these will be in the same UTC day
        # 13:00, 17:00, 21:00
        # so we expect the local date and UTC bins to be the same
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,6, tzinfo=tz.gettz(PST)),
                                    PST))
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,10, tzinfo=tz.gettz(PST)),
                                    PST))
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,14, tzinfo=tz.gettz(PST)),
                                    PST))

        self._fillModeDistanceDuration(test_section_list)
        logging.debug("durations = %s" %
                      [s.data.duration for s in test_section_list])

        summary_ts_dict = earmt.group_by_timestamp(self.testUUID,
                                           arrow.Arrow(2016,5,1).timestamp,
                                           arrow.Arrow(2016,6,1).timestamp,
                                           'd', [earmts.get_count])
        summary_ld_dict = earmt.group_by_local_date(self.testUUID,
                                               ecwl.LocalDate({'year': 2016, 'month': 5}),
                                               ecwl.LocalDate({'year': 2016, 'month': 6}),
                                               earmt.LocalFreq.DAILY, [earmts.get_count])

        summary_ts_last = summary_ts_dict["last_ts_processed"]
        summary_ld_last = summary_ld_dict["last_ts_processed"]

        summary_ts = summary_ts_dict["result"][0]
        summary_ld = summary_ld_dict["result"][0]

        self.assertEqual(summary_ts_last, arrow.Arrow(2016,5,3,14, tzinfo=tz.gettz(PST)).timestamp)
        self.assertEqual(summary_ld_last, arrow.Arrow(2016,5,3,14, tzinfo=tz.gettz(PST)).timestamp)

        self.assertEqual(len(summary_ts), len(summary_ld)) # local date and UTC results are the same
        self.assertEqual(len(summary_ts), 1) # spans one day
        self.assertEqual(summary_ts[0].BICYCLING, summary_ld[0].BICYCLING)
        self.assertEqual(summary_ts[0].BICYCLING, 3)
        # Note that the timestamps are not guaranteed to be equal since
        # the UTC range starts at midnight UTC while the local time range
        # starts at midnight PDT
        # self.assertEqual(summary_ts[0].ts, summary_ld[0].ts)
        self.assertEqual(summary_ts[0].ts, 1462233600)
        self.assertEqual(summary_ld[0].ts, 1462258800)
        self.assertEqual(summary_ts[0].local_dt.day, 3)
        self.assertEqual(summary_ts[0].local_dt.day, summary_ld[0].local_dt.day)
예제 #6
0
    def testGroupedByOneLocalDayMultiTzGoingEast(self):
        key = (2016, 5, 3)
        test_section_list = []
        # This is perhaps an extreme use case, but it is actually a fairly
        # common one with air travel

        # Step 1: user leaves SFO at 1am on the 3rd for JFK on a cross-country flight
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,1, tzinfo=tz.gettz(PST)),
                                    PST))
        # cross-country takes 8 hours, so she arrives in New York at 9:00 IST = 12:00am EDT
        # (taking into account the time difference)
        test_section_list[0]['data'] = self._fillDates(test_section_list[0].data, "end_",
                                                       arrow.Arrow(2016,5,3,9,tzinfo=tz.gettz(PST)),
                                                       EST)

        # Step 2: user leaves JFK for LHR at 1pm EST.
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,13, tzinfo=tz.gettz(EST)),
                                    EST))

        # cross-atlantic flight takes 7 hours, so she arrives at LHR at 8:00pm EDT
        # = 2am on the 4th local time
        test_section_list[1]['data'] = self._fillDates(test_section_list[1].data, "end_",
                                                       arrow.Arrow(2016,5,3,21,tzinfo=tz.gettz(EST)),
                                                       BST)

        # Then, she catches the train from the airport to her hotel in London
        # at 3am local time = 9:00pm EST
        # So as per local time, this is a new trip
        #
        # This clearly indicates why we need to use the timezone of the end of
        # last section to generate the timestamp for the range. If we use the
        # timezone of the beginning of the trip, we will say that the range ends
        # at midnight EST. But then it should include the next_day_first_trip,
        # which starts at 9pm EST, but it does not.
        # So we should use midnight BST instead. Note that midnight BST was
        # actually during the trip, but then it is no different from a regular
        # trip (in one timezone) where the trip spans the date change
        next_day_first_trip = self._createTestSection(
            arrow.Arrow(2016,5,4,3, tzinfo=tz.gettz(BST)),
            BST)

        self._fillModeDistanceDuration(test_section_list)
        self._fillModeDistanceDuration([next_day_first_trip])

        logging.debug("durations = %s" %
                      [s.data.duration for s in test_section_list])

        summary_dict = earmt.group_by_timestamp(self.testUUID,
                                           arrow.Arrow(2016,5,1).timestamp,
                                           arrow.Arrow(2016,6,1).timestamp,
                                           'd', [earmts.get_count])
        summary_last = summary_dict["last_ts_processed"]
        summary = summary_dict["result"][0]

        logging.debug(summary)

        self.assertEqual(summary_last,
                         arrow.Arrow(2016,5,4,3, tzinfo=tz.gettz(BST)).timestamp)

        self.assertEqual(len(summary), 2) # spans two days in UTC
        self.assertEqual(summary[0].BICYCLING, 2) # trip leaving SFO and JFK
        self.assertEqual(summary[1].BICYCLING, 1) # trip in GMT
        self.assertEqual(summary[0].local_dt.day, 3) # because it is the second in UTC
        self.assertEqual(summary[1].local_dt.day, 4)
        self.assertEqual(summary[0].local_dt.hour, 0) # timestamp fills out all vals
        self.assertEqual(summary[0].ts, 1462233600) # timestamp for start of 2nd May in UTC
        self.assertEqual(summary[1].ts, 1462320000) # timestamp for start of 2nd May in UTC

        # There's only one local date, but it starts in IST this time
        summary_ld_dict = earmt.group_by_local_date(self.testUUID,
                                               ecwl.LocalDate({'year': 2016, 'month': 5}),
                                               ecwl.LocalDate({'year': 2016, 'month': 6}),
                                               earmt.LocalFreq.DAILY, [earmts.get_count])

        summary_ld_last = summary_ld_dict["last_ts_processed"]
        summary_ld = summary_ld_dict["result"][0]

        self.assertEqual(summary_ld_last,
                         arrow.Arrow(2016,5,4,3, tzinfo=tz.gettz(BST)).timestamp)
        self.assertEqual(len(summary_ld), 2) # spans one day + 1 trip on the next day
        self.assertEqual(summary_ld[0].BICYCLING, 2) # two plane trips
        self.assertEqual(summary_ld[1].BICYCLING, 1) # trip SFO
        self.assertEqual(summary_ld[0].ts, 1462258800) # start of the 3rd in IST
        self.assertEqual(summary_ld[0].local_dt.day, 3)
        self.assertEqual(summary_ld[1].ts, 1462316400) # start of the 4th in BST
        self.assertEqual(summary_ld[1].local_dt.day, 4)
예제 #7
0
    def testGroupedByOneLocalDayMultiTzGoingWest(self):
        key = (2016, 5, 3)
        test_section_list = []
        # This is perhaps an extreme use case, but it is actually a fairly
        # common one with air travel

        # Step 1: user leaves Delhi at 1am on the 3rd for JFK on the non-stop
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,1, tzinfo=tz.gettz(IST)),
                                    IST))
        # non-stop takes 15 hours, so she arrives in New York at 16:00 IST = 6:30am EDT
        # (taking into account the time difference)

        # Step 2: user leaves JFK for SFO at 7am EST on a non-stop
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,7, tzinfo=tz.gettz(EST)),
                                    EST))

        # Step 3: user starts a trip out of SFO a midnight of the 4th PST
        # (earliest possible trip)
        # for our timestamp algo to be correct, this has to be after the
        # timestamp for the range
        next_day_first_trip = self._createTestSection(
            arrow.Arrow(2016,5,4,0, tzinfo=tz.gettz(PST)),
        PST)

        self._fillModeDistanceDuration(test_section_list)
        self._fillModeDistanceDuration([next_day_first_trip])
        logging.debug("durations = %s" %
                      [s.data.duration for s in test_section_list])

        summary_ts_dict = earmt.group_by_timestamp(self.testUUID,
                                           arrow.Arrow(2016,5,1).timestamp,
                                           arrow.Arrow(2016,6,1).timestamp,
                                           'd', [earmts.get_count])

        summary_ts_last = summary_ts_dict["last_ts_processed"]
        summary_ts = summary_ts_dict["result"][0]

        logging.debug(summary_ts)

        self.assertEqual(summary_ts_last,
                         arrow.Arrow(2016,5,4,0, tzinfo=tz.gettz(PST)).timestamp) # spans two days in UTC
        self.assertEqual(len(summary_ts), 3) # spans two days in UTC
        self.assertEqual(summary_ts[0].BICYCLING, 1) # trip leaving India
        self.assertEqual(summary_ts[1].BICYCLING, 1) # trip from New York
        self.assertEqual(summary_ts[2].BICYCLING, 1) # trip in SF
        self.assertEqual(summary_ts[0].local_dt.day, 2) # because it is the second in UTC
        self.assertEqual(summary_ts[1].local_dt.day, 3)
        self.assertEqual(summary_ts[2].local_dt.day, 4)
        self.assertEqual(summary_ts[0].local_dt.hour, 0) # timestamp fills out all vals
        self.assertEqual(summary_ts[0].ts, 1462147200) # timestamp for start of 2nd May in UTC
        self.assertEqual(summary_ts[1].ts, 1462233600) # timestamp for start of 2nd May in UTC

        # There's only one local date, but it starts in IST this time
        summary_ld_dict = earmt.group_by_local_date(self.testUUID,
                                               ecwl.LocalDate({'year': 2016, 'month': 5}),
                                               ecwl.LocalDate({'year': 2016, 'month': 6}),
                                               earmt.LocalFreq.DAILY, [earmts.get_count])

        summary_ld = summary_ld_dict["result"][0]
        summary_ld_last = summary_ld_dict["last_ts_processed"]

        self.assertEqual(summary_ld_last,
                         arrow.Arrow(2016,5,4,0, tzinfo=tz.gettz(PST)).timestamp) # spans two days in UTC
        self.assertEqual(len(summary_ld), 2) # spans one day + 1 trip at midnight
        self.assertEqual(summary_ld[0].BICYCLING, 2) # two plane trips
        self.assertEqual(summary_ld[1].BICYCLING, 1) # trip SFO
        self.assertEqual(summary_ld[0].ts, 1462213800) # start of the 3rd in IST
        self.assertEqual(summary_ld[0].local_dt.day, 3)
        self.assertEqual(summary_ld[1].ts, 1462345200) # start of the 4th in IST
        self.assertEqual(summary_ld[1].local_dt.day, 4)
예제 #8
0
    def testGroupedByOneLocalDayMultiTzGoingEast(self):
        key = (2016, 5, 3)
        test_section_list = []
        # This is perhaps an extreme use case, but it is actually a fairly
        # common one with air travel

        # Step 1: user leaves SFO at 1am on the 3rd for JFK on a cross-country flight
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,1, tzinfo=tz.gettz(PST)),
                                    PST))
        # cross-country takes 8 hours, so she arrives in New York at 9:00 IST = 12:00am EDT
        # (taking into account the time difference)
        test_section_list[0]['data'] = self._fillDates(test_section_list[0].data, "end_",
                                                       arrow.Arrow(2016,5,3,9,tzinfo=tz.gettz(PST)),
                                                       EST)

        # Step 2: user leaves JFK for LHR at 1pm EST.
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,13, tzinfo=tz.gettz(EST)),
                                    EST))

        # cross-atlantic flight takes 7 hours, so she arrives at LHR at 8:00pm EDT
        # = 2am on the 4th local time
        test_section_list[1]['data'] = self._fillDates(test_section_list[1].data, "end_",
                                                       arrow.Arrow(2016,5,3,21,tzinfo=tz.gettz(EST)),
                                                       BST)

        # Then, she catches the train from the airport to her hotel in London
        # at 3am local time = 9:00pm EST
        # So as per local time, this is a new trip
        #
        # This clearly indicates why we need to use the timezone of the end of
        # last section to generate the timestamp for the range. If we use the
        # timezone of the beginning of the trip, we will say that the range ends
        # at midnight EST. But then it should include the next_day_first_trip,
        # which starts at 9pm EST, but it does not.
        # So we should use midnight BST instead. Note that midnight BST was
        # actually during the trip, but then it is no different from a regular
        # trip (in one timezone) where the trip spans the date change
        next_day_first_trip = self._createTestSection(
            arrow.Arrow(2016,5,4,3, tzinfo=tz.gettz(BST)),
            BST)

        self._fillModeDistanceDuration(test_section_list)
        self._fillModeDistanceDuration([next_day_first_trip])

        logging.debug("durations = %s" %
                      [s.data.duration for s in test_section_list])

        summary = earmt.group_by_timestamp(self.testUUID,
                                           arrow.Arrow(2016,5,1).timestamp,
                                           arrow.Arrow(2016,6,1).timestamp,
                                           'd', earmts.get_count)

        logging.debug(summary)

        self.assertEqual(len(summary), 2) # spans two days in UTC
        self.assertEqual(summary[0].BICYCLING, 2) # trip leaving SFO and JFK
        self.assertEqual(summary[1].BICYCLING, 1) # trip in GMT
        self.assertEqual(summary[0].local_dt.day, 3) # because it is the second in UTC
        self.assertEqual(summary[1].local_dt.day, 4)
        self.assertEqual(summary[0].local_dt.hour, 0) # timestamp fills out all vals
        self.assertEqual(summary[0].ts, 1462233600) # timestamp for start of 2nd May in UTC
        self.assertEqual(summary[1].ts, 1462320000) # timestamp for start of 2nd May in UTC

        # There's only one local date, but it starts in IST this time
        summary_ld = earmt.group_by_local_date(self.testUUID,
                                               ecwl.LocalDate({'year': 2016, 'month': 5}),
                                               ecwl.LocalDate({'year': 2016, 'month': 6}),
                                               earmt.LocalFreq.DAILY, earmts.get_count)

        self.assertEqual(len(summary_ld), 2) # spans one day + 1 trip on the next day
        self.assertEqual(summary_ld[0].BICYCLING, 2) # two plane trips
        self.assertEqual(summary_ld[1].BICYCLING, 1) # trip SFO
        self.assertEqual(summary_ld[0].ts, 1462258800) # start of the 3rd in IST
        self.assertEqual(summary_ld[0].local_dt.day, 3)
        self.assertEqual(summary_ld[1].ts, 1462316400) # start of the 4th in BST
        self.assertEqual(summary_ld[1].local_dt.day, 4)
예제 #9
0
    def testGroupedByOneLocalDayMultiTzGoingWest(self):
        key = (2016, 5, 3)
        test_section_list = []
        # This is perhaps an extreme use case, but it is actually a fairly
        # common one with air travel

        # Step 1: user leaves Delhi at 1am on the 3rd for JFK on the non-stop
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,1, tzinfo=tz.gettz(IST)),
                                    IST))
        # non-stop takes 15 hours, so she arrives in New York at 16:00 IST = 6:30am EDT
        # (taking into account the time difference)

        # Step 2: user leaves JFK for SFO at 7am EST on a non-stop
        test_section_list.append(
            self._createTestSection(arrow.Arrow(2016,5,3,7, tzinfo=tz.gettz(EST)),
                                    EST))

        # Step 3: user starts a trip out of SFO a midnight of the 4th PST
        # (earliest possible trip)
        # for our timestamp algo to be correct, this has to be after the
        # timestamp for the range
        next_day_first_trip = self._createTestSection(
            arrow.Arrow(2016,5,4,0, tzinfo=tz.gettz(PST)),
        PST)

        self._fillModeDistanceDuration(test_section_list)
        self._fillModeDistanceDuration([next_day_first_trip])
        logging.debug("durations = %s" %
                      [s.data.duration for s in test_section_list])

        summary_ts = earmt.group_by_timestamp(self.testUUID,
                                           arrow.Arrow(2016,5,1).timestamp,
                                           arrow.Arrow(2016,6,1).timestamp,
                                           'd', earmts.get_count)

        logging.debug(summary_ts)

        self.assertEqual(len(summary_ts), 3) # spans two days in UTC
        self.assertEqual(summary_ts[0].BICYCLING, 1) # trip leaving India
        self.assertEqual(summary_ts[1].BICYCLING, 1) # trip from New York
        self.assertEqual(summary_ts[2].BICYCLING, 1) # trip in SF
        self.assertEqual(summary_ts[0].local_dt.day, 2) # because it is the second in UTC
        self.assertEqual(summary_ts[1].local_dt.day, 3)
        self.assertEqual(summary_ts[2].local_dt.day, 4)
        self.assertEqual(summary_ts[0].local_dt.hour, 0) # timestamp fills out all vals
        self.assertEqual(summary_ts[0].ts, 1462147200) # timestamp for start of 2nd May in UTC
        self.assertEqual(summary_ts[1].ts, 1462233600) # timestamp for start of 2nd May in UTC

        # There's only one local date, but it starts in IST this time
        summary_ld = earmt.group_by_local_date(self.testUUID,
                                               ecwl.LocalDate({'year': 2016, 'month': 5}),
                                               ecwl.LocalDate({'year': 2016, 'month': 6}),
                                               earmt.LocalFreq.DAILY, earmts.get_count)

        self.assertEqual(len(summary_ld), 2) # spans one day + 1 trip at midnight
        self.assertEqual(summary_ld[0].BICYCLING, 2) # two plane trips
        self.assertEqual(summary_ld[1].BICYCLING, 1) # trip SFO
        self.assertEqual(summary_ld[0].ts, 1462213800) # start of the 3rd in IST
        self.assertEqual(summary_ld[0].local_dt.day, 3)
        self.assertEqual(summary_ld[1].ts, 1462345200) # start of the 4th in IST
        self.assertEqual(summary_ld[1].local_dt.day, 4)
    def testAutomaticRewardActiveTransportation(self):
        # Create a task that we can retrieve later

        self.new_task_text = randomGen()
        new_habit = {
            'type':
            "habit",
            'text':
            self.new_task_text,
            'notes':
            'AUTOCHECK: {"mapper": "active_distance",'
            '"args": {"walk_scale": 1000, "bike_scale": 3000}}'
        }
        habit_id = proxy.create_habit(self.testUUID, new_habit)

        self.dummy_task = enehat.Task()
        self.dummy_task.task_id = habit_id
        logging.debug("in testAutomaticRewardActiveTransportation,"
                      "the new habit id is = %s and task is %s" %
                      (habit_id, self.dummy_task))

        #Create test data -- code copied from TestTimeGrouping
        key = (2016, 5, 3)
        test_section_list = []
        #
        # Since PST is UTC-7, all of these will be in the same UTC day
        # 13:00, 17:00, 21:00
        # so we expect the local date and UTC bins to be the same
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 6, tzinfo=tz.gettz(PST)), PST))
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 10, tzinfo=tz.gettz(PST)), PST))
        test_section_list.append(
            self._createTestSection(
                arrow.Arrow(2016, 5, 3, 14, tzinfo=tz.gettz(PST)), PST))

        self._fillModeDistanceDuration(test_section_list)
        #logging.debug("durations = %s" % [s.data.duration for s in test_section_list])

        summary_ts = earmt.group_by_timestamp(
            self.testUUID,
            arrow.Arrow(2016, 5, 1).timestamp,
            arrow.Arrow(2016, 6, 1).timestamp, None, [earmts.get_distance])
        logging.debug(
            "in testAutomaticRewardActiveTransportation, result = %s" %
            summary_ts)

        #Get user data before scoring
        user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
        self.assertIsNone(user_before)

        # Needed to work, otherwise sections from may won't show up in the query!
        modification = {
            "last_timestamp": arrow.Arrow(2016, 5, 1).timestamp,
            "bike_count": 0,
            "walk_count": 0
        }
        autocheck.save_task_state(self.testUUID, self.dummy_task, modification)

        user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
        self.assertEqual(int(user_before['bike_count']), 0)

        habits_before = proxy.habiticaProxy(self.testUUID, 'GET',
                                            "/api/v3/tasks/user?type=habits",
                                            None).json()
        bike_pts_before = [
            habit['history'] for habit in habits_before['data']
            if habit['text'] == self.new_task_text
        ]
        #Score points
        autocheck.give_points_for_all_tasks(self.testUUID)
        #Get user data after scoring and check results
        user_after = autocheck.get_task_state(self.testUUID, self.dummy_task)
        self.assertEqual(int(user_after['bike_count']), 1500)
        habits_after = proxy.habiticaProxy(self.testUUID, 'GET',
                                           "/api/v3/tasks/user?type=habits",
                                           None).json()
        bike_pts_after = [
            habit['history'] for habit in habits_after['data']
            if habit['text'] == self.new_task_text
        ]
        self.assertTrue(len(bike_pts_after[0]) - len(bike_pts_before[0]) == 2)
예제 #11
0
def give_points(user_id, task, curr_state):

    #get timestamps
    # user_val = list(edb.get_habitica_db().find({"user_id": user_id}))[0]['metrics_data']

    # Note that
    walk_scale = task["args"]["walk_scale"]
    bike_scale = task["args"]["bike_scale"]

    if curr_state is None:
        timestamp_from_db = arrow.utcnow().timestamp
        leftover_bike = 0
        leftover_walk = 0
        curr_state = {
            'last_timestamp': timestamp_from_db,
            'bike_count': leftover_bike,
            'walk_count': leftover_walk
        }
    else:
        timestamp_from_db = curr_state['last_timestamp']
        leftover_bike = curr_state["bike_count"]
        leftover_walk = curr_state["walk_count"]

    timestamp_now = arrow.utcnow().timestamp

    #Get metrics
    summary_ts = earmt.group_by_timestamp(user_id, timestamp_from_db,
                                          timestamp_now, None,
                                          [earmts.get_distance])
    logging.debug("Metrics response: %s" % summary_ts)

    if summary_ts["last_ts_processed"] == None:
        new_state = curr_state
    else:
        #get distances leftover from last timestamp
        bike_distance = leftover_bike
        walk_distance = leftover_walk

        #iterate over summary_ts and look for bike/on foot
        for item in summary_ts["result"][0]:
            try:
                bike_distance += item.BICYCLING
                logging.debug("bike_distance += %s" % item.BICYCLING)
            except AttributeError:
                logging.debug("no bike")
            try:
                walk_distance += item.ON_FOOT
                logging.debug("walk_distance += %s" % item.ON_FOOT)
            except AttributeError:
                logging.debug("no Android walk")
            try:
                walk_distance += item.WALKING
                logging.debug("walk_distance += %s" % item.WALKING)
            except AttributeError:
                logging.debug("no ios walk")
            try:
                walk_distance += item.RUNNING
                logging.debug("walk_distance += %s" % item.RUNNING)
            except AttributeError:
                logging.debug("no running")

        logging.debug("Finished with bike_distance == %s" % bike_distance)
        logging.debug("Finished with walk_distance == %s" % walk_distance)

        method_uri_active_distance = "/api/v3/tasks/" + task.task_id + "/score/up"
        #reward user by scoring + habits
        # Walk: +1 for every km
        walk_pts = int(walk_distance // walk_scale)
        for i in range(walk_pts):
            res = proxy.habiticaProxy(user_id, 'POST',
                                      method_uri_active_distance, None)
            logging.debug("Request to score walk points %s" % res)
        # Bike: +1 for every 3 km
        bike_pts = int(bike_distance // bike_scale)
        for i in range(bike_pts):
            res2 = proxy.habiticaProxy(user_id, 'POST',
                                       method_uri_active_distance, None)
            logging.debug("Request to score bike points %s" % res2)

        #update the timestamp and bike/walk counts in db
        new_state = {
            'last_timestamp':
            summary_ts["last_ts_processed"] + esp.END_FUZZ_AVOID_LTE,
            'bike_count': bike_distance % bike_scale,
            'walk_count': walk_distance % walk_scale
        }

    logging.debug("Returning %s" % new_state)
    return new_state
  def testAutomaticRewardActiveTransportation(self):
    # Create a task that we can retrieve later

    self.new_task_text = randomGen()
    new_habit = {'type': "habit", 'text': self.new_task_text,
                 'notes': 'AUTOCHECK: {"mapper": "active_distance",'
                          '"args": {"walk_scale": 1000, "bike_scale": 3000}}'}
    habit_id = proxy.create_habit(self.testUUID, new_habit)

    self.dummy_task = enehat.Task()
    self.dummy_task.task_id = habit_id
    logging.debug("in testAutomaticRewardActiveTransportation,"
        "the new habit id is = %s and task is %s" % (habit_id, self.dummy_task))

    #Create test data -- code copied from TestTimeGrouping
    key = (2016, 5, 3)
    test_section_list = []
    #
    # Since PST is UTC-7, all of these will be in the same UTC day
    # 13:00, 17:00, 21:00
    # so we expect the local date and UTC bins to be the same
    test_section_list.append(
        self._createTestSection(arrow.Arrow(2016,5,3,6, tzinfo=tz.gettz(PST)),
                                PST))
    test_section_list.append(
        self._createTestSection(arrow.Arrow(2016,5,3,10, tzinfo=tz.gettz(PST)),
                                PST))
    test_section_list.append(
        self._createTestSection(arrow.Arrow(2016,5,3,14, tzinfo=tz.gettz(PST)),
                                PST))

    self._fillModeDistanceDuration(test_section_list)
    #logging.debug("durations = %s" % [s.data.duration for s in test_section_list])

    summary_ts = earmt.group_by_timestamp(self.testUUID,
                                       arrow.Arrow(2016,5,1).timestamp,
                                       arrow.Arrow(2016,6,1).timestamp,
                                       None, [earmts.get_distance])
    logging.debug("in testAutomaticRewardActiveTransportation, result = %s" % summary_ts)
    
    #Get user data before scoring
    user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
    self.assertIsNone(user_before)

    # Needed to work, otherwise sections from may won't show up in the query!
    modification = {"last_timestamp": arrow.Arrow(2016,5,1).timestamp, "bike_count": 0, "walk_count":0}
    autocheck.save_task_state(self.testUUID, self.dummy_task, modification)

    user_before = autocheck.get_task_state(self.testUUID, self.dummy_task)
    self.assertEqual(int(user_before['bike_count']), 0)

    habits_before = proxy.habiticaProxy(self.testUUID, 'GET', "/api/v3/tasks/user?type=habits", None).json()
    bike_pts_before = [habit['history'] for habit in habits_before['data'] if habit['text'] == self.new_task_text]
    #Score points
    autocheck.give_points_for_all_tasks(self.testUUID)
    #Get user data after scoring and check results
    user_after = autocheck.get_task_state(self.testUUID, self.dummy_task)
    self.assertEqual(int(user_after['bike_count']),1500)
    habits_after = proxy.habiticaProxy(self.testUUID, 'GET', "/api/v3/tasks/user?type=habits", None).json()
    bike_pts_after = [habit['history'] for habit in habits_after['data'] if habit['text'] == self.new_task_text]
    self.assertTrue(len(bike_pts_after[0]) - len(bike_pts_before[0]) == 2)
예제 #13
0
def give_points(user_id, task, curr_state):

    #get timestamps
    # user_val = list(edb.get_habitica_db().find({"user_id": user_id}))[0]['metrics_data']

    # Note that
    walk_scale = task["args"]["walk_scale"]
    bike_scale = task["args"]["bike_scale"]

    if curr_state is None:
        timestamp_from_db = arrow.utcnow().timestamp
        leftover_bike = 0
        leftover_walk = 0
        curr_state = {'last_timestamp': timestamp_from_db,
                     'bike_count': leftover_bike,
                     'walk_count': leftover_walk}
    else:
        timestamp_from_db = curr_state['last_timestamp']
        leftover_bike = curr_state["bike_count"]
        leftover_walk = curr_state["walk_count"]

    timestamp_now = arrow.utcnow().timestamp
    
    #Get metrics
    summary_ts = earmt.group_by_timestamp(user_id, timestamp_from_db, timestamp_now,
                                          None, [earmts.get_distance])
    logging.debug("Metrics response: %s" % summary_ts)
    
    if summary_ts["last_ts_processed"] == None:
      new_state = curr_state
    else:
      #get distances leftover from last timestamp
      bike_distance = leftover_bike
      walk_distance = leftover_walk

      #iterate over summary_ts and look for bike/on foot
      for item in summary_ts["result"][0]:
        try:
            bike_distance += item.BICYCLING
            logging.debug("bike_distance += %s" % item.BICYCLING)
        except AttributeError:
            logging.debug("no bike")
        try:
            walk_distance += item.ON_FOOT
            logging.debug("walk_distance += %s" % item.ON_FOOT)
        except AttributeError:
            logging.debug("no Android walk")
        try:
            walk_distance += item.WALKING
            logging.debug("walk_distance += %s" % item.WALKING)
        except AttributeError:
            logging.debug("no ios walk")
        try:
            walk_distance += item.RUNNING
            logging.debug("walk_distance += %s" % item.RUNNING)
        except AttributeError:
            logging.debug("no running")
      
      logging.debug("Finished with bike_distance == %s" % bike_distance)
      logging.debug("Finished with walk_distance == %s" % walk_distance)

      method_uri_active_distance = "/api/v3/tasks/"+ task.task_id + "/score/up"
      #reward user by scoring + habits
      # Walk: +1 for every km
      walk_pts = int(walk_distance//walk_scale)
      for i in range(walk_pts):
        res = proxy.habiticaProxy(user_id, 'POST', method_uri_active_distance, None)
        logging.debug("Request to score walk points %s" % res)
      # Bike: +1 for every 3 km
      bike_pts = int(bike_distance//bike_scale)
      for i in range(bike_pts):
        res2 = proxy.habiticaProxy(user_id, 'POST', method_uri_active_distance, None)
        logging.debug("Request to score bike points %s" % res2)

      #update the timestamp and bike/walk counts in db
      new_state = {'last_timestamp': summary_ts["last_ts_processed"] + esp.END_FUZZ_AVOID_LTE,
              'bike_count': bike_distance%bike_scale,
              'walk_count': walk_distance%walk_scale}

    logging.debug("Returning %s" % new_state)
    return new_state
예제 #14
0
def reward_active_transportation(user_id):
    logging.debug("Entering habitica autocheck for user %s" % user_id)
    if edb.get_habitica_db().find({'user_id': user_id}).count() == 1:
        logging.debug("Habitica user: %s" %
                      list(edb.get_habitica_db().find({'user_id': user_id})))
        #make sure habits exist
        #bike
        bike_habit = {
            'type': "habit",
            'text': "Bike",
            'up': True,
            'down': False,
            'priority': 2
        }
        bike_habit_id = proxy.create_habit(user_id, bike_habit)
        #walk
        walk_habit = {
            'type': "habit",
            'text': "Walk",
            'up': True,
            'down': False,
            'priority': 2
        }
        walk_habit_id = proxy.create_habit(user_id, walk_habit)

        #get timestamps
        user_val = list(edb.get_habitica_db().find({"user_id": user_id
                                                    }))[0]['metrics_data']
        timestamp_from_db = user_val['last_timestamp']
        timestamp_now = arrow.utcnow().timestamp

        #Get metrics
        summary_ts = earmt.group_by_timestamp(user_id, timestamp_from_db,
                                              timestamp_now, None,
                                              earmts.get_distance)
        logging.debug("Metrics response: %s" % summary_ts)

        #get distances leftover from last timestamp
        bike_distance = user_val['bike_count']
        walk_distance = user_val['walk_count']

        #iterate over summary_ts and look for bike/on foot
        for item in summary_ts:
            try:
                bike_distance += item.BICYCLING
                logging.debug("bike_distance += %s" % item.BICYCLING)
            except AttributeError:
                logging.debug("no bike")
            try:
                walk_distance += item.ON_FOOT
                logging.debug("walk_distance += %s" % item.ON_FOOT)
            except AttributeError:
                logging.debug("no Android walk")
            try:
                walk_distance += item.WALKING
                logging.debug("walk_distance += %s" % item.WALKING)
            except AttributeError:
                logging.debug("no ios walk")
            try:
                walk_distance += item.RUNNING
                logging.debug("walk_distance += %s" % item.RUNNING)
            except AttributeError:
                logging.debug("no running")

        logging.debug("Finished with bike_distance == %s" % bike_distance)
        logging.debug("Finished with walk_distance == %s" % walk_distance)

        method_uri_walk = "/api/v3/tasks/" + walk_habit_id + "/score/up"
        method_uri_bike = "/api/v3/tasks/" + bike_habit_id + "/score/up"
        #reward user by scoring + habits
        # Walk: +1 for every km
        walk_pts = int(walk_distance // 1000)
        for i in range(walk_pts):
            res = proxy.habiticaProxy(user_id, 'POST', method_uri_walk, None)
            logging.debug("Request to score walk points %s" % res)
        # Bike: +1 for every 3 km
        bike_pts = int(bike_distance // 3000)
        for i in range(bike_pts):
            res2 = proxy.habiticaProxy(user_id, 'POST', method_uri_bike, None)
            logging.debug("Request to score bike points %s" % res2)

        #update the timestamp and bike/walk counts in db
        edb.get_habitica_db().update({"user_id": user_id}, {
            "$set": {
                'metrics_data': {
                    'last_timestamp': arrow.utcnow().timestamp,
                    'bike_count': bike_distance % 3000,
                    'walk_count': walk_distance % 1000
                }
            }
        },
                                     upsert=True)
        logging.debug("Habitica user after update: %s" %
                      list(edb.get_habitica_db().find({'user_id': user_id})))