Python automated testing + unittets framework

Our entire automated reporting process is basically divided into three parts:

1. Preparation of test cases

2. Execution of test cases

3. Output of test report

1. Preparation of test cases:

Then let's use Sougu as a simple use case:

from selenium import webdriver
import unittest
class Case_1(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()#放大浏览器
        self.driver.get("https://www.sogou.com/")
    def test_001(self):
        self.driver.find_element_by_link_text('微信').click()
        self.assertIn(self.driver.title,u'搜狗微信搜索_订阅号及文章内容独家收录,一搜即达')
    def test_002(self):
        self.driver.find_element_by_link_text('新闻').click()
        self.assertIn(self.driver.title,u'搜狗新闻 - 上网从搜狗开始')
    def test_003(self):
        self.driver.find_element_by_link_text('图片').click()
        self.assertIn(self.driver.title,u'搜狗图片-上网从搜狗开始')
    def tearDown(self):
        self.driver.close()
        self.driver.quit()
if __name__ == '__main__':
    unittest.main()
    print('简单的用例')

2-3. Output of use case execution and test report:

import os,time,unittest
import HTMLTestRunner

report_path = os.getcwd()#'F:\Python\Interface_automation'
now = time.strftime('%y-%m-%d %H:%M',time.localtime(time.time()))#获取当前信息并且以前面的格式输出
title = u'搜狗首页链接测试报告'#标题
report_repash = os.path.join(report_path,title + now + '.html')#这里只要是组成一个测试报告路径
print(report_repash)

#导入用例
def case_all():
    case_pash = 'F:\Python\Interface_automation'
    discover = unittest.defaultTestLoader.discover(case_pash,pattern='ceshi*.py')#添加用例,在case_path的路径下,所有以ceshi开头的文件都当做用例文件执行
    return discover

if __name__ == '__main__':
    fp = open(report_repash, "wb") # 保存报告文件
    print(fp)
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                           title=title + ':',)
    runner.run(case_all()) # 执行用例
    fp.close()
'''二、unittest.defaultTestLoader.discover加载测试用例

1.discover方法里面有三个参数:

-case_dir:这个是待执行用例的目录。

-pattern:这个是匹配脚本名称的规则,test*.py意思是匹配test开头的所有脚本。

-top_level_dir:这个是顶层目录的名称,一般默认等于None就行了。

2.discover加载到的用例是一个list集合,需要重新写入到一个list对象testcase里,这样就可以用unittest里面的TextTestRunner这里类的run方法去执行。'''

This is a process of generation-execution-result output of a complete test case. There are three ways to execute the test case:

as follows:

# coding=utf-8
#1.先设置编码,utf-8可支持中英文,如上,一般放在第一行

#2.注释:包括记录创建时间,创建人,项目名称。
'''
Created on 2016-7-27
@author: Jennifer
Project:使用unittest框架编写测试用例思路
'''
#3.导入unittest模块
import unittest

#4.定义测试类,父类为unittest.TestCase。
#可继承unittest.TestCase的方法,如setUp和tearDown方法,不过此方法可以在子类重写,覆盖父类方法。
#可继承unittest.TestCase的各种断言方法。
class Test(unittest.TestCase):

#5.定义setUp()方法用于测试用例执行前的初始化工作。
#注意,所有类中方法的入参为self,定义方法的变量也要“self.变量”
#注意,输入的值为字符型的需要转为int型
    def setUp(self):
        self.number=raw_input('Enter a number:')
        self.number=int(self.number)

#6.定义测试用例,以“test_”开头命名的方法
#注意,方法的入参为self
#可使用unittest.TestCase类下面的各种断言方法用于对测试结果的判断
#可定义多个测试用例
#最重要的就是该部分
    def test_case1(self):
        print(self.number)
        self.assertEqual(self.number,10,msg='Your input is not 10')

    def test_case2(self):
        print(self.number)
        self.assertEqual(self.number,20,msg='Your input is not 20')

    @unittest.skip('暂时跳过用例3的测试')
    def test_case3(self):
        print (self.number)
        self.assertEqual(self.number,30,msg='Your input is not 30')

#7.定义tearDown()方法用于测试用例执行之后的善后工作。
#注意,方法的入参为self
    def tearDown(self):
        print ('Test over')

#8如果直接运行该文件(__name__值为__main__),则执行以下语句,常用于测试脚本是否能够正常运行
if __name__=='__main__':
#8.1执行测试用例方案一如下:
#unittest.main()方法会搜索该模块下所有以test开头的测试用例方法,并自动执行它们。
#执行顺序是命名顺序:先执行test_case1,再执行test_case2
    unittest.main()

'''
#8.2执行测试用例方案二如下:
#8.2.1先构造测试集
#8.2.1.1实例化测试套件
    suite=unittest.TestSuite()
#8.2.1.2将测试用例加载到测试套件中。
#执行顺序是安装加载顺序:先执行test_case2,再执行test_case1
    suite.addTest(Test('test_case2'))
    suite.addTest(Test('test_case1'))
#8.2.2执行测试用例
#8.2.2.1实例化TextTestRunner类
    runner=unittest.TextTestRunner()
#8.2.2.2使用run()方法运行测试套件(即运行测试套件中的所有用例)
    runner.run(suite)
'''

'''
#8.3执行测试用例方案三如下:
#8.3.1构造测试集(简化了方案二中先要创建测试套件然后再依次加载测试用例)
#执行顺序同方案一:执行顺序是命名顺序:先执行test_case1,再执行test_case2
    test_dir = './'
    discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py')
#8.3.2执行测试用例
#8.3.2.1实例化TextTestRunner类
    runner=unittest.TextTestRunner()
#8.3.2.2使用run()方法运行测试套件(即运行测试套件中的所有用例)
    runner.run(discover)
'''

The basic principle of unittest:

  ♦ The entire platform is built using the python unittest testing framework. Here is a brief introduction to the simple application of the unittest module.

  ♦ unittest is python's standard test library, compared to other test frameworks, it is currently the most widely used test framework for python.

  ♦ unittest has four more important concepts: test fixture, test case, test suite, test runner, .

    ♦test fixture: The test fixture is everything we need to have in place to exercise the sut. Simply put, it is to do some things that need to be prepared during the test process, such as creating temporary databases, files and directories, etc., among which setUp() and setDown() are the most commonly used methods

    ♦test case: The base class of the user-defined test case, calling the run() method will call the setUP method, the method of executing the use case, and the tearDown() method in turn.

    ♦test suite: a collection of test cases, you can manually add Test Cases through the addTest() method, or automatically add Test Cases through TestLoader, and TestLoader will have no order when adding test cases.

    ♦test runner: The driving class for running test cases, which can execute TestCase or TestSuite. TestCase and Testsuite will automatically manage TestResult after execution.

Other unitest attributes:

    ♦ unittest.skip() : decorator, when running a test case, some test cases may not be executed, etc., the decorator can be used to temporarily shield the test case. A common usage is, for example, if you want to debug a certain test case, you can use a decorator to block it if you want to block other use cases first.

      @ unittest.skip(reason): skip(reason) decorator: Unconditionally skip the decorated test, and explain the reason for skipping the test.

      @ unittest.skipIf(reason): skipIf(condition,reason) decorator: When the condition is true, skip the decorated test and explain the reason for skipping the test.

      @ unittest.skipUnless(reason): skipUnless(condition,reason) decorator: When the condition is false, skip the decorated test and explain the reason for skipping the test.

      @ unittest.expectedFailure(): The expectedFailure() test is marked as failed.

2. The properties of the TestCase class are as follows:

  ♦setUp() : The setUp() method is used for the initialization work before the execution of the test case. If the test case needs to access the database, you can establish a database connection and initialize it in setUp. If the test case needs to log in to the web, you can instantiate the browser first.

  ♦tearDown() : The tearDown() method is used for the aftermath work after the test case is executed. Such as closing the database connection. Close the browser.

  ♦assert*(): Some assertion methods: In the process of executing the test case, whether the final test case is executed or not is determined by judging whether the actual result obtained by the test is equal to the expected result.

    assertEqual(a,b, [msg='information printed when the test fails']): Assert whether a and b are equal, if they are equal, the test case passes.

    assertNotEqual(a,b, [msg='information printed when the test fails']): Assert whether a and b are equal, if they are not equal, the test case passes.

    assertTrue(x, [msg='information printed when the test fails']): Assert whether x is True, if it is True, the test case passes.

    assertFalse(x, [msg='information printed when the test fails']): Assert whether x is False, if it is False, the test case passes.

    assertIs(a,b, [msg='information printed when the test fails']): Assert whether a is b, if yes, the test case passes.

    assertNotIs(a,b, [msg='information printed when the test fails']): Assert whether a is b, if not, the test case passes.

    assertIsNone(x, [msg='information printed when the test fails']): Assert whether x is None, if it is None, the test case passes.

    assertIsNotNone(x, [msg='information printed when the test fails']): Assert whether x is None, if it is not None, the test case passes.

    assertIn(a,b, [msg='information printed when the test fails']): Assert whether a is in b, if in b, the test case passes.

    assertNotIn(a,b, [msg='information printed when the test fails']): Assert whether a is in b, if not in b, the test case passes.

    assertIsInstance(a,b, [msg='information printed when the test fails']): Assert that a is an instance of b, and if it is, the test case passes.

    assertNotIsInstance(a,b, [msg='information printed when the test fails']): Assert that a is an instance of b, if not, the test case passes.

Through dir(unittest), we can see all the properties and methods of unittest, and their relationship is shown in the figure below.

Unittest main class relationship:

  ♦The process of calling unittest normally is that TestLoader automatically loads the test case TestCase into TestSuite, and TextTestRunner calls the run method of TestSuite, sequentially executes the methods starting with test in the TestCase inside, and obtains the test result TestResult. In the process of executing TestCase, the SetUp() environment preparation is performed first, the test code is executed, and finally tearDown() is used to restore the test.

  ♦The TestCases added by TestLoader are not in order during the loading process. If there are multiple verification methods in a TestCase, they will be executed according to the order of the first letter after the test in the method.

You can manually call the addTest and addTests methods of TestSuite to dynamically add TestCase, which can not only determine the execution order of adding test cases, but also avoid the verification method in TestCase must start with test.

  ♦When building an interface test platform, each time a new interface is created, a TestCase will be automatically generated. When a single interface is selected to run, the TextTestRunner can be used to directly call a single TestCase. When running multiple interfaces, manually add TestCase to TestSuite for TextTestRunner to call and generate test results.

A set of overall process is as follows:

3. The properties of the TestSuite class are as follows: (required when organizing use cases):

  ♦addTest(): The addTest() method is to add the test case to the test suite, as shown below, it is to add the test_baidu test case under the BaiduTest class under the test_baidu module to the test suite.

suite = unittest.TestSuite()
suite.addTest(test_baidu.BaiduTest('test_baidu'))

4. The properties of TextTextRunner are as follows: (required when organizing use cases):

  ♦run(): The run() method is to run the test case of the test suite, and the input parameter is the suite test suite.

runner = unittest.TextTestRunner()
runner.run(suite)

5. The directory structure of unitest is generally as follows: important

Summarize:

Thanks to everyone who read my article carefully! ! !

I personally sorted out some technical materials I have compiled in my software testing career in the past few years, including: e-books, resume modules, various job templates, interview books, self-study projects, etc. Welcome everyone to click on the business card below to get it for free, don't miss it.

 

 

Guess you like

Origin blog.csdn.net/MXB1220/article/details/131860211