Quickly build a complete Selenium framework

Today I will talk about how to build a complete selenium framework. When you learn this article, you can also say that you can automate selenium testing.

1. The structure of the new project is as follows:

Note: the whole project is a package, except for the outermost folder. That is to say, there is a "init". Py file under each folder. Only the package can be successfully imported with import~~

2. Document introduction and code


    There is only one "init". Py file, which contains constants, such as the setting information of e-mail, the fixed URL sent, etc.
# coding: utf-8'''
//Send mail parameters
'''Smtp_Server = 'smtp.mxhichina.com'Smtp_Sender = 'abc@tenez.cn'Smtp_Sender_Password = '**********'Smtp_Receiver = ['312652826@qq.com', 'warrior_meng08@163.com'] 


The package is as follows: "init". Py (make sure it is a package rather than a folder file), getTestcase.py -- get the test case file; getTestResult.py -- get the execution result file of the use case, and sendEmail.py -- send mail file. ". This package contains encapsulated methods, that is to say, we only need to call these methods in the future to achieve the corresponding functions.

__init __.py

Contents of this document:

# coding: utf-8import getTestcasesimport sendEmailimport getTestResult

As you can see, there are only a few imports. This is to use the import method from module import * later. If you don't write these imports in init.py, the previous import method can't be used.


# coding: utf-8import unittestimport osdef testcaseDir(test_directory):

    os.walk() passes in the top-level folder path and returns three contents: 1. Root path; 2. All folder names under the path; 3. All non folder names under the path [2,3 are returned in list form]
    This is to traverse the folder, and then traverse the files under the corresponding folder            

    # for a, b, c in os.walk(test_directory):
    #     for dirs in b:
    # test_dir = '%s\%s' % (test_directory, dirs) # test_discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py',  Top ﹣ level ﹣ dir = test ﹣ DIR) ﹣ return test ﹣ discover '' 'it turns out that adding a folder doesn't matter, but it can't be a folder, it must be a package, that is, when you create a new one, you must select package (there must be a ﹣ init ﹣ py file) "' discover = unittest.defaulttestloader.discover (test ﹣ directory, pattern ='test *. Py ', top ﹣ level ﹣ directory = test ﹣ return discover 

This method is to read the test cases in the testcase folder (package). As you can see, at first I built a folder, and then I couldn't read the use cases in the folder under testcase folder. At last, I wrote a specific method to traverse the folder, and then read the use cases. At last, with the help of people, I added "init". PY method, I changed the folder into a package, and it was OK in an instant.


# coding: utf-8from selenium import webdriverfrom time import sleepdef get_result(filename):
    driver = webdriver.Firefox()
    driver.maximize_window()    # Get test report path
    result_url = "file://%s" % filename
    res = driver.find_element_by_xpath("/html/body/div[1]/p[4]").text
    result = res.split(':') driver.quit() return result[-1] 

This method is to take out the test run result corresponding to the generated test report, and then send it as the title of the sent mail.


# coding: utf-8import smtplibimport baseinfoimport timefrom email.mime.multipart import MIMEMultipartfrom email.header import Headerfrom email.mime.text import MIMETextdef send_Mail(file_new, result):
    f = open(file_new, 'rb')    # Read test report body
    mail_body = f.read()
    f.close()    try:
        smtp = smtplib.SMTP(baseinfo.Smtp_Server, 25) sender = baseinfo.Smtp_Sender password = baseinfo.Smtp_Sender_Password receiver = baseinfo.Smtp_Receiver smtp.login(sender, password) msg = MIMEMultipart() text = MIMEText(mail_body, 'html', 'utf-8') text['Subject'] = Header('UI Automated test report', 'utf-8') msg.attach(text) now = time.strftime("%Y-%m-%d") msg['Subject'] = Header('[ Execution result:' + result + ' ]'+ 'UI Automated test report' + now, 'utf-8') msg_file = MIMEText(mail_body, 'html', 'utf-8') msg_file['Content-Type'] = 'application/octet-stream' msg_file["Content-Disposition"] = 'attachment; filename="TestReport.html"' msg.attach(msg_file) msg['From'] = sender msg['To'] = ",".join(receiver) tmp = smtp.sendmail(sender, receiver, msg.as_string()) print tmp smtp.quit() return True except smtplib.SMTPException as e: print(str(e)) return False 

Sending email is the same thing.



# coding: utf-8import os# Get current folder pathdef report_path(): return os.path.split(os.path.realpath(__file__))[0] 



testLogin1.py [test case 1]

# coding: utf-8from selenium import webdriverimport timeimport unittestimport baseinfoimport sys
sys.setdefaultencoding('utf8')class TestLogin(unittest.TestCase): print '1.This is testLogin1 Use case print content, folder login'  @ classmethod def setUpClass(self): self.driver = webdriver.Firefox() time.sleep(1) self.driver.maximize_window() @ classmethod def tearDownClass(self): time.sleep(1) self.driver.quit() def test_purchase(self): print(u"No corresponding element found,Test case does not execute normally!") 

testLogin2 [test case 2]

# coding: utf-8import unittestclass testLogin2(unittest.TestCase):

    def setUp(self): print '2.This is testLogin2 Under folder setup method' def test11(self): return '3.return Method return' def testLogin(self): print 222 


testBuy.py [test case 3]

# coding: utf-8import unittestclass testBuy(unittest.TestCase):

    print '4.This is testBuy Method, from testcase2 folder'

    def testPrint(self): print '5.This is test_1 Printed content, folder is testcase2' 

testSell.py [test case 4]

#coding: utf-8print '6. Here only print--testSell.py file'

Testcase? Path.py

# coding: utf-8import os# Get current folder pathdef dir_path(): return os.path.split(os.path.realpath(__file__))[0] 

If you are interested in software testing, interface testing, automation testing and interview experience, you can add software testing exchange: 1085991341. There will be free information links from time to time, and there will be technical exchanges with peers.


# coding: utf-8import timefrom module import *from testcase import testcase_pathfrom test_report import testReport_pathfrom HTMLTestRunner import HTMLTestRunnerif __name__ == '__main__':        # Test case path
    test_dir = testcase_path.dir_path()    # Test report storage path
    report_dir = testReport_path.report_path()    # print report_dir

    now = time.strftime("%Y-%m-%d")
    filename = report_dir + '\\report-' + now + '.html' # print filename fp = open(filename, 'wb') runner = HTMLTestRunner(stream=fp, title='UI Automated test report', description='Use case execution') runner.run(getTestcases.testcaseDir(test_dir)) fp.close() result = getTestResult.get_result(filename) print result mail = sendEmail.send_Mail(filename, result) if mail: print(u"Email sent successfully!") else: print(u"Failed to send email!") 

There is only one method for use case execution, and the other methods are all called under the module folder.

Please pay attention to my use case. You can see the output result after the operation:

Only 1, 4 and 6 are printed out. The others will not be printed. That is to say, the print you write in the use case will not be printed. This is because of the HTMLTestRunner.py rule. Try to print the print in the use case that you have modified, but it will return a lot of None, that is to say, there will be a lot of red None in it.
The above content hopes to be helpful to you. Friends who have been helped are welcome to like and comment.

Tags: Selenium Firefox

Posted on Mon, 18 May 2020 01:26:49 -0400 by toniknik1982