Objective
In the previous unittest, the setup can be executed before each execution of the use case, which effectively reduces the amount of code, but there is a drawback, such as opening a browser operation, which is reopened every time the use case is executed, which wastes a lot of time.
So it is possible to open a browser only once, execute the use case and then close it? This requires the use of adorners (@classmethod) to solve.
First, the decoration device
1. Using Setup to differentiate from SetupClass
Setup (): Run before each test case runs
Teardown (): Executes after each test case finishes running
SetupClass (): Must use @classmethod adorner, all case runs only once before running
Teardownclass (): Must use @classmethod adorner, all case runs once after run
[Email protected] is a modifier, Classmethod is a class method in Python
Ii. Order of execution
1. Use the class method to write a few simple case, you can compare this: Selenium2+python automated 52-unittest execution sequence
# Coding:utf-8
Import UnitTest
Import time
Class Test (UnitTest. TestCase):
@classmethod
def setupclass (CLS):
Print "start!"
@classmethod
def teardownclass (CLS):
Time.sleep (1)
Print "end!"
def test01 (self):
Print "Execute test Case 01"
def test03 (self):
Print "Execute test case 03"
def test02 (self):
Print "Execute test case 02"
def addtest (self):
Print "Add Method"
if __name__ = = "__main__":
Unittest.main ()
2. From the execution results it can be seen that the predecessor and the post are executed only once prior to the execution of the use case.
start!
Execute test Case 01
Execute test Case 02
Execute test Case 03
... end!
----------------------------------------------------------------------
Ran 3 Tests in 1.001s
Iii. Examples of Selenium
1. You can put open browser operations in the front SetupClass (CLS), so that you can open a browser, execute multiple case
# Coding:utf-8
From selenium import Webdriver
From Selenium.webdriver.support import expected_conditions as EC
Import UnitTest
Class Bolghome (UnitTest. TestCase):
U ' blog Home page '
@classmethod
def setupclass (CLS):
Cls.driver = Webdriver. Firefox ()
url = "http://www.cnblogs.com/yoyoketang/"
Cls.driver.get (URL)
Cls.driver.implicitly_wait (30)
@classmethod
def teardownclass (CLS):
Cls.driver.quit ()
def test_01 (self):
U ' validation element exists: Blog Park '
Locator = ("id", "blog_nav_sitehome")
Text = u "Blog Park"
result = Ec.text_to_be_present_in_element (locator, text) (Self.driver)
Self.asserttrue (Result)
def test_02 (self):
U ' validation element exists: Home '
Locator = ("id", "blog_nav_myhome")
Text = u "Home"
result = Ec.text_to_be_present_in_element (locator, text) (Self.driver)
Self.asserttrue (Result)
if __name__ = = "__main__":
Unittest.main ()
Selenium2+python Automation 55-unittest (@classmethod)