PyTest初探之—Unittest

 

作者:Daly 出处:http://www.cnblogs.com/daly 欢迎转载,也请保留这段声明。谢谢! 

前段时间研究PyTest框架时,因为PyTest是可以支持Unittest 和 Nose, 也去研究了Unittest和Nose这两个框架。整理记录以便后续查看。

因为给同事做培训都是用的英文资料,所有文章中大部分会引用英文。 

General introduction of unittest

1. Python’s default unittest framework

First unit test framework to be included in Python standard library;

Easy to use by people familiar with the xUnit frameworks;

Strong support for test organization and reuse via test suites.

备注: 默认情况下, Unittest是按照字母顺序执行Test case, 当然可以在TestSuite加载Test Case是组织好顺序

2. Keywords

TestCase: The individual unit of testing.
TestSuite: A collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.
TestLoader: Load the test cases to the test suite.
TestRunner: A component which orchestrates the execution of tests and provides the outcome to the user.
TestFixture: Represents the preparation needed to perform one or more tests, and any associate cleanup actions. setUp(), tearDown(), setUpClass(), tearDownClass()
Decorator: skip, skipIf, skipUnless, expectedFailure

3. Unittest framework

 

4. Assert methods

5. Command line

python -m unittest xxx
python -m unittest -h
python -m unittest discover # discovery the test cases(test*.py) and execute automatically

6. Demo

# unittest_tryout/test_unittest_demo1.py
"""
# @Time     : 6/22/2018 9:14 AM
# @Author   : Daly.You
# @File     : test_unittest_demo1.py
# @Project  : PyTestDemo
# @Python   : 2.7.14
# @Software : PyCharm Community Edition
"""
# !/usr/bin/python
# -*- coding:utf-8 -*-

import os
import time
import unittest
import HTMLTestRunner
from WindowsUpdatesLib import WindowsUpdatesUtilities

class UnitTestSample(unittest.TestCase):
    """Test WindowsUpdatesHelper.py"""
    @classmethod
    def setUpClass(cls):
        """Test WindowsUpdatesUtilities"""
        print "Ran set up class"
    def setUp(self):
        print "befor test"

    def tearDown(self):
        print "end test"

    #@unittest.skip("skip")
    #@unittest.skipIf(0>1, "0>1 skip")
    #@unittest.skipUnless(1>0, "1>0")
    #@unittest.expectedFailure
    def test_a_get_win_info(self):
        """Test method get_win_info"""
        print "test get_win_info"
        win_info = WindowsUpdatesUtilities().get_win_info()
        self.assertEqual(win_info['ProductName'], 'Windows 10 Ent')

    def test_b_is_win10_and_above(self):
        """Test method is_win10_and_above"""
        print "test is_win10_and_above"
        win_info = WindowsUpdatesUtilities().get_win_info()
        is_win10 = 
        WindowsUpdatesUtilities().is_win10_and_above(win_info['ProductName'])
        self.assertEqual(is_win10, True)

    @classmethod
    def test_c_right_click_start_button(cls):
        """Test method right_click_start_button"""
        print "test right_click_start_button"
        WindowsUpdatesUtilities().right_click_start_button()
        time.sleep(2)

    @classmethod
    def test_d_click_context_menu(cls):
        """Test method click_context_menu"""
        print "test click_context_menu"
        WindowsUpdatesUtilities().click_context_menu("Settings")
        time.sleep(2)

    @classmethod
    def test_e_install_updates_via_settingspage(cls):
        print "test install_updates_via_settingspage"
        WindowsUpdatesUtilities().install_updates_via_settingspage()
        time.sleep(2)

    @classmethod
    def test_f_close_windowsupdatesettingspage(cls):
        print "test close_windowsupdatesettingspage"
        WindowsUpdatesUtilities().close_windowsupdatesettingspage()

    @classmethod
    def tearDownClass(cls):
        print "End class"

def test_suite():
    suite_test =  unittest.TestSuite()
    suite_test.addTest(UnitTestSample("test_b_is_win10_and_above"))
    suite_test.addTest(UnitTestSample("test_a_get_win_info"))
    
    '''
    tests = [UnitTestSample("test_a_get_win_info"), 
    UnitTestSample("test_b_is_win10_and_above")]
    suite_test.addTests(tests)
    '''
    return suite_test
if __name__ == '__main__':
    # default
    unittest.main()

    '''
    # HTMLTestRunner
    report_path = "html_report.html"
    fp = file(report_path, 'wb')
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title="UnitTest Test Report", 
    description="UnitTest Test")
    print test_suite()
    runner.run(test_suite())
    fp.close()
    '''

    '''
    # discover test cases
    test_dir = os.path.join(os.getcwd())
    discover = unittest.defaultTestLoader.discover(test_dir, pattern='*unittest_*.py')
    print discover
    runner = unittest.TextTestRunner()
    runner.run(discover)
    '''

执行unittest:

python test_unittest_demo1.py

结果类似如下:

Ran set up class
befor test
test get_win_info
end test
befor test
test is_win10_and_above
end test
befor test
test right_click_start_button
end test
befor test
test click_context_menu
end test
befor test
test install_updates_via_settingspage
exist
timed out
timed out
end test
befor test
test close_windowsupdatesettingspage
end test
End class
======================================================================
FAIL: test_a_get_win_info (__main__.UnitTestSample)
Test method get_win_info
----------------------------------------------------------------------
Traceback (most recent call last):
  File "unittest_tryout/test_unittest_demo1.py", line 39, in test_a_get_win_info
    self.assertEqual(win_info['ProductName'], 'Windows 10 Ent')
AssertionError: u'Windows 10 Pro' != 'Windows 10 Ent'

----------------------------------------------------------------------
Ran 6 tests in 30.683s

FAILED (failures=1)

备注:

1. Discover test cases from folder(python -m unittest discover -s unittest_tryout -v)

2. HTMLTestRunner execute the test cases (python unittest_tryout/test_unittest_demo1.py)

转载于:https://www.cnblogs.com/daly/p/9369867.html

周次模块上午(10:00-12:00)下午(14:00-18:00)实战项目/作业 上午(10:00-12:00) 下午(14:00-18:00) 实战项目/作业 1 Python基础 Python语法基础:变量、数据类型、流程控制 函数、模块、异常处理;文件操作(JSON/CSV) 编写一个文件处理工具,支持JSON/CSV转换 2 Python进阶 面向对象编程:类、继承、多态 常用库:requests, logging, unittest;单元测试实践 实现一个支持日志记录的API请求工具 3 Python测试Pytest框架入门:用例编写、断言、夹具 参数化测试、Allure报告生成;Mock技术 为API工具编写Pytest测试用例并生成报告 4 UI自动化 Selenium基础:元素定位、页面操作 Page Object模式;Pytest集成Selenium 网站登录、搜索功能自动化 5 接口自动化 Requests深度使用:HTTP协议、会话管理 接口测试框架设计:封装请求、数据驱动 搭建接口测试框架,实现登录接口测试 6 接口高级实战 接口安全:OAuth2.0;接口依赖处理 Mock服务(使用Python库);持续集成(GitHub Actions) 实现带Token验证的接口测试 7 接口性能一体化 接口性能测试基础:Locust核心概念 编写Locust性能测试脚本;分布式压测 对接口进行压力测试并生成报告 8 性能测试 性能监控与分析:资源监控、结果分析 性能调优实战;Locust与Prometheus集成 分析性能瓶颈并优化 9 测试开发(上) 测试框架优化:插件机制、配置管理 测试报告定制:Allure二次开发;钉钉/邮件通知 开发一个带通知功能的测试报告插件 10 测试开发(下) 测试工具链:Docker化测试环境 低代码测试平台初探测试数据工厂设计 构建一个测试用例管理平台原型 我这是给0基础的测试同学,的课程内容,但是现在课程要变成12节课,所以得修改下,另外上面的课程10需要改掉,现在这个没懂啥意思,可以构建一个测试用例管理平台没错,但是没看出和10 节课教的东西有什么关联
08-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值