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