コード例 #1
0
class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.driver = None
        cls.test_url = 'http://automationpractice.com/index.php'
        cls.test_title = 'My Store'
        cls.header_text = 'Automation Practice Website'

    def setUp(self):
        if self.driver is not None:
            self.driver.quit()

        self.driver = None

    # @unittest.skip('not ready')
    def test_chrome(self):
        browser = 'chrome'
        self.generic_method(browser)

    # @unittest.skip('not ready')
    def test_ie(self):
        browser = 'ie'
        self.generic_method(browser)

    # @unittest.skip('not ready')
    def test_opera(self):
        browser = 'opera'
        self.generic_method(browser)

    # @unittest.skip('not ready')
    def test_mozilla(self):
        browser = 'mozilla'
        self.generic_method(browser)

    # @unittest.skip('not ready')
    def test_edge(self):
        browser = 'edge'
        self.generic_method(browser)

    def generic_method(self, browser):
        try:
            self.open_test_web_page(browser)
            header = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.TAG_NAME, 'h1')))
            self.assertEqual(self.header_text, header.text)

        except Exception as ec:
            print('\nERROR: {}'.format(ec))
            self.take_screen_shot()
            raise

    def open_test_web_page(self, browser):
        # Open test web page and verify URL + Title
        self.driver = Driver(browser).get_driver()
        self.driver.get(self.test_url)
        self.driver.maximize_window()

        WebDriverWait(self.driver,
                      15).until(EC.title_contains(self.test_title))
        time.sleep(1)

        self.assertEqual(self.test_url, self.driver.current_url)
        self.assertEqual(self.test_title, self.driver.title)

    def take_screen_shot(self):
        """Take a Screen-shot of the webpage when test Failed."""
        now = datetime.datetime.now()
        filename = 'screenshot-{}-{}.png'.format(
            self.driver.name,
            datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))
        self.driver.save_screenshot(filename)
        print('\nScreenshot saved as {}'.format(filename))

    def screenshots_collector(self):
        '''
        Collect all screenshots and put them into screenshots directory
        :return:
        '''
        import os
        import shutil

        screenshots_folder = 'screenshots'
        if not os.path.exists(os.curdir + '\\screenshots'):
            os.mkdir(screenshots_folder)

        now = datetime.datetime.now()
        folder_name = '{}\\screenshots_{}_{}'.format(
            screenshots_folder, self.driver.name,
            datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))

        files = os.listdir(os.curdir)
        for file in files:
            if '.png' in str(file):
                if not os.path.exists(os.curdir + '\\' + folder_name):
                    os.mkdir(folder_name)
                shutil.move(
                    file.split('\\')[-1], os.curdir + '\\' + folder_name)

    def tearDown(self):
        self.screenshots_collector()
        self.driver.stop_client()
        self.driver.close()
        time.sleep(1)

    @classmethod
    def tearDownClass(cls):
        if cls.driver is not None:
            cls.driver.quit()
class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.driver = None
        cls.jscript_alerts_url = 'https://www.seleniumeasy.com/test/javascript-alert-box-demo.html'
        cls.jscript_alerts_title = 'Selenium Easy Demo - Automate All Scenarios'

        cls.jscript_alert_box_btn_xpath = '/html/body/div[2]/div/div[2]/div[1]/div[2]/button'
        cls.jscript_confirm_box_xpath = '/html/body/div[2]/div/div[2]/div[2]/div[2]/button'
        cls.configrm_demo_id = 'confirm-demo'
        cls.jscript_alert_box_prompt_xpath = '/html/body/div[2]/div/div[2]/div[3]/div[2]/button'
        cls.promt_demo_id = 'prompt-demo'

    def setUp(self):
        if self.driver is not None:
            self.driver.quit()

        self.driver = None

    def test_chrome(self):
        browser = 'chrome'
        self.generic_method(browser)

    def test_ie(self):
        browser = 'ie'
        self.generic_method(browser)

    def test_opera(self):
        browser = 'opera'
        self.generic_method(browser)

    def test_mozilla(self):
        browser = 'mozilla'
        self.generic_method(browser)

    def test_edge(self):
        browser = 'edge'
        self.generic_method(browser)

    def generic_method(self, browser):

        self.open_web_browser(browser)

        try:
            # Test Java Script Alert Box
            self.alert_box_testing()

            # Test Java Script Confirm Box
            self.confirm_box_testing()

            # Test Java Script Prompt Box
            self.prompt_box_testing()
        except WebDriverException as ec:
            self.screen_shot()
            raise

    def alert_box_testing(self):

        # Open Java Script Alert Box
        self.driver.find_element(By.XPATH,
                                 self.jscript_alert_box_btn_xpath).click()
        alert_box = WebDriverWait(self.driver, 15).until(
            expected_conditions.alert_is_present())

        # Verify alert box text and close the alert
        self.assertEqual('I am an alert box!', alert_box.text)
        time.sleep(1)
        alert_box.accept()

        # Back to the main window
        self.driver.switch_to.default_content()

    def confirm_box_testing(self):

        # Open Java Script Confirm Box
        self.driver.find_element(By.XPATH,
                                 self.jscript_confirm_box_xpath).click()
        confirm_box = WebDriverWait(self.driver, 15).until(
            expected_conditions.alert_is_present())

        # Verify text >>> Hit OK button
        self.assertTrue('Press a button!' in confirm_box.text)
        time.sleep(1)
        confirm_box.accept()

        # Verify the result
        self.driver.switch_to.default_content()
        self.assertEqual(
            'You pressed OK!',
            self.driver.find_element(By.ID, self.configrm_demo_id).text)
        time.sleep(1)

        # Open alert again
        self.driver.find_element(By.XPATH,
                                 self.jscript_confirm_box_xpath).click()
        confirm_box = WebDriverWait(self.driver, 15).until(
            expected_conditions.alert_is_present())

        # Verify text >>> Hit CANCEL button
        self.assertTrue('Press a button!' in confirm_box.text)
        time.sleep(1)
        confirm_box.dismiss()

        # Verify the result
        self.driver.switch_to.default_content()
        self.assertEqual(
            'You pressed Cancel!',
            self.driver.find_element(By.ID, self.configrm_demo_id).text)
        time.sleep(1)

    def prompt_box_testing(self):

        # Open prompt box and verify prompt text
        self.driver.find_element(By.XPATH,
                                 self.jscript_alert_box_prompt_xpath).click()
        prompt_box = WebDriverWait(self.driver, 15).until(
            expected_conditions.alert_is_present())
        self.assertEqual('Please enter your name', prompt_box.text)
        time.sleep(1)

        # Cancel it and verify the result
        prompt_box.dismiss()
        self.driver.switch_to.default_content()
        self.assertEqual(
            '',
            self.driver.find_element(By.ID, self.promt_demo_id).text)
        time.sleep(1)

        # Open prompt again
        self.driver.switch_to.default_content()
        self.driver.find_element(By.XPATH,
                                 self.jscript_alert_box_prompt_xpath).click()
        prompt_box = WebDriverWait(self.driver, 15).until(
            expected_conditions.alert_is_present())

        # Type name in prompt box
        time.sleep(1)
        prompt_box.send_keys('John Snow')
        time.sleep(1)

        # Accept it and verify text
        prompt_box.accept()
        self.driver.switch_to.default_content()
        self.assertEqual(
            'You have entered \'John Snow\' !',
            self.driver.find_element(By.ID, self.promt_demo_id).text)
        time.sleep(1)

    def open_web_browser(self, browser):

        try:
            # Launch webdriver on test web page + maximize window:
            self.driver = Driver(browser).get_driver()
            self.driver.maximize_window()
            self.driver.get(self.jscript_alerts_url)
            WebDriverWait(self.driver, 5).until(
                expected_conditions.title_is(self.jscript_alerts_title))

        except TimeoutException as ec:
            print('\n', ec)
            is_webpage_loaded = False
            while not is_webpage_loaded:
                is_webpage_loaded = True
                try:
                    if self.driver is not None:
                        self.driver.quit()

                    self.driver = Driver(browser).get_driver()
                    self.driver.maximize_window()
                    self.driver.get(self.jscript_alerts_url)

                    WebDriverWait(self.driver, 5).until(
                        expected_conditions.title_is(
                            self.jscript_alerts_title))
                except TimeoutException as ec:
                    print('\n', ec)
                    is_webpage_loaded = False

        finally:
            # Verify URL + Title
            self.assertEqual(self.jscript_alerts_url, self.driver.current_url)
            self.assertEqual(self.jscript_alerts_title, self.driver.title)

    def screen_shot(self):
        """Take a Screen-shot of the webpage when test Failed."""
        now = datetime.datetime.now()
        filename = 'screenshot-{}-{}.png'.format(
            self.driver.name,
            datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))
        self.driver.save_screenshot(filename)
        print('\nScreenshot saved as {}'.format(filename))

    @staticmethod
    def screenshots_collector():
        '''
        Collect all screenshots and put them into screenshots directory
        :return:
        '''
        import os
        import shutil

        screenshots_folder = 'screenshots'
        if not os.path.exists(os.curdir + '\\screenshots'):
            os.mkdir(screenshots_folder)

        now = datetime.datetime.now()
        folder_name = '{}\\screenshots_{}'.format(
            screenshots_folder,
            datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))

        files = os.listdir(os.curdir)
        for file in files:
            if '.png' in str(file):
                if not os.path.exists(os.curdir + '\\' + folder_name):
                    os.mkdir(folder_name)
                shutil.move(
                    file.split('\\')[-1], os.curdir + '\\' + folder_name)

    def tearDown(self):
        for handle in self.driver.window_handles:
            self.driver.switch_to.window(handle)
            self.driver.stop_client()
            self.driver.close()
        time.sleep(1)

    @classmethod
    def tearDownClass(cls):
        if cls.driver is not None:
            cls.driver.quit()
class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.driver = None
        cls.test_url = 'https://jqueryui.com/droppable/'
        cls.test_title = 'Droppable | jQuery UI'

    def setUp(self):
        if self.driver is not None:
            self.driver.quit()

        self.driver = None

    def test_chrome(self):
        browser = 'chrome'
        self.generic_method(browser)

    def test_ie(self):
        browser = 'ie'
        self.generic_method(browser)

    def test_opera(self):
        browser = 'opera'
        self.generic_method(browser)

    def test_mozilla(self):
        browser = 'mozilla'
        self.generic_method(browser)

    def test_edge(self):
        browser = 'edge'
        self.generic_method(browser)

    def generic_method(self, browser):

        self.open_web_page(browser)

        iframe = self.driver.find_element(
            By.XPATH, '/html/body/div[1]/div[2]/div/div[1]/iframe')
        self.driver.switch_to.frame(iframe)

        try:
            source = WebDriverWait(self.driver, 5).until(
                expected_conditions.presence_of_element_located(
                    (By.ID, 'draggable')))
            target = WebDriverWait(self.driver, 5).until(
                expected_conditions.presence_of_element_located(
                    (By.ID, 'droppable')))

        except Exception as ec:
            self.take_screen_shot()
            raise

        self.assertEqual("Drop here", target.text)
        time.sleep(2)

        actions = ActionChains(self.driver)
        actions.drag_and_drop(source, target).perform()
        time.sleep(2)

        try:
            self.assertEqual("Dropped!", target.text)

        except Exception as e:
            print('\nERROR: ', e.args)
            self.take_screen_shot()
            raise

    def open_web_page(self, browser):

        try:
            # Open web browser and verify page title:
            self.driver = Driver(browser).get_driver()
            self.driver.get(self.test_url)
            self.driver.maximize_window()
            WebDriverWait(self.driver, 5).until(
                expected_conditions.title_is(self.test_title))

        except TimeoutException as ec:
            print('\n', ec)
            is_loaded = False
            while not is_loaded:
                is_loaded = True
                try:
                    self.tearDown()
                    self.driver = Driver(browser).get_driver()
                    self.driver.get(self.test_url)
                    self.driver.maximize_window()
                    WebDriverWait(self.driver, 5).until(
                        expected_conditions.title_is(self.test_title))
                except TimeoutException as ec:
                    print('\n', ec)
                    is_loaded = False

        finally:
            self.assertEqual(self.test_url, self.driver.current_url)
            self.assertEqual(self.test_title, self.driver.title)

    def take_screen_shot(self):
        """Take a Screen-shot of the webpage when test Failed."""
        now = datetime.datetime.now()
        filename = 'screenshot-{}-{}.png'.format(
            self.driver.name,
            datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))
        self.driver.save_screenshot(filename)
        print('\nScreenshot saved as {}'.format(filename))

    @staticmethod
    def screenshots_collector():
        '''
        Collect all screenshots and put them into screenshots directory
        :return:
        '''
        import os
        import shutil

        screenshots_folder = 'screenshots'
        if not os.path.exists(os.curdir + '\\screenshots'):
            os.mkdir(screenshots_folder)

        now = datetime.datetime.now()
        folder_name = '{}\\screenshots_{}'.format(
            screenshots_folder,
            datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))

        files = os.listdir(os.curdir)
        for file in files:
            if '.png' in str(file):
                if not os.path.exists(os.curdir + '\\' + folder_name):
                    os.mkdir(folder_name)
                shutil.move(
                    file.split('\\')[-1], os.curdir + '\\' + folder_name)

    def tearDown(self):
        self.driver.stop_client()
        self.driver.close()

    @classmethod
    def tearDownClass(cls):
        cls.screenshots_collector()
        if cls.driver is not None:
            cls.driver.quit()
class MyTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.driver = None
        cls.url = 'http://demo.automationtesting.in/Windows.html'
        cls.new_url = 'http://www.sakinalium.in/'
        cls.origin_window_name = 'Frames & windows'
        cls.new_window_name = 'Sakinalium | Home'

    def setUp(self):
        if self.driver is not None:
            self.driver.quit()

        self.driver = None

    def test_chrome(self):
        browser = 'chrome'
        try:
            self.generic_method(browser)
        except Exception:
            self.take_screen_shot()
            raise

    def test_ie(self):
        browser = 'ie'
        try:
            self.generic_method(browser)
        except Exception:
            self.take_screen_shot()
            raise

    def test_opera(self):
        browser = 'opera'
        try:
            self.generic_method(browser)
        except Exception:
            self.take_screen_shot()
            raise

    def test_mozilla(self):
        browser = 'mozilla'
        try:
            self.generic_method(browser)
        except Exception:
            self.take_screen_shot()
            raise

    def test_edge(self):
        browser = 'edge'
        try:
            self.generic_method(browser)
        except Exception:
            self.take_screen_shot()
            raise

    def generic_method(self, browser):

        self.open_web_browser(browser)

        # Get current window handle:
        main_window = self.driver.current_window_handle

        try:
            # Hit on click button and switch to new window:
            btn = WebDriverWait(self.driver, 5).until(
                expected_conditions.element_to_be_clickable((By.XPATH,
                                                             '/html/body/div[1]/div/div/div/div[2]/div[1]/a/button')))
            btn.click()
            time.sleep(1)

            # New tabs will be the last object in window_handles:
            self.driver.switch_to.window(self.driver.window_handles[-1])
            self.driver.maximize_window()
        except WebDriverException as ec:
            print('\n', ec)
            self.screen_shot()
            raise

        # Wait for element to appear.
        # Implemented due to a very slow performance of IE and FireFox.
        try:
            WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.new_window_name))
        except TimeoutException as ec:
            is_loaded = False

            while not is_loaded:
                is_loaded = True
                try:
                    print('\n', ec)
                    self.driver.close()
                    time.sleep(1)
                    self.driver.switch_to.window(main_window)
                    btn.click()
                    self.driver.switch_to.window(self.driver.window_handles[-1])
                    self.driver.maximize_window()
                    WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.new_window_name))
                except WebDriverException as ec:
                    print('\n', ex)
                    is_loaded = False

        # Verify new tab name + url:
        self.assertEqual(self.new_window_name, self.driver.title)
        self.assertEqual(self.new_url, self.driver.current_url)
        time.sleep(1)

        # Get a new window handle:
        new_window = self.driver.current_window_handle

        # Switch back to original window:
        self.driver.switch_to.window(main_window)
        self.assertEqual(self.origin_window_name, self.driver.title)
        self.assertEqual(self.url, self.driver.current_url)
        time.sleep(1)

        # Switch to a new tab:
        self.driver.switch_to.window(new_window)
        self.assertEqual(self.new_window_name, self.driver.title)
        self.assertEqual(self.new_url, self.driver.current_url)
        time.sleep(1)

    def open_web_browser(self, browser):
        try:
            # Launch webdriver on test web page + maximize window:
            self.driver = Driver(browser).get_driver()
            self.driver.get(self.url)
            self.driver.maximize_window()
            WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.origin_window_name))

        except TimeoutException as ec:
            print('\n', ec)
            is_loaded = False
            while not is_loaded:
                is_loaded = True
                try:
                    self.tearDown()
                    self.driver = Driver(browser).get_driver()
                    self.driver.get(self.url)
                    self.driver.maximize_window()
                    WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.origin_window_name))
                except TimeoutException as ec:
                    print('\n', ec)
                    is_loaded = False

        finally:
            self.assertEqual(self.url, self.driver.current_url)
            self.assertEqual(self.origin_window_name, self.driver.title)

    def screen_shot(self):
        """Take a Screen-shot of the webpage when test Failed."""
        now = datetime.datetime.now()
        filename = 'screenshot-{}-{}.png'.format(self.driver.name, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))
        self.driver.save_screenshot(filename)
        print('\nScreenshot saved as {}'.format(filename))

    @staticmethod
    def screenshots_collector():
        '''
        Collect all screenshots and put them into screenshots directory
        :return:
        '''
        import os
        import shutil

        screenshots_folder = 'screenshots'
        if not os.path.exists(os.curdir + '\\screenshots'):
            os.mkdir(screenshots_folder)

        now = datetime.datetime.now()
        folder_name = '{}\\screenshots_{}'.format(screenshots_folder, datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))

        files = os.listdir(os.curdir)
        for file in files:
            if '.png' in str(file):
                if not os.path.exists(os.curdir + '\\' + folder_name):
                    os.mkdir(folder_name)
                shutil.move(file.split('\\')[-1], os.curdir + '\\' + folder_name)

    def tearDown(self):
        for handle in self.driver.window_handles:
            self.driver.switch_to.window(handle)
            self.driver.stop_client()
            self.driver.close()
        time.sleep(1)

    @classmethod
    def tearDownClass(cls):
        cls.screenshots_collector()
        if cls.driver is not None:
            cls.driver.quit()
class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):

        cls.driver = None

        cls.test_url = 'http://automationpractice.com/index.php'
        cls.test_title = 'My Store'

        cls.women_text = 'Women'
        cls.women_link = 'http://automationpractice.com/index.php?id_category=3&controller=category'
        cls.women_title = 'Women - My Store'

        cls.dresses_text = 'Dres'
        cls.dresses_link = "http://automationpractice.com/index.php?id_category=8&controller=category"
        cls.dresses_title = 'Dresses - My Store'

        cls.t_shirts_text = 'T-shirts'
        cls.t_shirts_path = '//*[@id="block_top_menu"]/ul/li[3]/a'
        cls.t_shirts_link = "http://automationpractice.com/index.php?id_category=5&controller=category"
        cls.t_shirts_title = 'T-shirts - My Store'

    def setUp(self):
        if self.driver is not None:
            self.driver.quit()

        self.driver = None

    # @unittest.skip('not ready')
    def test_chrome(self):
        browser = 'chrome'
        self.generic_method(browser)

    # @unittest.skip('not ready')
    def test_ie(self):
        browser = 'ie'
        self.generic_method(browser)

    # @unittest.skip('not ready')
    def test_opera(self):
        browser = 'opera'
        self.generic_method(browser)

    # @unittest.skip('not ready')
    def test_mozilla(self):
        browser = 'mozilla'
        self.generic_method(browser)

    # @unittest.skip('not ready')
    def test_edge(self):
        browser = 'edge'
        self.generic_method(browser)

    def generic_method(self, browser):
        try:
            # 1 open web page
            self.open_test_web_page(browser)

            # 2 click on 'Women' button and verify page title
            women_btn = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.LINK_TEXT, self.women_text)))
            women_btn.click()
            WebDriverWait(self.driver,
                          10).until(EC.title_contains(self.women_title))
            self.assertEqual(self.women_title, self.driver.title)
            self.assertEqual(self.women_link, self.driver.current_url)

            # 3
            dresses_btn = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable(
                    (By.PARTIAL_LINK_TEXT, self.dresses_text)))
            dresses_btn.click()
            WebDriverWait(self.driver,
                          10).until(EC.title_contains(self.dresses_title))
            self.assertEqual(self.dresses_title, self.driver.title)
            self.assertEqual(self.dresses_link, self.driver.current_url)

            # 4
            t_shirts_btn = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, self.t_shirts_path)))
            t_shirts_btn.click()
            WebDriverWait(self.driver,
                          10).until(EC.title_contains(self.t_shirts_title))
            self.assertEqual(self.t_shirts_title, self.driver.title)
            self.assertEqual(self.t_shirts_link, self.driver.current_url)

        except Exception as ec:
            print('\nERROR: {}'.format(ec))
            self.take_screen_shot()
            raise

    def open_test_web_page(self, browser):
        # Open test web page and verify URL + Title
        self.driver = Driver(browser).get_driver()
        self.driver.get(self.test_url)
        self.driver.maximize_window()

        WebDriverWait(self.driver,
                      15).until(EC.title_contains(self.test_title))

        self.assertEqual(self.test_url, self.driver.current_url)
        self.assertEqual(self.test_title, self.driver.title)

    def take_screen_shot(self):
        """Take a Screen-shot of the webpage when test Failed."""
        now = datetime.datetime.now()
        filename = 'screenshot-{}-{}.png'.format(
            self.driver.name,
            datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))
        self.driver.save_screenshot(filename)
        print('\nScreenshot saved as {}'.format(filename))

    def screenshots_collector(self):
        '''
		Collect all screenshots and put them into screenshots directory
		:return:
		'''
        import os
        import shutil

        screenshots_folder = 'screenshots'
        if not os.path.exists(os.curdir + '\\screenshots'):
            os.mkdir(screenshots_folder)

        now = datetime.datetime.now()
        folder_name = '{}\\screenshots_{}_{}'.format(
            screenshots_folder, self.driver.name,
            datetime.datetime.strftime(now, '%Y-%m-%d_%H-%M-%S'))

        files = os.listdir(os.curdir)
        for file in files:
            if '.png' in str(file):
                if not os.path.exists(os.curdir + '\\' + folder_name):
                    os.mkdir(folder_name)
                shutil.move(
                    file.split('\\')[-1], os.curdir + '\\' + folder_name)

    def tearDown(self):
        self.screenshots_collector()
        self.driver.stop_client()
        self.driver.close()

    @classmethod
    def tearDownClass(cls):
        if cls.driver is not None:
            cls.driver.quit()