当前位置:网站首页>Unittest framework learning (I)

Unittest framework learning (I)

2022-07-23 05:53:00 Jiuxiang_

1.unittest Writing specifications

1.unittest Introduce

unittest, It can also be called PyUnit, Be similar to JUnit, be used for python In the project , Can be used to create a comprehensive test suite , Can be used for unit automation testing ( modular )、 Interface automation testing ( Interface )、 Function automation test (UI) wait .
advantage :1. Support Test Automation , Configure shared and shutdown code tests .
2. Support to aggregate test samples into test set , And separate testing from reporting framework

Official documents :https://docs.python.org/zh-cn/3.7/library/unittest.html#

unittest Have the ability to create test cases 、 test suite 、 Test fixture 、 Test the ability during operation , The components included are as follows :
Test Fixture( Test fixture ): Indicates the preparatory work required to carry out one or more tests , And all the cleaning operations involved . for instance , This may include creating temporary or proxy databases 、 Catalog , Or start a server process .
Test Case( The test case ): A test case is an independent test unit . It checks the response to input specific data .
Test Suite( test suite ): It's a series of test cases , Or test suite , Or both . It's used to archive tests that need to be performed together .
Test Runner( Test runner ): Is a component for executing and outputting test results . This runner may use a graphical interface 、 Text interface , Or return a specific value that represents the result of running the test .

2.unittest Writing specifications

The test module needs to be imported unittest frame
The test class must inherit unittest.TestCase; It is suggested that Test start
The test method must be "test_" start

2.unittest Test frame structure

2.1 setUp() Method

A test case is from setUp() Method started , Use this method to perform some initialization tasks before each test execution . For example, create browser instances , visit URL, Load test data and open Log files, etc . This method has no parameters , No value returned . When defining a setUp() Method , The test actuator executes the test method before each execution .

2.2 teardown() Method

Be similar to setUp() Methods are called before each test method ,TestCase Class will also test the call after execution tearDown() Method to clean up all initialization values . Once the test is performed , stay setUp() The value defined in will no longer be needed , All the best ones are cleaned up when finished .

2.3 setUpClass() Method

You have to use @classmethod Decorator , all case Only run once after running

2.4 tearDownClass() Method

You have to use @classmethod Decorator , all case Only run once after running

2.5 unittest.skip() Decorator

When running use cases , Some use cases may not want to execute etc , You can use the decorator to temporarily shield the test case . A common usage is to debug a test case , If you want to shield other use cases first, you can use decorator shielding .

3.unittest Basic use

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from time import sleep
import unittest

class TestUnit1(unittest.TestCase):
	def setUp(self):
		#1.self  It's a reference to a class / example 
		#2. Definition of global variables :self. Variable name 
		self.browser = webdriver.Chrome()
		#self.browser.maxmize_window()
		self.url = "https://www.baidu.com/"
		self.browser.get(self.url)
		sleep(3)
		
		# Baidu search information 
		# Test case naming :test_
  
	def test_search1(self):
		self.browser.find_element(By.ID,value="kw").send_keys(" The interface test ")
		self.browser.find_element(By.ID,value="su").click()
		sleep(3)
	def test_search2(self):
		self.browser.find_element(By.ID,value="kw").send_keys(" Performance testing ")
		self.browser.find_element(By.ID,value="su").click()
		sleep(3)
	
	def tearDown(self):
		self.browser.quit()
		
if __name__ =="__main__":
	unittest.main()

4. test suite

Test case group formed by organizing test cases under different documents .
Put the test cases that need to be executed at one time , Put it in a kit , You can run it once .

```python
import unittest
from Test import demo1

def creatSuit():
	
	""" 1. The methods that need to be executed in the classes of different test scripts are in a test suite  suit = unittest.TestSuit() suit.addTest(demo1.TestUnit1("test_search1")) """
	
	""" 2. Add all methods in a test class  makeSuite(" Class name ") suit.addTest(unittest.makeSuite("TestUnit1")) """""" """
	3.discover Batch load folder use case 
	discover(case_dir,pattern,top_level_dir)
	@case_dir: The directory of the use cases to be executed 
	@pattern: Rules for matching script names 
	@top_level_dir: The name of the top-level directory , General default None Just go 
	"""
	discover = unittest.defaultTestLoader.discover("./Test",pattern="demo*.py",top_level_dir=None)
	return discover


if __name__=="__main__":
	suit = creatSuit()
	runner = unittest.TextTestRunner()
	runner.run(suit)

3.1 Test case execution sequence

according to test_ The following names are sorted ,0 ~ 9, A ~ Z,a ~ z. If the first letter is the same , Just look at the second letter , Execute sequentially .

3.2 Ignore the execution of test cases

@unittest.skip(“skipping”)
@unittest.skip(reason)
Skip the test decorated by this decorator . reason For the reason that the test was skipped .
@unittest.skipIf(condition, reason)
When condition To true , Skip the decorated test .
@unittest.skipUnless(condition, reason)
Skip the decorated test , Unless condition It's true .
@unittest.expectedFailure
Mark the test as expected failure . If the test fails , Will be considered successful ; If the test passes , It is considered a test failure .
exception unittest.SkipTest(reason)
Throw this exception to skip a test . Generally speaking , You can use TestCase.skipTest() Or one of the decorators that skips the test realizes the function of skipping the test , Instead of directly throwing this exception .
Skipped test setUp() and tearDown() Will not be run . Of the skipped class setUpClass() and tearDownClass() Will not be run . Of the skipped module setUpModule() and tearDownModule() Will not be run .

4. Assertion

Determine whether the actual results are consistent with the expected results in the automated script .
Take Baidu as an example , How to judge whether a query is successful ? The title of the web page is search information , Or an element appears in the page .
assertEqual( Expected results , The actual result ,msg = “ The output content when the actual result is inconsistent with the expected result ”).

MethodChecks that
assertEqual(a, b)a == b
assertNotEqual(a, b)a != b
assertTrue(x)bool(x) is True
assertFalse(x)bool(x) is False
assertIsNot(a, b)a is b
assertEqual(a, b)a is not b
assertIsNone(x)x is None
assertIsNotNone(x)x is not None
assertIn(a, b)a in b
assertNotIn(a, b)a not in b
assertIsInstance(a, b)isinstance(a, b)
assertNotIsInstance(a, b)not isinstance(a, b)
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from time import sleep
import unittest

class TestBaidu(unittest.TestCase):
	def setUp(self):
		self.driver = webdriver.Chrome()
		self.url = "https://www.baidu.com/"
		
		self.driver.get(self.url)
		
		sleep(2)
		
	def test_baidu1(self):
		self.assertTrue(" use Baidu Search , You will know " == self.driver.title, msg=" atypism !!!")
		self.driver.find_element(By.ID,"kw").send_keys("selenium")
		self.driver.find_element(By.ID,"su").submit()
		sleep(3)
		print(self.driver.title)
		self.assertEqual(self.driver.title, "selenium_ Baidu search ", msg=" The actual results are inconsistent with the expected results " )
		sleep(3)
	def tearDown(self):
		self.driver.quit()

if __name__=="__main__":
	unittest.main()
原网站

版权声明
本文为[Jiuxiang_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207221756232940.html