Esempio n. 1
0
 def testRounding(self):
     self.assertEqual("5 minutes",
                      display_timedelta(timedelta(minutes=5, seconds=0.2)))
     self.assertEqual("right now",
                      display_timedelta(timedelta(seconds=0.2)))
     self.assertEqual("right now",
                      display_timedelta(timedelta(seconds=0.99999)))
Esempio n. 2
0
 def testAllFour(self):
     self.assertEqual(
         "4 days, 3 hours, 5 minutes, and 2 seconds",
         display_timedelta(timedelta(days=4, hours=3, minutes=5,
                                     seconds=2)))
     self.assertEqual(
         "1 day, 3 hours, 5 minutes, and 2 seconds",
         display_timedelta(timedelta(days=1, hours=3, minutes=5,
                                     seconds=2)))
     self.assertEqual(
         "1 day, 1 hour, 1 minute, and 1 second",
         display_timedelta(timedelta(days=1, hours=1, minutes=1,
                                     seconds=1)))
Esempio n. 3
0
 def test1Missing(self):
     self.assertEqual(
         "1 hour, 1 minute, and 1 second",
         display_timedelta(timedelta(hours=1, minutes=1, seconds=1)))
     self.assertEqual(
         "1 day, 1 minute, and 1 second",
         display_timedelta(timedelta(days=1, minutes=1, seconds=1)))
     self.assertEqual(
         "1 day, 1 hour, and 1 second",
         display_timedelta(timedelta(days=1, hours=1, seconds=1)))
     self.assertEqual(
         "1 day, 1 hour, and 1 minute",
         display_timedelta(timedelta(days=1, hours=1, minutes=1)))
Esempio n. 4
0
    def send_all_messages(self, access_token, message_list, current=False):
        if not self.args.insecure:
            ssl = network.check_ssl()
        else:
            ssl = None

        if current and self.args.revise:
            action = "Revise"
        elif current and self.args.submit:
            action = "Submit"
        else:
            action = "Backup"

        num_messages = len(message_list)
        send_all = self.args.submit or self.args.backup
        retries = self.RETRY_LIMIT

        if send_all:
            timeout = None
            stop_time = datetime.datetime.max
            retries = self.RETRY_LIMIT * 2
        else:
            timeout = self.SHORT_TIMEOUT
            stop_time = datetime.datetime.now() + datetime.timedelta(
                seconds=timeout)
            log.info('Setting timeout to %d seconds', timeout)

        first_response = None
        error_msg = ''
        log.info("Sending {0} messages".format(num_messages))

        while retries > 0 and message_list and datetime.datetime.now(
        ) < stop_time:
            log.info('Sending messages...%d left', len(message_list))

            print('{action}... {percent}% complete'.format(
                action=action,
                percent=100 -
                round(len(message_list) * 100 / num_messages, 2)),
                  end='\r')

            # message_list is assumed to be ordered in chronological order.
            # We want to send the most recent message first, and send older
            # messages after.
            message = message_list[-1]

            try:
                response = self.send_messages(access_token, message, timeout,
                                              current)
            except requests.exceptions.Timeout as ex:
                log.warning("HTTP request timeout: %s", str(ex))
                retries -= 1
                error_msg = 'Connection timed out after {} seconds. '.format(timeout) + \
                            'Please check your network connection.'
            except (requests.exceptions.RequestException,
                    requests.exceptions.BaseHTTPError) as ex:
                log.warning('%s: %s', ex.__class__.__name__, str(ex))
                retries -= 1
                if getattr(ex, 'response', None) is None:
                    error_msg = 'Please check your network connection.'
                    continue
                try:
                    response_json = ex.response.json()
                except ValueError as ex:
                    log.warning("Invalid JSON Response", exc_info=True)
                    retries -= 1
                    error_msg = 'The server did not provide a valid response. Try again soon.'
                    continue

                log.warning('%s error message: %s', ex.__class__.__name__,
                            response_json['message'])

                if ex.response.status_code == 401:  # UNAUTHORIZED (technically authorization != authentication, but oh well)
                    raise exceptions.AuthenticationException(
                        response_json.get(
                            'message'))  # raise this for the caller
                elif ex.response.status_code == 403 and 'download_link' in response_json[
                        'data']:
                    retries = 0
                    error_msg = 'Aborting because OK may need to be updated.'
                else:
                    retries -= 1
                    error_msg = response_json['message']
            except Exception as ex:
                if ssl and isinstance(ex, ssl.CertificateError):
                    retries = 0
                    log.warning("SSL Error: %s", str(ex))
                    error_msg = 'SSL Verification Error: {}\n'.format(ex) + \
                                'Please check your network connection and SSL configuration.'
                else:
                    retries -= 1
                    log.warning(error_msg, exc_info=True)
                    error_msg = "Unknown Error: {}".format(ex)
            else:
                if not first_response:
                    first_response = response
                message_list.pop()

        if current and error_msg:
            print()  # Preserve progress bar.
            print_error('Could not', action.lower() + ':', error_msg)
        elif not message_list:
            print('{action}... 100% complete'.format(action=action))
            due_date = self.get_due_date(access_token, timeout)
            if due_date is not None and action != "Revise":
                now = datetime.datetime.now(tz=datetime.timezone.utc)
                time_to_deadline = due_date - now
                if time_to_deadline < datetime.timedelta(0):
                    print_error(
                        "{action} past deadline by".format(action=action),
                        display_timedelta(-time_to_deadline))
                elif time_to_deadline < datetime.timedelta(hours=10):
                    print_warning("Assignment is due in",
                                  display_timedelta(time_to_deadline))
            return first_response
        elif not send_all:
            # Do not display any error messages if --backup or --submit are not
            # used.
            print()
        elif not error_msg:
            # No errors occurred, but could not complete request within TIMEOUT.
            print()  # Preserve progress bar.
            print_error('Could not {} within {} seconds.'.format(
                action.lower(), timeout))
        else:
            # If not all messages could be backed up successfully.
            print()  # Preserve progress bar.
            print_error('Could not', action.lower() + ':', error_msg)
Esempio n. 5
0
 def testInPast(self):
     self.assertRaises(ValueError,
                       lambda: display_timedelta(timedelta(seconds=-2)))
Esempio n. 6
0
 def testYears(self):
     self.assertEqual("2734032 days",
                      display_timedelta(timedelta(days=2734032)))
Esempio n. 7
0
 def testRightNow(self):
     self.assertEqual("right now", display_timedelta(timedelta(seconds=0)))
Esempio n. 8
0
 def testOnlyOne(self):
     self.assertEqual("7 hours", display_timedelta(timedelta(hours=7)))
Esempio n. 9
0
 def test2Missing(self):
     self.assertEqual("7 hours and 1 second",
                      display_timedelta(timedelta(hours=7, seconds=1)))