Simple Selenium Automated test framework (Python)

Source: Internet
Author: User
Tags xpath

Recent free time in exploring selenium's automated testing, simply wrote a small framework to test a company's web product. The framework includes the following modules:

1. Test Case Authoring Mode (page mode, refer to previous post http://www.cnblogs.com/AlwinXu/p/5537955.html)

2. Test Case management and execution (mainly with nose)

The module uses an external TXT file to record test cases, each use case is its own file name, and if you do not need to do this, simply add a "#" identifier before the file name to skip the execution of the use case.

3. Test report generation (XML and HTML two formats)

For automated testing, these modules should be the most basic configuration, of course, there are some auxiliary modules such as logs, and other common library modules need to be based on the specific business gradually enriched. Talk less, communicate with the code.

Test Case Writing

This module uses the page mode, previously introduced, this time only paste the code

basepage.py:

__author__ = ' Xua ' #super classclass basepage (object):    def __init__ (self, driver):        self.driver = Driver

Then the individual Web page inherits basepage,loginpage.py:

From basepage import basepagefrom selenium.webdriver.common.by import byfrom selenium.webdriver.common.keys Import    Keysclass LoginPage (basepage): "" "Description of Class" "" "#page element identifier Usename = (by.id, ' username ') Password = (by.id, ' password ') DialogTitle = (By.xpath, '//html/body/div[7]/div/div/div[1]/h3 ') CancelButton = (by. XPATH, '//html/body/div[7]/div/div/div[3]/button[2] ') #Get username textbox and input username def set_username (self,  Username): name = Self.driver.find_element (*loginpage.usename) Name.send_keys (username) #Get Password TextBox and input password, then hits return def set_password (self, password): pwd = Self.driver.find_element (*l         Oginpage.password) Pwd.send_keys (password + keys.return) #Get pop up dialog title Def get_diaglogtitle (self): Digtitle = Self.driver.find_element (*loginpage.dialogtitle) return digtitle.text #Get "Cancel" button an D then click Def click_canceL (self): cancelbtn = Self.driver.find_element (*loginpage.cancelbutton) Cancelbtn.click () 

Test Case Information Class:

testcaseinfo.py

Class Testcaseinfo (object): "" "Description of Class" ""    def __init__ (self, id= "", Name= "", owner= "", result= " Failed ", Starttime=" ", Endtime=" ", Errorinfo=" "):        self.id = id        self.name = name        Self.owner = owner        Self.result = result        Self.starttime = starttime        self.endtime = endtime        self.errorinfo = errorinfo

Finally, each test case is written: (each use case must have its own use case information, there are id,name, and so on, but also call the test Results report generation module to add test results)

test_login.py

__author__ = ' Xua ' from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom Selenium.webdriver.common.alert import alertimport unittestimport timefrom loginpage import Loginpagefrom testcaseinfo Import testcaseinfofrom testreport import Testreportclass test_login (unittest. TestCase): #Setup def Setup (self): Self.driver = Webdriver. Chrome (R ' C:\Users\xua\Downloads\chromedriver_win32\chromedriver.exe ') self.driver.implicitly_wait (self.b) Ase_url = "Http://10.222.30.145:9000/" #test case Information self.testcaseinfo = Testcaseinfo (id= "3", name= "        Login to Floor manager Lite using Sbxadmin ", owner=" Xua ") Self.testresult = Testreport () def test_login (self): Try:self.testcaseinfo.starttime = str (time.asctime ()) #Step1: Open Base site Self . Driver.get (Self.base_url) #Step2: Open Login page login_page = LoginPage (self.driver) #S Tep3:enter username           Login_page.set_username ("Sbxadmin") #Step4: Enter password Login_page.set_password ("Igtte St1 ") #Checkpoint1: Check Popup Dialog Title self.assertequal (Login_page.get_diaglogtitle ()," sign in  "," not Equal ") #Step5: Cancel Dialog login_page.click_cancel () Self.testcaseinfo.result = "Pass" except Exception as Err:self.testcaseinfo.errorinfo = str (err) finally:self. Testcaseinfo.endtime = str (time.asctime ()) #tearDown def tearDown (self): Self.driver.close () #write te St result Self.testResult.WriteHTML (self.testcaseinfo) If __name__ = = "__main__": Unittest.main ()
Use Case Execution Module

1. Use external files to record the cases that need to be executed

Testcases.txt (use cases marked with "#" will not be executed):

test_login.pytest_login_2.py#test_login_3.pytest_login_4.py

2. Use nose's nosetests command to execute each use case:

Import Subprocessclass runtests (object): "" "Description of Class" ""    def __init__ (self):        Self.testcaselistfile = "Testcases.txt"        #use nosetests command to the Execute test case list    def loadandruntestcases (self):        f = open (Self.testcaselistfile)        testfiles = [test to test in F.readlines () if not Test.startswith ("#")]< C9/>f.close ()        for item in TestFiles:            subprocess.call ("nosetests" +STR (item). replace ("\\n", ""), Shell = True if __name__ = = "__main__":    Newrun = runtests ()    Newrun. Loadandruntestcases ()
Test Results Report Generation module

The test report module is written in two formats: XML and HTML

testreport.py

From Xml.etree import ElementTree as Etimport osimport lxml.etree as Mytreefrom lxml import Htmlclass Testreport (object): "" "Description of Class" "" Def __init__ (self): Self.testreport = "Testresult.xml" #If there is no "testres            Ult.xml ", then create one def createtestresultfile (self): if os.path.exists (self.testreport) = = False: Newelem = ET. Element ("testcases") NewTree = ET.  ElementTree (Newelem) newtree.write (self.testreport) #Write test result to XML def Writeresult (self,testcaseinfo): self. Createtestresultfile () Testresultfile = Et.parse (self.testreport) root = Testresultfile.getroot () New Elem = ET.            Element ("TestCase") Newelem.attrib = {"ID": Testcaseinfo.id, "Name": Testcaseinfo.name,            "Owner": Testcaseinfo.owner, "Result": Testcaseinfo.result, "StartTime": Testcaseinfo.starttime, "EndTime": TestcaseinfO.endtime, "ErrorInfo": Testcaseinfo.errorinfo} root.append (Newelem) TESTRESULTFILE.WR ITE (Self.testreport) #If There is no "testresult.html" file exists and then create one with default style def createhtm Lfile (self): if os.path.exists ("testresult.html") = = = False:f = Open ("testresult.html", ' W ') m                Essage = "" "

OK, last look at the generated test report:

Summarize

There are many on the internet on the Selenium automation best practice, of course, we can also according to their own needs to DIY their own framework, whether simple or not, easy to use is the hard truth:)!

Simple Selenium Automated test framework (Python)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.