程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Take you through Python automated testing (IX) -- Python unittest framework

編輯:Python

Unittest The framework is introduced

Unittest yes python The unit test framework of , It was originally called PyUnit, from java Of junit Evolved .

Unittest Provides test case、test suites、test fixtures、test runnet.

Test case : By inheritance TestCase class , Implementation creation test Quit tests

Test suite: Test Suite , A set of related tests is usually called a test suite , Pass the test suite , Service Organically combine a series of test cases under the same running environment for the same test purpose . The test suite is Determined according to the test objectives of each stage defined in the test plan , That is, there is a test plan first , There are tests later Kit .

test fixtures:setup + test case + teardown The combination of

Unittest structure :

Unittest Detailed explanation framework

The test case

stay unittest It is not clear what test Of class It's a test case , still class Medium test Opening method It's a test case , In the following case , We will test The first method is executed as a test case .

Let's start with a simple case

import unittest
In the use of unittest When the framework , You need to import unittest
class login_test(unittest.TestCase):
Create a test class , Inheritance of such kind unittest Of TestCase.
def setUp(self):
Setup Is the action before the test is executed , This will be done before the use case is executed
Content , Usually used to initialize the environment
self.testa=1039
self.testb=10
def test_login(self):
Tests to be performed 1
self.assertTrue(self.testa == self.testb)
def test_login2(self):
Tests to be performed 2
try:
self.testc=30
self.assertTrue(self.testa == self.testc)
except AssertionError:
self.fail("test is false")
def tearDown(self):
After execution , It is usually used to restore the test environment
print('Test Runner End')
if __name__ == '__main__':
unittest.main()
call unittest The beginning of

In the use of unittest front , You need to import unittest My bag , This package contains unittest Provide All kinds of , Such as :TestCase、TestSuite、TextTestRunner、TestLoader、main wait .

Create a login_test Of class, For testing , Inheritance of such kind TestCase, So that you can use TestCase The method in .

Setup The method is TestCase The method in , Here is rewriting TestCase Of setup Method , The party Method is used to do the operation before test execution , For example, build test data , Open the browser 、 Link database and other operations . Below tearDown In the same way , The difference is that this method is not used to perform the operation after the test execution , For example, off Close the browser , Release database connection operation .

In the middle to test Opening method , Will be used as test cases to execute , When you run the script ,unittest Will automatically load these test Opening method , To perform tests .

Unitest.main Is to call unittest How to execute , Here is the entrance to test execution .

Test Suite

Test suite is also called test set , Also talk about the test suite , Usually a set of test cases , adopt suite can To execute a set of test cases . The following code is for LMD The landing test of , If the login is successful , And get him all 40 Of title, Judge title Whether the results are not consistent with the expected results , If the same , Then the test is successful , Otherwise, the use case execution fails . This case passed suite Realized . The code is as follows :

#coding=utf-8
__author__ = 'Administrator'
import unittest
from selenium import webdriver
import HTMLTestRunner
from selenium.webdriver.support import expected_conditions
class login_test2(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.maximize_window()
def test_login(self):
driver = self.driver
driver.get('http://www.chuangyijia.com/login')
driver.find_element_by_id('email').send_keys('810155067
@qq.com')
driver.find_element_by_id('pwd').send_keys('a654321')
driver.find_element_by_css_selector('#submit').click()
test=expected_conditions.title_is(u' Creationist , Sign in ')
self.assertTrue(test(driver))
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
suite=unittest.TestLoader().loadTestsFromTestCase(login_test2)
unittest.TextTestRunner().run(suite)

In this code , There is no difference between the above content and the previous one , Mainly in the if name==’main’ The content of , This sentence means “Make a script both importable and executable”, The explanation is that the script module you write can be imported into other modules , in addition The module can also execute itself . When trying the code , stay ”if name == ‘main’“ Add some Our debug code , We can let the external module call without executing our debugging code , But if When we want to check the problem , Execute the module file directly , The debug code works properly !

Unittest.TestLoader: The source code is interpreted as “This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite”

This class can be used to load test cases , Load use cases into siuter in , But it needs to be adjusted Use this type of loadTestFromTestCase Method to load the use case , The parameters received by this method are test class , That is to say What we defined above login_test2 The name of the class . This code will put... In the class test The first method is loaded into suiter in .Suiter Variable is used to receive the loaded result .

adopt unittest Call his TextTestRunner Class run Method to execute the test ,run Method Need to put suiter Pass in as a parameter .TextTestRunner Is to display the test results in text form , If you test Failure , The name of the failed test will be displayed , And count the test results .run The method is to run the incoming case Quit suiter.

Assertion

In programming , Usually make some assumptions , Use assertion , To determine whether the result of a code processing is consistent with Your expectations match , If yes, it is True, Otherwise false. In the test , We will also have such needs seek , Perform a test , Give an expected result , To assert whether the actual results do not match the expected results , Not in conformity with Then the test fails , If yes, the execution is successful . stay unittest Of TestCase Provides us with rich assertion operations , The following is a list of commonly used Some assertions of .

assertTrue: Check whether the return value of the expression is true True, The return value type is Boolean .

assertFalse: No, on the contrary , Check whether the return of the expression is false False, Boolean type .

assertEqual(arg1, arg2, msg=None): verification arg1 and arg2 Whether it is equal or not .

assertNotEqual(arg1, arg2, msg=None): verification arg1 and arg2 Whether they are not equal .

assertIs(arg1, arg2, msg=None): verification arg1 and arg2 Is it the same object .

assertIsNot(arg1, arg2, msg=None): verification arg1 and arg2 Whether it is not the same object .

assertIsNone(expr, msg=None): verification expr Is it none, Yes, go back to True.

ssertIsNotNone(expr, msg=None): verification expr Whether it is not none, Yes, go back to True.

assertIn(arg1, arg2, msg=None): verification arg1 Whether in arg2 in , it is then True

assertNotIn(arg1, arg2, msg=None): verification arg1 Not in arg2 In the middle , it is then fail42

Example :

#coding=utf-8
__author__ = 'Administrator'
import unittest
class Test_Asser(unittest.TestCase):
def test_assertTrue(self):
self.assertTrue(5>4)
5>4 Then return to True, Otherwise return to False
def test_assertFalse(self):
self.assertFalse(5<4)
If the expression holds, it returns False, Otherwise return to True
def test_assertEqual(self):
self.assertEqual(u" China ",u" China ")
Two strings are equal , Then return to True, Otherwise return to False
def test_assertNotEqual(self):
self.assertNotEqul(u" China 1",u" China 2")
Two strings are not equal , return True, Otherwise return to false
def test_assertIs(self):
a=10
a=20
self.assertIs(a,a)
a It's a variable , The following is right a Reassign , So it's still an object ,
So back here True, Otherwise return to false.
def test_assertIsNot(self):
a=10
b=20
self.assertIsNot(a,b)
a and b It's two variables , Not belonging to the same object , So back here True,
Otherwise return to False
def test_assertIsNone(self):
a=None
self.assertIsNone(a)
None stay python Is a special null value , That is, it means null value , You can also watch
Shown as an empty object . Give it here a The assignment is None, that a It's an empty object , here
return True, Otherwise return to false
def test_assertIsNotNone(self):
43
c=10
self.assertIsNotNone(c)
Contrary to the above ,c Is a valuable object , Judge here c Is it not for
None, Yes, go back to True, Otherwise return to False.
def test_assertIsIn(self):
text="abcdef"
t='c'
self.assertIn(t,text)
Judge t Is the value of text in , If yes, it returns True, Otherwise return to
False.
def test_assertIsNotIn(self):
text="abcdef"
self.assertNotIn('h',text)
Judge the character h Is it not in text in , If not, return to True, Otherwise return to
false.
if __name__ == '__main__':
unittest.main()

Bi Ran is unittest It's not about these assertions , There are other assertions , The follow-up will slowly join .

Test batch execution

Here are two test cases , First create the target structure :

The main purpose is :Lmd_auto_test

Secondary eye :Lmd_auto_test\test_case

stay test_case There is... In the eye login_auto.py and Release_Creative.py The two script .

Save the following code as login_auto.py

#coding=utf-8
__author__ = 'Administrator'
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
import time
import unittest
class login_test_case(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.maximize_window()
self.driver.get('http://www.chuangyijia.com/login')
def tearDown(self):
self.driver.quit()
def test_login(self):
self.driver.find_element_by_id('email').send_keys('[email protected]
qq.com')
self.driver.find_element_by_id('pwd').send_keys('a654321')
self.driver.find_element_by_id('submit').click()
#self.driver.implicitly_wait(5)
time.sleep(3)
WebDriverWait(self.driver,30).until(expected_conditions.visib
ility_of_element_located((By.CSS_SELECTOR,'.logo')))
print self.driver.title
is_title = expected_conditions.title_is(u' home page - Creationist ')
self.assertTrue(is_title(self.driver))
if __name__ == '__main__':
unittest.main()

The following file is saved as Release_Creative.py

#coding=utf-8
__author__ = 'Administrator'
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.action_chains import
ActionChains
44
import unittest
import sys
import os,time
class release_creat(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.maximize_window()
self.driver.get('http://www.chuangyijia.com/login')
self.driver.find_element_by_id('email').send_keys('[email protected]
qq.com')
self.driver.find_element_by_id('pwd').send_keys('a654321')
self.driver.find_element_by_id('submit').click()
time.sleep(3)
#is_title = expected_conditions.title_is(u' home page - Creationist ')
#self.assertTrue(is_title(self.driver))
def test_release(self):
self.driver.find_element_by_css_selector('.menu >
ul:nth-child(1) > li:nth-child(1) > a:nth-child(1)').click()
self.driver.find_element_by_css_selector('.c01 > a:nthchild(1)').click()
self.driver.find_element_by_name('mobile').send_keys('1943235
923')
self.driver.find_element_by_css_selector('.idea_name').send_k
eys(u" Release Chinese ideas ")
self.driver.find_element_by_id('province').click()
self.driver.find_element_by_xpath('//option[contains(text(),"
jiangsu ")]').click()
self.driver.find_element_by_id('city').click()
self.driver.find_element_by_xpath('//option[contains(text(),"
nanjing ")]').click()
text=u" Pre sale management , The background administrator can modify the time , And can only be modified to
The date of the month , The year and month cannot be modified "
45
self.driver.find_element_by_css_selector('#pForm >
table:nth-child(11) > tbody:nth-child(1) > tr:nth-child(1) >
td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) >
tr:nth-child(6) > td:nth-child(2) > textarea:nthchild(1)').send_keys(text)
self.driver.find_element_by_css_selector('#pForm >
table:nth-child(11) > tbody:nth-child(1) > tr:nth-child(1) >
td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) >
tr:nth-child(7) > td:nth-child(2) > textarea:nthchild(1)').send_keys(u" No problem ....")
self.driver.find_element_by_css_selector('#pForm >
table:nth-child(11) > tbody:nth-child(1) > tr:nth-child(1) >
td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) >
tr:nth-child(8) > td:nth-child(2) > textarea:nthchild(1)').send_keys(u" There is no need to solve ")
self.driver.find_element_by_name('support_end_date').send_key
s('2017-8-18')
time.sleep(2)
self.driver.find_element_by_css_selector('.c_btn').click()
self.driver.find_element_by_css_selector('.c_btn').click()
os.system("H:\\pydj\\Lmd_auto_test\\testjpg.exe")
time.sleep(2)
put2 =
self.driver.find_element_by_css_selector('#upimg_1')
put1 =
self.driver.find_element_by_css_selector('.cy_pic > ul:nthchild(1) > li:nth-child(1) > input:nth-child(3)')
ActionChains(self.driver).move_to_element(put2).perform()
self.driver.find_element_by_css_selector('.cy_pic >
ul:nth-child(1) > li:nth-child(1) > input:nthchild(3)').click()
os.system("H:\\pydj\\Lmd_auto_test\\testjpg.exe")
#self.driver.find_element_by_css_selector('.cy_pic >
46
47
ul:nth-child(1) > li:nth-child(2) > input:nthchild(3)').click()
#os.system("H:\\pydj\\Lmd_auto_test\\testjpg.exe")
self.driver.find_element_by_id('saveBtn').click()
time.sleep(2)
is_exist =
self.driver.find_element_by_css_selector('div.item:nthchild(1) > div:nth-child(2) > a:nth-child(1)')
Creat_Name = is_exist.text
self.assertEqual(Creat_Name,u" Release Chinese ideas ")
#self.assertTrue(is_exist)
if __name__ == '__main__':
unittest.main()

The two files above , One is to test the login function , The other is the use case for testing creative deployment , here Made a simple judgment on the relationship between success and failure , For example, landing , About judging after logging in ,title Whether it is a successful login title, If yes, the execution passes , Otherwise, the execution fails . When creative ideas are developed , After the judgment is submitted , Whether the idea is being developed In the list , And in the first , If it is , Then the execution is successful , Otherwise, the execution fails .

stay test_case Create... In your project __init__.py file , The contents of the document are as follows :

#coding=utf-8
__author__ = 'Administrator'
import login_auto
import Release_Creative

stay Lmd_auto_test Create... Under the project run_test_case.py file , Files are mainly used to implement test_case The test script for this purpose . The contents of the document are as follows :

#coding=utf-8
__author__ = 'Administrator'
# import test_case
import unittest
from test_case import login_auto,Release_Creative
suiter = unittest.TestSuite()
suiter.addTest(unittest.makeSuite(login_auto.login_test_case))
suiter.addTest(unittest.makeSuite(Release_Creative.release_cr
48
eat))
unittest.TextTestRunner().run(suiter)

Finally, thank everyone who reads my article carefully , The following online link is also a very comprehensive one that I spent a few days sorting out , I hope it can also help you in need !

These materials , For those who want to change careers 【 software test 】 For our friends, it should be the most comprehensive and complete war preparation warehouse , This warehouse also accompanied me through the most difficult journey , I hope it can help you ! Everything should be done as soon as possible , Especially in the technology industry , We must improve our technical skills . I hope that's helpful ……

If you don't want to grow up alone , Unable to find the information of the system , The problem is not helped , If you insist on giving up after a few days , You can click the small card below to join our group , We can discuss and exchange , There will be various software testing materials and technical exchanges .

Click the small card at the end of the document to receive it

Typing is not easy , If this article is helpful to you , Click a like, collect a hide and pay attention , Give the author an encouragement . It's also convenient for you to find it quickly next time .

Self study recommendation B Stop video :

Zero basis transition software testing :25 Days from zero basis to software testing post , I finished today , Employment tomorrow .【 Include features / Interface / automation /python automated testing / performance / Test Development 】

Advanced automation testing :2022B The first station is super detailed python Practical course of automated software testing , Prepare for the golden, silver and four job hopping season , After advanced learning, it soared 20K


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved