怎样快速构建一个完整的Selenium框架

今天跟大家细讲如何构建一个完整的selenium框架,当你学会了这一篇你就也可以说自己会selenium自动化测试了。

1、新建项目,结构如图:

在这里插入图片描述
注意:整个项目除了最外层的是文件夹,其他的都是包(package)。也就是说每一个文件夹下面都是有一个_init _.py文件的。只有包才能顺利的用import导入哦~~

2、文件介绍及代码

baseinfo

这里面只有一个__init __.py文件,里面放的是常量:比如邮件的设置信息、发送的固定URL等。

# coding: utf-8'''
发送邮件参数
'''Smtp_Server = 'smtp.mxhichina.com'Smtp_Sender = 'abc@tenez.cn'Smtp_Sender_Password = '**********'Smtp_Receiver = ['312652826@qq.com', 'warrior_meng08@163.com']

module

这个包下面有:__init __.py(确定它是包而不是文件夹的文件),getTestcase.py——获取测试用例文件;getTestResult.py——获取用例执行结果文件,以及sendEmail.py——发送邮件文件。这个包里放的都是封装好的方法,也就是说以后我们只需要调用这些方法就可以实现相应的功能了。

__init __.py

这个文件里面的内容:

# coding: utf-8import getTestcasesimport sendEmailimport getTestResult

正如大家看到的,这里面只有几个import,这样写是为了后面利用from module import * 这种导入方式,如果不在__init __.py里写这些导入的话,前面的那种导入方式是不能用的。

getTestcase.py

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

    '''
    os.walk()传入顶层文件夹路径,返回三个内容:            1、根路径;            2、路径下所有文件夹名;            3、路径下所有非文件夹名【2,3都是以列表形式返回】
    这个是遍历文件夹,然后遍历对应文件夹下面的文件            
    '''

    # 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

    '''
    事实证明加了文件夹也没关系,但是不能是文件夹,必须是包,也就是你新建的时候必须选package(必须有__init__.py文件)
    '''

    discover = unittest.defaultTestLoader.discover(test_directory, pattern='test*.py', top_level_dir=test_directory)    return discover    

这个方法是读取testcase文件夹(包)里面的测试用例。大家也看到了,一开始我建的就是文件夹,然后怎么样都读不出testcase文件夹下面的文件夹里面的用例,最后我写了一个具体的遍历文件夹的方法,然后去读用例,最后经人指点,加了__init __.py方法,把文件夹变成了包,瞬间就OK了。

getTestResult.py

# coding: utf-8from selenium import webdriverfrom time import sleepdef get_result(filename):
    driver = webdriver.Firefox()
    driver.maximize_window()    # 得到测试报告路径
    result_url = "file://%s" % filename
    driver.get(result_url)
    sleep(3)
    res = driver.find_element_by_xpath("/html/body/div[1]/p[4]").text
    result = res.split(':')
    driver.quit()    return result[-1]    

这个方法是将生成的测试报告对应的测试运行结果拿出来,到时候作为发送邮件的标题发送。

sendEmail.py

# 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')    # 读取测试报告正文
    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自动化测试报告', 'utf-8')
        msg.attach(text)

        now = time.strftime("%Y-%m-%d")
        msg['Subject'] = Header('[ 执行结果:' + result + ' ]'+ 'UI自动化测试报告' + 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

发送邮件的方法,都是一个道理。

test_report

testReport_path.py

# coding: utf-8import os# 获取当前文件夹路径def report_path():
    return os.path.split(os.path.realpath(__file__))[0]

testcase

login

testLogin1.py【测试用例1】

# coding: utf-8from selenium import webdriverimport timeimport unittestimport baseinfoimport sys
reload(sys)
sys.setdefaultencoding('utf8')class TestLogin(unittest.TestCase):

    print '1.这是testLogin1用例打印内容,文件夹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"因未找到对应元素,测试用例未正常执行!")

testLogin2【测试用例2】

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

    def setUp(self):

        print '2.这是testLogin2文件夹下面的setup方法'

    def test11(self):
        return '3.return 方法返回'

    def testLogin(self):
        print 222

testcase2

testBuy.py【测试用例3】

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

    print '4.这是testBuy方法,来自testcase2文件夹'

    def testPrint(self):
        print '5.这是test_1打印的内容,文件夹是testcase2'

testSell.py【测试用例4】

# coding: utf-8print '6.这里只有print--testSell.py文件'

与login和testcase2文件夹同级文件testcase_path.py

# coding: utf-8import os# 获取当前文件夹路径def dir_path():
    return os.path.split(os.path.realpath(__file__))[0]

如果对软件测试、接口测试、自动化测试、面试经验交流感兴趣可以加软件测试交流:313782132 ,会有不定期的发放免费的资料链接,还会有同行一起技术交流。

runtest.py

# coding: utf-8import timefrom module import *from testcase import testcase_pathfrom test_report import testReport_pathfrom HTMLTestRunner import HTMLTestRunnerif __name__ == '__main__':        # 测试用例路径
    test_dir = testcase_path.dir_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自动化测试报告', description='用例执行情况')
    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"邮件发送成功!")    else:
        print(u"邮件发送失败!")    

用例执行这里只有一个方法,其他全是调用module文件夹下面的方法。

大家注意一下我的用例,运之后可以看到输出结果:

在这里插入图片描述
只有1、4、6打印出来了哦,其他的是不会打印的,也就是说你在用例里写的print是不会打印的,这是因为HTMLTestRunner.py规定的。试过自己修改过的可以打印用例里面的print了,但是会返回很多None,也就是说出里面会有好多红色的None。

以上内容希望对你有帮助,有被帮助到的朋友欢迎点赞,评论。

软件测试是IT相关行业中最容易入门的学科~不需要开发人员烧脑的逻辑思维、不需要运维人员24小时的随时待命,需要的是细心认真的态度和IT相关知识点广度的了解,每个测试人员从入行到成为专业大牛的成长路线可划分为:软件测试、自动化测试、测试开发工程师 3个阶段。在这里给大家推荐一个技术交流群 313782132 里面有各种软件测试资料和技术交流。

猜你喜欢

转载自blog.csdn.net/weixin_50271247/article/details/109330795