Unittest学习(五)--------测试套件

       应用unittest的TestSuites特性,可以将不同的测试组成一个逻辑组,然后设置统一的测试套件,并通过一个命令来执行测试。这都是通过TestSuites、TestLoader和TestRunner类来实现的。

      在了解TestSuites的细节之前,我们为例子程序添加一个新的测试,用于校验主页。我们将把新加的测试和之前的测试放到一个测试组件中,详见下面代码。

import unittest
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from __builtin__ import classmethod

class HomePageTest(unittest.TestCase):
    @classmethod
    def setUp(cls):
        # create a new Firefox session """
        cls.driver = webdriver.Firefox()
        cls.driver.implicitly_wait(30)
        cls.driver.maximize_window()
        # navigate to the application home page """
        cls.driver.get("http://demo.magentocommerce.com/")

    def test_search_field(self):
        # check search field exists on Home page
        self.assertTrue(self.is_element_present(By.NAME,"q"))

    def test_language_option(self):
        # check language options dropdown on Home page
        self.assertTrue(self.is_element_present
          (By.ID,"select-language"))

    def test_shopping_cart_empty_message(self):
        # check content of My Shopping Cart block on Home page
        shopping_cart_icon = \ 
            self.driver.find_element_by_css_selector
              ("div.header-minicart span.icon")
        shopping_cart_icon.click()

        shopping_cart_status = \ 
             self.driver.find_element_by_css_selector
               ("p.empty").text
        self.assertEqual("You have no items in your shopping cart.", shopping_cart_status)

        close_button =  self.driver.find_element_by_css_selector
          ("div.minicart-wrapper a.close")
        close_button.click()

    @classmethod
    def tearDown(cls):
        # close the browser window
        cls.driver.quit()

    def is_element_present(self, how, what):
        """
        Utility method to check presence of an element on page
        :params how: By locator type
        :params what: locator value
        """
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True

    if __name__ == '__main__':
        unittest.main(verbosity=2)

       我们将用TestSuite类来定义和执行测试套件。我们可以把多个测试加入到一个测试套件中去。除了TestSuite类,我们还可以用TestLoader和TextTestRunner来创建和运行测试套件,举例如下。

import unittest
from searchtests import SearchTests
from homepagetests import HomePageTest

# get all tests from SearchProductTest and HomePageTest class
search_tests = unittest.TestLoader().loadTestsFromTestCase
(SearchTests)
home_page_tests = unittest.TestLoader().loadTestsFromTestCase
(HomePageTest)

# create a test suite combining search_test and home_page_test
smoke_tests = unittest.TestSuite([home_page_tests, search_tests])

# run the suite
unittest.TextTestRunner(verbosity=2).run(smoke_tests)

      使用TestLoader类,我们将得到指定测试文件中的所有测试方法且用于创建测试套件。TestRunner类将通过调用测试套件来执行文件中所有的测试。

你可能感兴趣的:(selenium)