def test_message_to_send_parsing(self):
   '''This should only be run if database's job queue is empty.'''
   self.assertFalse(database._get_database().exists('message_to_send'))
   
   created_message = database.MessageToSend('topher200',
                                            'This is a test message, see?')
   database.push_message_to_send(created_message)
   parsed_message = database.pop_message_to_send()
   
   self.assertTrue(created_message.user == parsed_message.user)
   self.assertTrue(created_message.message == parsed_message.message)
   self.assertTrue(created_message.time == parsed_message.time)
def do_deferred_job():
  '''Attempts to run a job in the queue. Returns True if a job is found.'''
  message_to_send = database.pop_message_to_send()
  if not message_to_send:
    return False
  
  # If it's been more then 5 minutes, throw away the job
  if time() > message_to_send.time + (5 * 60):
    logging.error(
      "Timing out DM to %s. dm.time: %s, current time: %s. Message: %s" \
        % (message_to_send.user, message_to_send.time, time(),
           message_to_send.message))
    return True
      
  # Job is still valid. Run it!
  if twitter.send_dm(message_to_send.user, message_to_send.message):
    logging.info('sent DM to user: %s' % message_to_send.user)
  else:
    logging.warn('DM to user %s failed' % message_to_send.user)
    # We couldn't finish the job - push it back into the queue
    database.push_message_to_send(message_to_send)