• 看到就是赚到!Selenium完整框架——告别2017


    这个框架大家可以拿过去直接用——作为送给大家的元旦礼物——船长对你们简直太好了!

     

            学了这么长时间,又是定位,又是发邮件,还有乱七八糟的unittest,现在时候后把东西用起来了~而且学会了这一篇你就可以说自己会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-8
    
    import getTestcases
    import sendEmail
    import getTestResult

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

            getTestcase.py

     

    # coding: utf-8
    
    import unittest
    import os
    
    def 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-8
    
    from selenium import webdriver
    from time import sleep
    
    def 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-8
    
    import smtplib
    import baseinfoimport time
    from email.mime.multipart
    import MIMEMultipart from email.header import Header from email.mime.text import MIMEText def 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-8
    
    import os
    
    # 获取当前文件夹路径
    
    def report_path():
        return os.path.split(os.path.realpath(__file__))[0]

    testcase

        login

                testLogin1.py【测试用例1】

    # coding: utf-8
    
    from selenium import webdriver
    import timeimport unittest
    import baseinfo
    import 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-8
    
    import unittest
    
    class 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-8
    
    import unittest
    
    class testBuy(unittest.TestCase): print '4.这是testBuy方法,来自testcase2文件夹' def testPrint(self): print '5.这是test_1打印的内容,文件夹是testcase2'

                testSell.py【测试用例4】

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

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

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

    runtest.py    

    # coding: utf-8
    
    import time
    from module import *
    from testcase import testcase_path
    from test_report import testReport_path
    from HTMLTestRunner import HTMLTestRunner
    if __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。如果你能忍受这些None(没有用),那就用船长修改过的HTMLTestRunner.py文件~~怎么修改船长前面介绍过。

            哇,直接可以用的代码啊!!复制过去就能用的框架,看到就是赚到,花两天时间就学会一个可以用的Selenium框架啊,纯粹的福利啊~~~

     

            2017就要过去了,祝大家新年快乐~~船长在这里祝大家在2018年工作顺利、梦想成真!

            感谢大家这么长时间的陪伴~~还有,打赏过船长的朋友在后台回复一下你的QQ号,船长拉你进一个船长的群,只有四个人,不闲聊,只给大家解决问题和发红包,哈哈~~

            再次感谢大家的陪伴和支持!

     

    希望2018善待我们这些努力、善良的人。加油!

     

    We deserves!

    微信公众号搜索“自动化测试实战”或扫描下方二维码添加关注~~~

  • 相关阅读:
    老刘 Yii2 源码学习笔记之 Component 类
    zanphp 初探----安装篇
    php SQL 防注入的一些经验
    基于FPGA的CNN算法移植(五)算法优化方向汇总
    基于FPGA的CNN算法移植(四)地平线等公司的 ADAS 产品
    基于FPGA的CNN算法移植(三)软件算法架构分析
    基于FPGA的CNN算法移植(二)硬件架构
    基于FPGA的CNN算法移植(一)概述
    ubuntu下无法启动vivado SDK的解决办法(二)
    HDMI调试经验分享(二)—— 基于zc706的ADV7511的实现
  • 原文地址:https://www.cnblogs.com/captainmeng/p/8157729.html
Copyright © 2020-2023  润新知