示例#1
0
class UTDriver(unittest.TestCase):
    def setUp(self):
        self.shared_session = Session()
        self.driver = Role.get('Driver')

    def test_creation_n_properties_of_driver(self):
        self.driver = Role.get('Driver')
        self.assertTrue(hasattr(self.driver, 'drivername'))
        self.assertTrue(hasattr(self.driver, 'password'))
        self.assertTrue(hasattr(self.driver, 'session'))
        self.assertEqual(self.driver.drivername, None)
        self.assertEqual(self.driver.password, None)
        self.assertEqual(self.driver.session, None)
        self.driver.drivername = 'John Doe'
        self.assertEqual(self.driver.drivername, 'John Doe')
        print(self.driver.drivername)
        print(self.driver.password)
        print(self.driver.session)

    def test_load_properties_success(self):
        self.driver.load_properties(drivername='John Smith', password='******', session=self.shared_session)
        self.assertEqual(self.driver.drivername, 'John Smith')
        self.assertEqual(self.driver.password, '888888')
        self.assertIs(self.driver.session, self.shared_session)

    def test_load_properties_fail(self):

        def _no_drivername():
            self.driver.load_properties(password='******', session=self.shared_session)

        def _no_password():
            self.driver.load_properties(drivername='John Smith', session=self.shared_session)

        def _no_session():
            self.driver.load_properties(drivername='John Smith', password='******')

        self.assertRaises(ValueError, _no_drivername)
        self.assertRaises(ValueError, _no_password)
        self.assertRaises(ValueError, _no_session)

    def test_get_login_form(self):
        self.shared_session.set_max_retry(for_url='http://haijia.bjxueche.net/', max_retries=5)
        self.driver.load_properties(drivername='John Smith', password='******', session=self.shared_session)
        login_form = self.driver._get_login_form()

        self.assertTrue('txtUserName' in login_form)
        self.assertTrue('txtPassword' in login_form)
        self.assertTrue('txtIMGCode' in login_form)
        self.assertTrue('rcode' in login_form)
        self.assertEqual(login_form['txtUserName'], 'John Smith')
        self.assertEqual(login_form['txtPassword'], '8'*6)
        self.assertEqual(login_form['txtIMGCode'], None)
        self.assertEqual(login_form['rcode'], None)
示例#2
0
 def __init__(self, **kwargs):
     super(WaitToTimeTask, self).__init__(**kwargs)
     # self.session = Role.get('Session')
     self.session = Session()
     self.cars = None
     self.max_thread_number = 10
     self.launcher = None
     self.retry_times = 20
示例#3
0
class UTDriver(unittest.TestCase):
    def setUp(self):
        self.shared_session = Session()
        self.driver = Role.get('Driver')
        self.driver.log_path = 'log_utdriver'

    def test_creation_n_properties_of_driver(self):
        self.driver = Role.get('Driver')
        self.assertTrue(hasattr(self.driver, 'drivername'))
        self.assertTrue(hasattr(self.driver, 'password'))
        self.assertTrue(hasattr(self.driver, 'session'))
        self.assertEqual(self.driver.drivername, None)
        self.assertEqual(self.driver.password, None)
        self.assertEqual(self.driver.session, None)
        self.driver.drivername = 'John Doe'
        self.assertEqual(self.driver.drivername, 'John Doe')
        print(self.driver.drivername)
        print(self.driver.password)
        print(self.driver.session)

    def test_load_properties_success(self):
        self.driver.load_properties(drivername='John Smith', password='******', session=self.shared_session)
        self.assertEqual(self.driver.drivername, 'John Smith')
        self.assertEqual(self.driver.password, '888888')
        self.assertIs(self.driver.session, self.shared_session)

    def test_load_properties_fail(self):

        def _no_drivername():
            self.driver.load_properties(password='******', session=self.shared_session)

        def _no_password():
            self.driver.load_properties(drivername='John Smith', session=self.shared_session)

        def _no_session():
            self.driver.load_properties(drivername='John Smith', password='******')

        self.assertRaises(ValueError, _no_drivername)
        self.assertRaises(ValueError, _no_password)
        self.assertRaises(ValueError, _no_session)

    def test_get_login_form(self):
        self.shared_session.set_max_retry(for_url='http://haijia.bjxueche.net/', max_retries=5)
        self.driver.load_properties(drivername='John Smith', password='******', session=self.shared_session)
        login_form = self.driver._get_login_form()

        self.assertTrue('txtUserName' in login_form)
        self.assertTrue('txtPassword' in login_form)
        self.assertTrue('txtIMGCode' in login_form)
        self.assertEqual(login_form['txtUserName'], 'John Smith')
        self.assertEqual(login_form['txtPassword'], '8'*6)
        self.assertEqual(login_form['txtIMGCode'], None)

    def test_login_again(self):
        def monkey_patch_get_login_form():
            raise TypeError('monkey_patch_get_login_form')
        setattr(self.driver, '_get_login_form', monkey_patch_get_login_form)
        self.assertRaises(LoginAgain, self.driver.login)

    def test_login_retry(self):
        self.retry_cnt = 0
        expect_retry_num = 11
        Driver.login_repeat_times = expect_retry_num

        def monkey_patch_get_net_text():
            self.retry_cnt += 1

        def monkey_patch_get_login_form():
            raise CAPTCHAError('monkey_patch_get_login_form')

        setattr(self.driver, '_get_login_form', monkey_patch_get_login_form)
        setattr(self.driver, '_get_net_text', monkey_patch_get_net_text)
        self.assertRaises(LoginFail, self.driver.login)
        self.assertEquals(expect_retry_num, self.retry_cnt)

    def test_login(self):
        self.shared_session.set_max_retry(for_url='http://haijia.bjxueche.net/', max_retries=5)
        # utdriver_login.txt should contain the following format:
        # username
        # password
        with open('Private files/utdriver_login.txt', 'r') as f:
            s_file = f.read()
            s_lst = s_file.split('\n')
        print(s_lst)
        self.driver.load_properties(drivername=s_lst[0], password=s_lst[1], session=self.shared_session)
        self.assertTrue(self.driver.login())
示例#4
0
 def setUp(self):
     self.session = Session()
     self.session.set_max_retry(for_url='http://haijia.bjxueche.net/', max_retries=10)
     self.dut = Role.get('WaitingTimer')
     self.dut.load_properties(session=self.session)
示例#5
0
class UTWaitingTimer(unittest.TestCase):
    def setUp(self):
        self.session = Session()
        self.session.set_max_retry(for_url='http://haijia.bjxueche.net/', max_retries=10)
        self.dut = Role.get('WaitingTimer')
        self.dut.load_properties(session=self.session)

    @httpretty.activate
    def test_get_server_time(self):

        httpretty.register_uri(httpretty.GET, 'http://haijia.bjxueche.net/',
                               body='Mock, Post succeed',
                               forcing_headers={'date': 'Fri, 26 Dec 2014 14:59:41 GMT'})
        loc_time = self.dut.get_server_time()
        self.assertEqual('2014-12-26 22:59:41+08:00', str(loc_time))

    @httpretty.activate
    def test_get_server_time_2(self):
        httpretty.register_uri(httpretty.GET, "http://haijia.bjxueche.net/",
                               Date='Mon, 15 Dec 2014 16:58:19 GMT')
        loc_time = self.dut.get_server_time()
        self.assertEqual(loc_time.day, 16)
        self.assertEqual(loc_time.hour, 0)
        self.assertEqual(loc_time.minute, 58)
        httpretty.register_uri(httpretty.GET, "http://haijia.bjxueche.net/",
                               Date='Mon, 15 Dec 2014 17:08:20 GMT')
        loc_time = self.dut.get_server_time()
        self.assertEqual(loc_time.day, 16)
        self.assertEqual(loc_time.hour, 1)
        self.assertEqual(loc_time.minute, 8)

    @httpretty.activate
    def test_get_server_time_with_retry(self):
        self.retry_cnt = 0

        def _retry(request, uri, headers):
            if self.retry_cnt == 9:
                print('Round:{0}, Response'.format(self.retry_cnt))
                return 200, headers, 'Mock, Connection succeed'
            else:
                print('Round:{0}, Timeout'.format(self.retry_cnt))
                self.retry_cnt += 1
                raise socket.timeout()
        httpretty.register_uri(httpretty.GET, 'http://haijia.bjxueche.net/',
                               body=_retry,
                               forcing_headers={'date': 'Fri, 26 Dec 2014 14:59:41 GMT'})

        loc_time = self.dut.get_server_time()
        self.assertEqual('2014-12-26 22:59:41+08:00', str(loc_time))
        self.assertEqual(self.retry_cnt, 9)

    def test_get_server_time_timeout_after_retry(self):
        self.dut.home_page_url = 'http://haijia.bjxueche.net:81/'
        self.session.set_max_retry(for_url='http://haijia.bjxueche.net:81/', max_retries=5)

        def _test():
            self.dut.get_server_time()
        start_time = time.time()
        self.assertRaises(ConnectionError, _test)
        delta = time.time() - start_time
        print('Return after {0} seconds because of timeout '.format(delta))
        self.assertGreaterEqual(delta, 20*5)

    def offset_n_minutes(self, current_time, func_get_offset_minute):
        self.dut.debut_hour = current_time.hour + func_get_offset_minute(current_time.minute)//60
        self.dut.debut_minute = func_get_offset_minute(current_time.minute) % 60

    def test_get_book_time_today(self):
        """
            Don't set book date, DUT set it 7 days later automatically, and gives the wake-up time as 3 minutes later
        """
        loc_time = datetime.now()
        self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e + 3)
        book_time = self.dut.get_book_time(loc_time)
        self.assertEqual(book_time.day, loc_time.day)
        self.assertEqual(book_time.hour, self.dut.debut_hour)
        self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_today_set(self):
        """
            Set book date to 7 days later , and DUT gives the wake-up time as 3 minutes later
        """
        seven_days = timedelta(days=7)
        loc_time = datetime.now()
        self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e + 3)
        self.dut.set_book_date = loc_time + seven_days
        book_time = self.dut.get_book_time(loc_time)
        self.assertEqual(book_time.day, loc_time.day)
        self.assertEqual(book_time.hour, self.dut.debut_hour)
        self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_later_equal_tomorrow_set(self):
        """
            Set book date to 8 and 9 days later , and DUT gives the wake-up time as 3 minutes later at some day
        """
        for i in range(2):
            print('Round {0}'.format(i))
            eight_days = timedelta(days=8+i)
            loc_time = datetime.now()
            self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e + 3)
            self.dut.set_book_date = loc_time + eight_days
            book_time = self.dut.get_book_time(loc_time)
            wake_up_date = loc_time + timedelta(days=1+i)
            self.assertEqual(book_time.day, wake_up_date.day)
            self.assertEqual(book_time.hour, self.dut.debut_hour)
            self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_tomorrow(self):
        """
            Don't set book date, DUT set it 8 days later automatically,
            and gives the wake-up time at tomorrow
        """
        loc_time = datetime.now()
        self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e - 3)
        book_time = self.dut.get_book_time(loc_time)
        print('Wake up at {0}'.format(str(book_time)))
        wake_up_date = loc_time + timedelta(days=1)
        self.assertEqual(book_time.day, wake_up_date.day)
        self.assertEqual(book_time.hour, self.dut.debut_hour)
        self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_tomorrow_set(self):
        """
            Set book date to 1~8 days later , and DUT gives the wake-up time as tomorrow
        """
        for i in range(8):
            _7_8_days = timedelta(days=1+i)
            loc_time = datetime.now()
            self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e - 3)
            self.dut.set_book_date = loc_time + _7_8_days
            print('Round {0}: want {1} in {2}'.format(i, str(self.dut.set_book_date), str(_7_8_days)))
            book_time = self.dut.get_book_time(loc_time)
            print('Wake up at {0}'.format(str(book_time)))
            wake_up_date = loc_time + timedelta(days=1)
            self.assertEqual(book_time.day, wake_up_date.day)
            self.assertEqual(book_time.hour, self.dut.debut_hour)
            self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_later_than_tomorrow_set(self):
        """
            Set book date to 9~11 days later , and DUT gives the wake-up time as tomorrow
        """
        for i in range(3):
            _7_8_days = timedelta(days=9+i)
            loc_time = datetime.now()
            self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e - 3)
            self.dut.set_book_date = loc_time + _7_8_days
            print('Round {0}: want {1} in {2}'.format(i, str(self.dut.set_book_date), str(_7_8_days)))
            book_time = self.dut.get_book_time(loc_time)
            print('Wake up at {0}'.format(str(book_time)))
            wake_up_date = loc_time + timedelta(days=2+i)
            self.assertEqual(book_time.day, wake_up_date.day)
            self.assertEqual(book_time.hour, self.dut.debut_hour)
            self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_sleep_span_0(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(second=(loc_time.second + 30) % 60,
                                     minute=loc_time.minute + (loc_time.second + 30) // 60)

        self.assertEqual(0, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_sleep_span_50s_tc0(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 1) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 1) // 60)

        self.assertLessEqual(self.dut.get_sleep_span(book_time, loc_time), 50)

    def test_get_sleep_span_50s_tc1(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 3) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 3) // 60)

        self.assertEqual(50, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_sleep_span_10m_tc0(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 10) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 10) // 60)

        self.assertEqual(50, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_sleep_span_10m_tc1(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 15) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 15) // 60)

        self.assertEqual(600, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_sleep_span_10m_tc2(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 11) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 11) // 60)

        self.assertEqual(50, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_book_date_auto(self):
        _7_days = timedelta(days=7)
        loc_time = datetime.now()
        book_date = self.dut.get_book_date(loc_time, loc_time)
        expt_date = loc_time + _7_days
        self.assertEqual(expt_date.year, book_date.year)
        self.assertEqual(expt_date.month, book_date.month)
        self.assertEqual(expt_date.day, book_date.day)

    def test_get_book_date_set(self):
        _9_days = timedelta(days=9)
        loc_time = datetime.now()
        self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e - 3)
        expt_date = loc_time + _9_days
        self.dut.set_book_date = expt_date
        book_date = self.dut.get_book_date(loc_time, loc_time)
        self.assertEqual(expt_date.year, book_date.year)
        self.assertEqual(expt_date.month, book_date.month)
        self.assertEqual(expt_date.day, book_date.day)

    def to_test_run_common(self, func_get_book_minute, delay=None):
        server_time = self.dut.get_server_time()
        self.offset_n_minutes(server_time, func_get_book_minute)

        if delay is not None:
            time.sleep(delay)
        self.dut.run()
        return self.dut, server_time

    def test_run_tc0(self):
        dut, server_time = self.to_test_run_common(lambda e: e + 1)
        wait_end_time = dut.get_server_time()
        self.assertTrue(wait_end_time - server_time < timedelta(seconds=50))

    def test_run_tc1(self):
        dut, server_time = self.to_test_run_common(lambda e: e + 1, delay=10)
        wait_end_time = dut.get_server_time()
        self.assertTrue(wait_end_time - server_time < timedelta(seconds=50))

    def test_run_tc2(self):
        dut, server_time = self.to_test_run_common(lambda e: e + 3)
        wait_end_time = dut.get_server_time()
        self.assertTrue(wait_end_time - server_time > timedelta(seconds=100))

    def test_run_tc3(self):
        dut, server_time = self.to_test_run_common(lambda e: e + 4)
        wait_end_time = dut.get_server_time()
        self.assertGreaterEqual(wait_end_time - server_time, timedelta(minutes=2))
示例#6
0
 def setUp(self):
     self.dut = Session()
     self.dut.log_file_name = 'UTSession'
示例#7
0
class UTSession(unittest.TestCase):
    def setUp(self):
        self.dut = Session()
        self.dut.log_file_name = 'UTSession'

    @httpretty.activate
    def _do_success(self,
                    do_func,
                    fake_body='Mock, Connection succeed',
                    func_get_expt=None):
        httpretty.register_uri(httpretty.GET,
                               'http://haijia.bjxueche.net/',
                               body=fake_body)
        httpretty.register_uri(httpretty.POST,
                               'http://haijia.bjxueche.net/',
                               body=fake_body)
        body = do_func()
        if isinstance(fake_body, str):
            self.assertEqual(body, fake_body)
        elif callable(func_get_expt):
            self.assertEqual(body, func_get_expt())
        else:
            self.assertTrue(False)

    def _do_failed(self, do_func):
        self.assertRaises(ConnectionError or ReadTimeout, do_func)

    @httpretty.activate
    def _do_with_retry(self, do_func, func_check_request=None):
        self.retry_cnt = 0

        def _retry(request, uri, headers):
            if func_check_request is not None and callable(func_check_request):
                func_check_request(request)
                print('Checking Request:{0}, Pass'.format(request.body))
            if self.retry_cnt == 5:
                print('Round:{0}, Response'.format(self.retry_cnt))
                return 200, headers, 'Mock, Connection succeed'
            else:
                print('Round:{0}, Timeout'.format(self.retry_cnt))
                self.retry_cnt += 1
                raise socket.timeout()

        httpretty.register_uri(httpretty.GET,
                               'http://haijia.bjxueche.net/',
                               body=_retry)
        httpretty.register_uri(httpretty.POST,
                               'http://haijia.bjxueche.net/',
                               body=_retry)
        self.dut.set_max_retry(for_url='http://haijia.bjxueche.net/',
                               max_retries=6)
        body = do_func()
        self.assertEqual(body, 'Mock, Connection succeed')
        self.assertEqual(self.retry_cnt, 5)

    @httpretty.activate
    def _do_retried_but_failed(self, do_func, func_check_request=None):
        self.retry_cnt = 0

        def _retry(request, uri, headers):
            if func_check_request is not None and callable(func_check_request):
                func_check_request(request)
                print('Checking Request:{0}, Pass'.format(request.body))
            print('Round:{0}, Timeout'.format(self.retry_cnt))
            self.retry_cnt += 1
            raise socket.timeout()

        httpretty.register_uri(httpretty.GET,
                               'http://haijia.bjxueche.net/',
                               body=_retry)
        httpretty.register_uri(httpretty.POST,
                               'http://haijia.bjxueche.net/',
                               body=_retry)
        self.dut.set_max_retry(for_url='http://haijia.bjxueche.net/',
                               max_retries=10)
        self.assertRaises(ConnectionError, do_func)
        self.assertEqual(self.retry_cnt, 11)

    def _do_timeout_failed(self, do_func, expt_time):
        start_time = time.time()
        self.assertRaises(Timeout, do_func)
        delta = time.time() - start_time
        print('Return after {0} seconds because of timeout '.format(delta))
        self.assertLessEqual(delta, expt_time)

    def _do_multi_timeout_failed(self, do_func, expt_time):
        start_time = time.time()
        self.assertRaises(ConnectionError, do_func)
        delta = time.time() - start_time
        print('Return after {0} seconds because of timeout '.format(delta))
        self.assertLessEqual(delta, expt_time)

    def test_connect_success(self):
        def _connect():
            resp = self.dut.connect()
            print(resp.text)
            return resp.text

        self._do_success(_connect)

    def test_connect_connection_failed(self):
        self.dut.urls['connect'] = 'http://haijia.bjxueche.ne/'
        self._do_failed(self.dut.connect)

    def test_connect_with_retry(self):
        def _test_connect():
            resp = self.dut.connect()
            print(resp.text)
            return resp.text

        self._do_with_retry(_test_connect)

    def test_connect_retried_but_failed(self):
        self._do_retried_but_failed(self.dut.connect)

    def test_connect_timeout_failed(self):
        self.dut.urls['connect'] = 'http://haijia.bjxueche.net:81/'
        self.dut.timeout_parameters['connect'] = 3
        self._do_timeout_failed(self.dut.connect,
                                self.dut.timeout_parameters['connect'] + 1)

    def test_connect_multi_timeout_failed(self):
        self.dut.urls['connect'] = 'http://haijia.bjxueche.net:81/'
        self.dut.timeout_parameters['connect'] = 2
        self.dut.set_max_retry(for_url=self.dut.urls['connect'], max_retries=5)
        self._do_multi_timeout_failed(
            self.dut.connect,
            (self.dut.timeout_parameters['connect'] + 0.5) * 5)

    def test_open_url_n_read_success(self):
        def _test():
            resp, body = self.dut.open_url_n_read(
                'http://haijia.bjxueche.net/')
            return resp.text

        self._do_success(_test)

    def test_open_url_n_read_failed(self):
        def _test():
            resp, body = self.dut.open_url_n_read('http://haijia.bjxueche.ne/')
            return body

        self._do_failed(_test)

    def test_open_url_n_read_with_retry(self):
        def _test():
            resp, body = self.dut.open_url_n_read(
                'http://haijia.bjxueche.net/')
            return body

        self._do_with_retry(_test)

    def test_open_url_n_read_retry_but_failed(self):
        def _test():
            resp, body = self.dut.open_url_n_read(
                'http://haijia.bjxueche.net/')
            return resp.text

        self._do_retried_but_failed(_test)

    def test_open_url_n_read_timeout_failed(self):
        self.dut.timeout_parameters['open_url_n_read'] = 6

        def _test():
            resp, body = self.dut.open_url_n_read(
                'http://haijia.bjxueche.net:81/')
            return resp.text

        def _test_with_timeout_args():
            resp, body = self.dut.open_url_n_read(
                'http://haijia.bjxueche.net:81/', timeout=7)
            return resp.text

        self._do_timeout_failed(
            _test, self.dut.timeout_parameters['open_url_n_read'] + 1)
        self._do_timeout_failed(_test_with_timeout_args, 8)

    def test_open_url_n_read_multi_timeout_failed(self):
        self.dut.timeout_parameters['open_url_n_read'] = 2

        def _test():
            resp, body = self.dut.open_url_n_read(
                'http://haijia.bjxueche.net:81/')
            return body

        self.dut.set_max_retry(for_url='http://haijia.bjxueche.net:81/',
                               max_retries=5)
        self._do_multi_timeout_failed(
            _test, (self.dut.timeout_parameters['open_url_n_read'] + 0.5) * 5)

    def test_post_with_response_success(self):
        def _post_with_response():
            resp, body = self.dut.post_with_response(
                'http://haijia.bjxueche.net/', data='Posted Data')
            print(body)
            return body

        def chk_post_data(request, uri, headers):
            self.assertEqual(request.body, 'Posted Data')
            return 200, headers, 'Mock, Post succeed'

        self._do_success(_post_with_response,
                         fake_body=chk_post_data,
                         func_get_expt=lambda: 'Mock, Post succeed')

    def test_post_with_response_fail(self):
        def _post_with_response():
            resp, body = self.dut.post_with_response(
                'http://haijia.bjxueche.ne/', data='Posted Data')
            print(body)
            return body

        self._do_failed(_post_with_response)

    def test_post_with_response_with_retry(self):
        def _test():
            resp, body = self.dut.post_with_response(
                'http://haijia.bjxueche.net/', data='Posted Data')
            return body

        self._do_with_retry(_test,
                            func_check_request=lambda r: self.assertEqual(
                                r.body, 'Posted Data'))

    def test_post_with_response_retry_but_failed(self):
        def _test():
            resp, body = self.dut.post_with_response(
                'http://haijia.bjxueche.net/', data='Posted Data')
            return body

        self._do_retried_but_failed(_test,
                                    func_check_request=lambda r: self.
                                    assertEqual(r.body, 'Posted Data'))

    def test_post_with_response_timeout_failed(self):
        self.dut.timeout_parameters['post_with_response'] = 3

        def _test():
            print('Calling Test function')
            resp, body = self.dut.post_with_response(
                'http://haijia.bjxueche.net:81/', data='Posted Data')
            return body

        def _test_with_timeout_args():
            print('Calling Test function with timeout argument')
            resp, body = self.dut.post_with_response(
                'http://haijia.bjxueche.net:81/',
                data='Posted Data',
                timeout=7)
            return body

        self._do_timeout_failed(
            _test, self.dut.timeout_parameters['post_with_response'] + 1)
        self._do_timeout_failed(_test_with_timeout_args, 8)

    def test_post_with_response_multi_timeout_failed(self):
        self.dut.timeout_parameters['post_with_response'] = 2

        def _test():
            print('Calling Test function')
            resp, body = self.dut.post_with_response(
                'http://haijia.bjxueche.net:81/', data='Posted Data')
            return body

        def _test_with_timeout_args():
            print('Calling Test function with timeout argument')
            resp, body = self.dut.post_with_response(
                'http://haijia.bjxueche.net:81/',
                data='Posted Data',
                timeout=3)
            return body

        self.dut.set_max_retry(for_url='http://haijia.bjxueche.net:81/',
                               max_retries=5)
        self._do_multi_timeout_failed(
            _test,
            (self.dut.timeout_parameters['post_with_response'] + 0.5) * 5)
        self._do_multi_timeout_failed(_test_with_timeout_args, (3 + 0.8) * 5)

    def test_multi_threads(self):
        urls = [
            'http://en.wiktionary.org', 'http://en.wiktionary.org',
            'http://en.wiktionary.org', 'http://www.google.com',
            'http://www.google.com'
        ]

        workers = [
            WorkerInMultiThreads(v, self.dut, i + 4, i, self)
            for i, v in enumerate(urls)
        ]
        working_threads = [Thread(target=worker.run) for worker in workers]

        existed_threads = active_count()
        print(
            'Before starting, {0} threads are running'.format(existed_threads))
        for a_thread in working_threads:
            a_thread.start()
            print(a_thread.is_alive())
            time.sleep(randrange(1, 10) / 10)

        while active_count() > existed_threads:
            print('{0} threads are running'.format(active_count()))
            time.sleep(20)
        self.assertTrue(all([w.run_pass for w in workers]))
示例#8
0
 def setUp(self):
     URLsForHJ.connect = 'http://haijia.bjxueche.net'
     self.session = Session()
     self.session.set_max_retry(for_url='http://haijia.bjxueche.net/', max_retries=10)
     self.dut = Role.get('WaitingTimer')
     self.dut.load_properties(session=self.session)
示例#9
0
class UTDriver(unittest.TestCase):
    def setUp(self):
        self.shared_session = Session()
        self.driver = Role.get('Driver')
        self.driver.log_path = 'log_utdriver'

    def test_creation_n_properties_of_driver(self):
        self.driver = Role.get('Driver')
        self.assertTrue(hasattr(self.driver, 'drivername'))
        self.assertTrue(hasattr(self.driver, 'password'))
        self.assertTrue(hasattr(self.driver, 'session'))
        self.assertEqual(self.driver.drivername, None)
        self.assertEqual(self.driver.password, None)
        self.assertEqual(self.driver.session, None)
        self.driver.drivername = 'John Doe'
        self.assertEqual(self.driver.drivername, 'John Doe')
        print(self.driver.drivername)
        print(self.driver.password)
        print(self.driver.session)

    def test_load_properties_success(self):
        self.driver.load_properties(drivername='John Smith',
                                    password='******',
                                    session=self.shared_session)
        self.assertEqual(self.driver.drivername, 'John Smith')
        self.assertEqual(self.driver.password, '888888')
        self.assertIs(self.driver.session, self.shared_session)

    def test_load_properties_fail(self):
        def _no_drivername():
            self.driver.load_properties(password='******',
                                        session=self.shared_session)

        def _no_password():
            self.driver.load_properties(drivername='John Smith',
                                        session=self.shared_session)

        def _no_session():
            self.driver.load_properties(drivername='John Smith',
                                        password='******')

        self.assertRaises(ValueError, _no_drivername)
        self.assertRaises(ValueError, _no_password)
        self.assertRaises(ValueError, _no_session)

    def test_get_login_form(self):
        self.shared_session.set_max_retry(
            for_url='http://haijia.bjxueche.net/', max_retries=5)
        self.driver.load_properties(drivername='John Smith',
                                    password='******',
                                    session=self.shared_session)
        login_form = self.driver._get_login_form()

        self.assertTrue('txtUserName' in login_form)
        self.assertTrue('txtPassword' in login_form)
        self.assertTrue('txtIMGCode' in login_form)
        self.assertEqual(login_form['txtUserName'], 'John Smith')
        self.assertEqual(login_form['txtPassword'], '8' * 6)
        self.assertEqual(login_form['txtIMGCode'], None)

    def test_login_again(self):
        def monkey_patch_get_login_form():
            raise TypeError('monkey_patch_get_login_form')

        setattr(self.driver, '_get_login_form', monkey_patch_get_login_form)
        self.assertRaises(LoginAgain, self.driver.login)

    def test_login_retry(self):
        self.retry_cnt = 0
        expect_retry_num = 11
        Driver.login_repeat_times = expect_retry_num

        def monkey_patch_get_net_text():
            self.retry_cnt += 1

        def monkey_patch_get_login_form():
            raise CAPTCHAError('monkey_patch_get_login_form')

        setattr(self.driver, '_get_login_form', monkey_patch_get_login_form)
        setattr(self.driver, '_get_net_text', monkey_patch_get_net_text)
        self.assertRaises(LoginFail, self.driver.login)
        self.assertEquals(expect_retry_num, self.retry_cnt)

    def test_login(self):
        self.shared_session.set_max_retry(
            for_url='http://haijia.bjxueche.net/', max_retries=5)
        # utdriver_login.txt should contain the following format:
        # username
        # password
        with open('Private files/utdriver_login.txt', 'r') as f:
            s_file = f.read()
            s_lst = s_file.split('\n')
        print(s_lst)
        self.driver.load_properties(drivername=s_lst[0],
                                    password=s_lst[1],
                                    session=self.shared_session)
        self.assertTrue(self.driver.login())
示例#10
0
 def setUp(self):
     self.dut = Session()
     self.dut.log_file_name = 'UTSession'
示例#11
0
class UTSession(unittest.TestCase):
    def setUp(self):
        self.dut = Session()
        self.dut.log_file_name = 'UTSession'

    @httpretty.activate
    def _do_success(self, do_func, fake_body='Mock, Connection succeed', func_get_expt=None):
        httpretty.register_uri(httpretty.GET, 'http://haijia.bjxueche.net/',
                               body=fake_body)
        httpretty.register_uri(httpretty.POST, 'http://haijia.bjxueche.net/',
                               body=fake_body)
        body = do_func()
        if isinstance(fake_body, str):
            self.assertEqual(body, fake_body)
        elif callable(func_get_expt):
            self.assertEqual(body, func_get_expt())
        else:
            self.assertTrue(False)

    def _do_failed(self, do_func):
        self.assertRaises(ConnectionError, do_func)

    @httpretty.activate
    def _do_with_retry(self, do_func, func_check_request=None):
        self.retry_cnt = 0

        def _retry(request, uri, headers):
            if func_check_request is not None and callable(func_check_request):
                func_check_request(request)
                print('Checking Request:{0}, Pass'.format(request.body))
            if self.retry_cnt == 5:
                print('Round:{0}, Response'.format(self.retry_cnt))
                return 200, headers, 'Mock, Connection succeed'
            else:
                print('Round:{0}, Timeout'.format(self.retry_cnt))
                self.retry_cnt += 1
                raise socket.timeout()

        httpretty.register_uri(httpretty.GET, 'http://haijia.bjxueche.net/', body=_retry)
        httpretty.register_uri(httpretty.POST, 'http://haijia.bjxueche.net/', body=_retry)
        self.dut.set_max_retry(for_url='http://haijia.bjxueche.net/', max_retries=6)
        body = do_func()
        self.assertEqual(body, 'Mock, Connection succeed')
        self.assertEqual(self.retry_cnt, 5)

    @httpretty.activate
    def _do_retried_but_failed(self, do_func, func_check_request=None):
        self.retry_cnt = 0

        def _retry(request, uri, headers):
            if func_check_request is not None and callable(func_check_request):
                func_check_request(request)
                print('Checking Request:{0}, Pass'.format(request.body))
            print('Round:{0}, Timeout'.format(self.retry_cnt))
            self.retry_cnt += 1
            raise socket.timeout()

        httpretty.register_uri(httpretty.GET, 'http://haijia.bjxueche.net/', body=_retry)
        httpretty.register_uri(httpretty.POST, 'http://haijia.bjxueche.net/', body=_retry)
        self.dut.set_max_retry(for_url='http://haijia.bjxueche.net/', max_retries=10)
        self.assertRaises(ConnectionError, do_func)
        self.assertEqual(self.retry_cnt, 11)

    def _do_timeout_failed(self, do_func, expt_time):
        start_time = time.time()
        self.assertRaises(Timeout, do_func)
        delta = time.time() - start_time
        print('Return after {0} seconds because of timeout '.format(delta))
        self.assertLessEqual(delta, expt_time)

    def _do_multi_timeout_failed(self, do_func, expt_time):
        start_time = time.time()
        self.assertRaises(ConnectionError, do_func)
        delta = time.time() - start_time
        print('Return after {0} seconds because of timeout '.format(delta))
        self.assertLessEqual(delta, expt_time)

    def test_connect_success(self):
        def _connect():
            resp = self.dut.connect()
            print(resp.content)
            return resp.content
        self._do_success(_connect)

    def test_connect_connection_failed(self):
        self.dut.urls['connect'] = 'http://haijia.bjxueche.ne/'
        self._do_failed(self.dut.connect)

    def test_connect_with_retry(self):
        def _test_connect():
            resp = self.dut.connect()
            print(resp.content)
            return resp.content
        self._do_with_retry(_test_connect)

    def test_connect_retried_but_failed(self):
        self._do_retried_but_failed(self.dut.connect)

    def test_connect_timeout_failed(self):
        self.dut.urls['connect'] = 'http://haijia.bjxueche.net:81/'
        self.dut.timeout_parameters['connect'] = 3
        self._do_timeout_failed(self.dut.connect, self.dut.timeout_parameters['connect']+1)

    def test_connect_multi_timeout_failed(self):
        self.dut.urls['connect'] = 'http://haijia.bjxueche.net:81/'
        self.dut.timeout_parameters['connect'] = 2
        self.dut.set_max_retry(for_url=self.dut.urls['connect'], max_retries=5)
        self._do_multi_timeout_failed(self.dut.connect, (self.dut.timeout_parameters['connect']+0.5)*5)

    def test_open_url_n_read_success(self):
        def _test():
            resp, body = self.dut.open_url_n_read('http://haijia.bjxueche.net/')
            return body
        self._do_success(_test)

    def test_open_url_n_read_failed(self):
        def _test():
            resp, body = self.dut.open_url_n_read('http://haijia.bjxueche.ne/')
            return body
        self._do_failed(_test)

    def test_open_url_n_read_with_retry(self):
        def _test():
            resp, body = self.dut.open_url_n_read('http://haijia.bjxueche.net/')
            return body
        self._do_with_retry(_test)

    def test_open_url_n_read_retry_but_failed(self):
        def _test():
            resp, body = self.dut.open_url_n_read('http://haijia.bjxueche.net/')
            return body
        self._do_retried_but_failed(_test)

    def test_open_url_n_read_timeout_failed(self):
        self.dut.timeout_parameters['open_url_n_read'] = 6

        def _test():
            resp, body = self.dut.open_url_n_read('http://haijia.bjxueche.net:81/')
            return body

        def _test_with_timeout_args():
            resp, body = self.dut.open_url_n_read('http://haijia.bjxueche.net:81/', timeout=7)
            return body
        self._do_timeout_failed(_test, self.dut.timeout_parameters['open_url_n_read']+1)
        self._do_timeout_failed(_test_with_timeout_args, 8)


    def test_open_url_n_read_multi_timeout_failed(self):
        self.dut.timeout_parameters['open_url_n_read'] = 2
        def _test():
            resp, body = self.dut.open_url_n_read('http://haijia.bjxueche.net:81/')
            return body
        self.dut.set_max_retry(for_url='http://haijia.bjxueche.net:81/', max_retries=5)
        self._do_multi_timeout_failed(_test, (self.dut.timeout_parameters['open_url_n_read']+0.5)*5)

    def test_post_with_response_success(self):
        def _post_with_response():
            resp, body = self.dut.post_with_response('http://haijia.bjxueche.net/', data='Posted Data')
            print(body)
            return body

        def chk_post_data(request, uri, headers):
            self.assertEqual(request.body, 'Posted Data')
            return 200, headers, 'Mock, Post succeed'

        self._do_success(_post_with_response, fake_body=chk_post_data, func_get_expt=lambda: 'Mock, Post succeed')

    def test_post_with_response_fail(self):
        def _post_with_response():
            resp, body = self.dut.post_with_response('http://haijia.bjxueche.ne/', data='Posted Data')
            print(body)
            return body
        self._do_failed(_post_with_response)

    def test_post_with_response_with_retry(self):
        def _test():
            resp, body = self.dut.post_with_response('http://haijia.bjxueche.net/', data='Posted Data')
            return body
        self._do_with_retry(_test, func_check_request=lambda r: self.assertEqual(r.body, 'Posted Data'))

    def test_post_with_response_retry_but_failed(self):
        def _test():
            resp, body = self.dut.post_with_response('http://haijia.bjxueche.net/', data='Posted Data')
            return body
        self._do_retried_but_failed(_test, func_check_request=lambda r: self.assertEqual(r.body, 'Posted Data'))

    def test_post_with_response_timeout_failed(self):
        self.dut.timeout_parameters['post_with_response'] = 3

        def _test():
            print('Calling Test function')
            resp, body = self.dut.post_with_response('http://haijia.bjxueche.net:81/', data='Posted Data')
            return body

        def _test_with_timeout_args():
            print('Calling Test function with timeout argument')
            resp, body = self.dut.post_with_response('http://haijia.bjxueche.net:81/', data='Posted Data', timeout=7)
            return body
        self._do_timeout_failed(_test, self.dut.timeout_parameters['post_with_response']+1)
        self._do_timeout_failed(_test_with_timeout_args, 8)

    def test_post_with_response_multi_timeout_failed(self):
        self.dut.timeout_parameters['post_with_response'] = 2

        def _test():
            print('Calling Test function')
            resp, body = self.dut.post_with_response('http://haijia.bjxueche.net:81/', data='Posted Data')
            return body

        def _test_with_timeout_args():
            print('Calling Test function with timeout argument')
            resp, body = self.dut.post_with_response('http://haijia.bjxueche.net:81/', data='Posted Data', timeout=3)
            return body
        self.dut.set_max_retry(for_url='http://haijia.bjxueche.net:81/', max_retries=5)
        self._do_multi_timeout_failed(_test, (self.dut.timeout_parameters['post_with_response']+0.5)*5)
        self._do_multi_timeout_failed(_test_with_timeout_args, (3+0.8)*5)

    def test_multi_threads(self):
        urls = ['http://en.wiktionary.org',
                'http://en.wiktionary.org',
                'http://en.wiktionary.org',
                'http://www.google.com',
                'http://www.google.com'
                ]

        workers = [WorkerInMultiThreads(v, self.dut, i+4, i, self) for i, v in enumerate(urls)]
        working_threads = [Thread(target=worker.run) for worker in workers]

        existed_threads = active_count()
        print('Before starting, {0} threads are running'.format(existed_threads))
        for a_thread in working_threads:
            a_thread.start()
            print(a_thread.is_alive())
            time.sleep(randrange(1, 10)/10)

        while active_count() > existed_threads:
            print('{0} threads are running'.format(active_count()))
            time.sleep(20)
        self.assertTrue(all([w.run_pass for w in workers]))
示例#12
0
 def setUp(self):
     self.shared_session = Session()
     self.driver = Role.get('Driver')
示例#13
0
 def setUp(self):
     self.shared_session = Session()
     self.driver = Role.get('Driver')
     self.driver.log_path = 'log_utdriver'
示例#14
0
 def setUp(self):
     self.shared_session = Session()
     self.driver = Role.get('Driver')
     self.driver.log_path = 'log_utdriver'
示例#15
0
class UTWaitingTimer(unittest.TestCase):
    def setUp(self):
        URLsForHJ.connect = 'http://haijia.bjxueche.net'
        self.session = Session()
        self.session.set_max_retry(for_url='http://haijia.bjxueche.net/', max_retries=10)
        self.dut = Role.get('WaitingTimer')
        self.dut.load_properties(session=self.session)

    @httpretty.activate
    def test_get_server_time(self):

        httpretty.register_uri(httpretty.GET, 'http://haijia.bjxueche.net/',
                               body='Mock, Post succeed',
                               forcing_headers={'date': 'Fri, 26 Dec 2014 14:59:41 GMT'})
        loc_time = self.dut.get_server_time()
        self.assertEqual('2014-12-26 22:59:41+08:00', str(loc_time))

    @httpretty.activate
    def test_get_server_time_2(self):
        httpretty.register_uri(httpretty.GET, "http://haijia.bjxueche.net/",
                               Date='Mon, 15 Dec 2014 16:58:19 GMT')
        loc_time = self.dut.get_server_time()
        self.assertEqual(loc_time.day, 16)
        self.assertEqual(loc_time.hour, 0)
        self.assertEqual(loc_time.minute, 58)
        httpretty.register_uri(httpretty.GET, "http://haijia.bjxueche.net/",
                               Date='Mon, 15 Dec 2014 17:08:20 GMT')
        loc_time = self.dut.get_server_time()
        self.assertEqual(loc_time.day, 16)
        self.assertEqual(loc_time.hour, 1)
        self.assertEqual(loc_time.minute, 8)

    @httpretty.activate
    def test_get_server_time_with_retry(self):
        self.retry_cnt = 0

        def _retry(request, uri, headers):
            if self.retry_cnt == 9:
                print('Round:{0}, Response'.format(self.retry_cnt))
                return 200, headers, 'Mock, Connection succeed'
            else:
                print('Round:{0}, Timeout'.format(self.retry_cnt))
                self.retry_cnt += 1
                raise socket.timeout()
        httpretty.register_uri(httpretty.GET, 'http://haijia.bjxueche.net/',
                               body=_retry,
                               forcing_headers={'date': 'Fri, 26 Dec 2014 14:59:41 GMT'})

        loc_time = self.dut.get_server_time()
        self.assertEqual('2014-12-26 22:59:41+08:00', str(loc_time))
        self.assertEqual(self.retry_cnt, 9)

    def test_localize_date(self):
        fmt01 = self.dut.localize_date('Jan 01 2017')
        fmt02 = self.dut.localize_date('2017-01-01')
        fmt03 = self.dut.localize_date('20170101')
        self.assertEquals(fmt01, fmt02)
        self.assertEquals(fmt02, fmt03)

    def test_get_server_time_timeout_after_retry(self):
        URLsForHJ.connect = 'http://haijia.bjxueche.net:81'
        self.session.set_max_retry(for_url='http://haijia.bjxueche.net:81/', max_retries=5)

        def _test():
            self.dut.get_server_time()
        start_time = time.time()
        self.assertRaises(ConnectionError, _test)
        delta = time.time() - start_time
        print('Return after {0} seconds because of timeout '.format(delta))
        self.assertGreaterEqual(delta, 20*5)

    def offset_n_minutes(self, current_time, func_get_offset_minute):
        self.dut.debut_hour = current_time.hour + func_get_offset_minute(current_time.minute)//60
        self.dut.debut_minute = func_get_offset_minute(current_time.minute) % 60

    def test_get_book_time_today(self):
        """
            Don't set book date, DUT set it 7 days later automatically, and gives the wake-up time as 3 minutes later
        """
        loc_time = datetime.now()
        self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e + 3)
        book_time = self.dut.get_debut_time(loc_time)
        self.assertEqual(book_time.day, loc_time.day)
        self.assertEqual(book_time.hour, self.dut.debut_hour)
        self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_today_set(self):
        """
            Set book date to 7 days later , and DUT gives the wake-up time as 3 minutes later
        """
        seven_days = timedelta(days=7)
        loc_time = datetime.now()
        self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e + 3)
        self.dut.lesson_date = loc_time + seven_days
        book_time = self.dut.get_debut_time(loc_time)
        self.assertEqual(book_time.day, loc_time.day)
        self.assertEqual(book_time.hour, self.dut.debut_hour)
        self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_later_equal_tomorrow_set(self):
        """
            Set book date to 8 and 9 days later , and DUT gives the wake-up time as 3 minutes later at some day
        """
        for i in range(2):
            print('Round {0}'.format(i))
            eight_days = timedelta(days=8+i)
            loc_time = datetime.now()
            self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e + 3)
            self.dut.lesson_date = loc_time + eight_days
            book_time = self.dut.get_debut_time(loc_time)
            wake_up_date = loc_time + timedelta(days=1+i)
            self.assertEqual(book_time.day, wake_up_date.day)
            self.assertEqual(book_time.hour, self.dut.debut_hour)
            self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_tomorrow(self):
        """
            Don't set book date, DUT set it 8 days later automatically,
            and gives the wake-up time at tomorrow
        """
        loc_time = datetime.now()
        self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e - 3)
        book_time = self.dut.get_debut_time(loc_time)
        print('Wake up at {0}'.format(str(book_time)))
        wake_up_date = loc_time + timedelta(days=1)
        self.assertEqual(book_time.day, wake_up_date.day)
        self.assertEqual(book_time.hour, self.dut.debut_hour)
        self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_tomorrow_set(self):
        """
            Set book date to 1~8 days later , and DUT gives the wake-up time as tomorrow
        """
        for i in range(8):
            _7_8_days = timedelta(days=1+i)
            loc_time = datetime.now()
            self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e - 3)
            self.dut.lesson_date = loc_time + _7_8_days
            print('Round {0}: want {1} in {2}'.format(i, str(self.dut.lesson_date), str(_7_8_days)))
            book_time = self.dut.get_debut_time(loc_time)
            print('Wake up at {0}'.format(str(book_time)))
            wake_up_date = loc_time + timedelta(days=1)
            self.assertEqual(book_time.day, wake_up_date.day)
            self.assertEqual(book_time.hour, self.dut.debut_hour)
            self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_book_time_later_than_tomorrow_set(self):
        """
            Set book date to 9~11 days later , and DUT gives the wake-up time as tomorrow
        """
        for i in range(3):
            _7_8_days = timedelta(days=9+i)
            loc_time = datetime.now()
            self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e - 3)
            self.dut.lesson_date = loc_time + _7_8_days
            print('Round {0}: want {1} in {2}'.format(i, str(self.dut.lesson_date), str(_7_8_days)))
            book_time = self.dut.get_debut_time(loc_time)
            print('Wake up at {0}'.format(str(book_time)))
            wake_up_date = loc_time + timedelta(days=2+i)
            self.assertEqual(book_time.day, wake_up_date.day)
            self.assertEqual(book_time.hour, self.dut.debut_hour)
            self.assertEqual(book_time.minute, self.dut.debut_minute)

    def test_get_sleep_span_0(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(second=(loc_time.second + 30) % 60,
                                     minute=loc_time.minute + (loc_time.second + 30) // 60)

        self.assertEqual(0, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_sleep_span_50s_tc0(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 1) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 1) // 60)

        self.assertLessEqual(self.dut.get_sleep_span(book_time, loc_time), 50)

    def test_get_sleep_span_50s_tc1(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 3) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 3) // 60)

        self.assertEqual(50, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_sleep_span_10m_tc0(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 10) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 10) // 60)

        self.assertEqual(50, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_sleep_span_10m_tc1(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 15) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 15) // 60)

        self.assertEqual(600, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_sleep_span_10m_tc2(self):
        loc_time = self.dut.get_server_time()
        book_time = loc_time.replace(minute=(loc_time.minute + 11) % 60,
                                     hour=loc_time.hour + (loc_time.minute + 11) // 60)

        self.assertEqual(50, self.dut.get_sleep_span(book_time, loc_time))

    def test_get_book_date_auto(self):
        _7_days = timedelta(days=7)
        loc_time = datetime.now()
        book_date = self.dut.get_book_date(loc_time)
        expt_date = loc_time + _7_days
        self.assertEqual(expt_date.year, book_date.year)
        self.assertEqual(expt_date.month, book_date.month)
        self.assertEqual(expt_date.day, book_date.day)

    def test_get_book_date_set(self):
        _9_days = timedelta(days=9)
        loc_time = datetime.now()
        self.offset_n_minutes(loc_time, func_get_offset_minute=lambda e: e - 3)
        expt_date = loc_time + _9_days
        self.dut.lesson_date = expt_date
        book_date = self.dut.get_book_date(loc_time)
        self.assertEqual(expt_date.year, book_date.year)
        self.assertEqual(expt_date.month, book_date.month)
        self.assertEqual(expt_date.day, book_date.day)

    def to_test_run_common(self, func_get_book_minute, delay=None):
        server_time = self.dut.get_server_time()
        self.offset_n_minutes(server_time, func_get_book_minute)

        if delay is not None:
            time.sleep(delay)
        self.dut.run()
        return self.dut, server_time

    def test_run_tc0(self):
        dut, server_time = self.to_test_run_common(lambda e: e + 1)
        wait_end_time = dut.get_server_time()
        self.assertTrue(wait_end_time - server_time < timedelta(seconds=50))

    def test_run_tc1(self):
        dut, server_time = self.to_test_run_common(lambda e: e + 1, delay=10)
        wait_end_time = dut.get_server_time()
        self.assertTrue(wait_end_time - server_time < timedelta(seconds=50))

    def test_run_tc2(self):
        dut, server_time = self.to_test_run_common(lambda e: e + 3)
        wait_end_time = dut.get_server_time()
        self.assertTrue(wait_end_time - server_time > timedelta(seconds=100))

    def test_run_tc3(self):
        dut, server_time = self.to_test_run_common(lambda e: e + 4)
        wait_end_time = dut.get_server_time()
        self.assertGreaterEqual(wait_end_time - server_time, timedelta(minutes=2))

    def test_book_now_0(self):
        dut_book_now = BookNowTimer()
        dut_book_now.load_properties(session=self.session, lesson_date='Jan 1 2020')
        loc_time = dut_book_now.get_server_time()
        book_time = dut_book_now.run()
        wait_end_time = dut_book_now.get_server_time()

        self.assertLessEqual(wait_end_time - loc_time, timedelta(seconds=1))
示例#16
0
 def setUp(self):
     self.session = Session()
     self.dut = CAPTCHARecognizer(self.session)
     CAPTCHARecognizer.ocr_exe_path = 'tesseract'
示例#17
0
 def setUp(self):
     self.shared_session = Session()
     self.dut = Role.get('Booker')