Menambahkan Bidang Anda ke Laporan Pytest

Menghadapi tugas memodifikasi laporan html ketika bekerja dengan pytest, sebagai hasilnya saya menemukan solusi yang nyaman untuk tugas saya, saya ingin membagikannya - mungkin seseorang akan berguna. * Semua gambar dapat diklik




Komponen berikut ini diperlukan untuk pengoperasian:
* python3 ( Linux: apt-get install python3 ) — Python
* pip3 ( Linux: apt-get install python3-pip ) — Python ( )
* pytest ( Linux: pip3 install pytest ) — framework
* pytest-html ( Linux: pip3 install pytest-html ) — pytest html-

Struktur proyek :
| - test.py (skrip uji utama)
| - conftest.py (Plug-in lokal di mana skrip kait diterapkan)
| - test-1.jpg (File gambar)
| - test-2.jpg (File dengan gambar)

Isi test.py:
import pytest
import base64

#  
log = { 'a':'none', 'b':'none', 'sum':'none' }
log_html = 'none'
log_img = 'none'
log_img_url = 'none'

#    
def set_global_var(a='none',b='none',sum_='none',html='none',img='none',img_url='none'):
	global log, log_html, log_img, log_img_url
	log = { 'a': a, 'b': b, 'sum': sum_ }
	log_html = html
	log_img = img
	log_img_url = img_url

# ,  ,        
@pytest.fixture(scope="function", autouse=True)
def default_global_var():
	set_global_var()

def test_default():
	'''    '''
	assert True

def test_1():
	''' '''
	#  
	a, b = 2, 2
	sum_ = a + b
	#    
	set_global_var( a = a, b = b, sum_ = sum_ )
	# 
	assert sum_ == 4

def test_2():
	''' '''
	#  
	a, b = 3, 3
	sum_ = a + b
	#  html 
	html = '''
	<p>
	  <table border="3" width="100%">
	  <tbody>
	    <tr>
	      <td bgcolor="#D3D3D3"><font color="black"><strong>a</strong></font></td>
	      <td bgcolor="#D3D3D3"><font color="black"><strong>b</strong></font></td>
	      <td bgcolor="#D3D3D3"><font color="black"><strong>sum</strong></font></td>
	    </tr>
	    <tr>
	      <td><font color="black">{0}</font></td>
	      <td><font color="black">{1}</font></td>
	      <td><font color="black">{2}</font></td>
	    </tr>
	  </tbody>
	  </table>
	  </p>
	  '''.format( a, b, sum_ )
	#    
	set_global_var( a = a, b = b, sum_ = sum_, html = html )
	# 
	assert sum_ == 6

def test_3():
	''' '''
	#  
	a, b = 4, 4
	sum_ = a + b
	#     base64
	image = open('test-1.jpg', 'rb')
	image_read = image.read()
	img = base64.encodebytes( image_read ).decode("utf-8")
	#    
	set_global_var( a = a, b = b, sum_ = sum_, img = img )
	# 
	assert sum_ == 8

def test_4():
	''' '''
	#  
	a, b = 5, 5
	sum_ = a + b
	#    url
	img_url = 'test-2.jpg'
	#    
	set_global_var( a = a, b = b, sum_ = sum_, img_url = img_url )
	# 
	assert sum_ == 10

def test_5():
	''' '''
	#  
	a, b = 5, 1
	sum_ = a + b
	#  html 
	html = '<h1> HTML-</h1>'
	#     base64
	image = open('test-1.jpg', 'rb')
	image_read = image.read()
	img = base64.encodebytes( image_read ).decode("utf-8")
	#    url
	img_url = 'test-2.jpg'
	#    
	set_global_var( a = a, b = b, sum_ = sum_, html = html, img = img, img_url = img_url )
	# 
	print ('    ...')
	assert sum_ == 6

#   
@pytest.mark.parametrize("test_a, test_b, test_sum", [(1,2,3), (2,3,5), (4,5,8)])
def test_6(test_a, test_b, test_sum):
	'''  '''
	#  
	a, b = test_a, test_b
	sum_ = a + b
	#    
	set_global_var( a = a, b = b, sum_ = sum_ )
	# 
	assert sum_ == test_sum
 


Isi dari conftest.py:
import pytest
from py.xml import html

#   
def pytest_html_results_table_header(cells):
	cells.insert(1, html.th('description'))		#  1- 
	cells.insert(2, html.th('a'))			#  2- 
	cells.insert(3, html.th('b'))			#  3- 
	cells.insert(4, html.th('sum'))			#  4- 
	cells.pop()

def pytest_html_results_table_row(report, cells):
	cells.insert(1, html.td( report.description ))	#  1-    
	cells.insert(2, html.td( report.a ))		#  2-    
	cells.insert(3, html.td( report.b ))		#  3-    
	cells.insert(4, html.td( report.sum ))		#  4-    
	cells.pop()

# hook       
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
	pytest_html = item.config.pluginmanager.getplugin('html')
	outcome = yield
	report = outcome.get_result()
	#     -     __doc__    
	report.description = str( item.function.__doc__ )
	report.a = str( item.module.log['a'] )
	report.b = str( item.module.log['b'] )
	report.sum = str( item.module.log['sum'] )
	#  html  image    -     
	extra = getattr(report, 'extra', [])
	if report.when == 'call':
		#  html-
		if item.module.log_html != 'none':
			extra.append(pytest_html.extras.html( item.module.log_html ))
		#  img- (    )
		if item.module.log_img != 'none':
			extra.append(pytest_html.extras.image( item.module.log_img, mime_type='image/jpg', extension='jpg' ))
		#  img-  url-
		if item.module.log_img_url != 'none':
			extra.append(pytest_html.extras.image( item.module.log_img_url ))
		report.extra = extra


Modifikasi laporan dibuat di file conftest.py


Membuat kolom baru dilakukan melalui fungsi: pytest_html_results_table_header (sel) dan pytest_html_results_table_row (laporan, sel) :

Kode
#   
def pytest_html_results_table_header(cells):
	cells.insert(1, html.th('description'))		#  1- 
	cells.insert(2, html.th('a'))			#  2- 
	cells.insert(3, html.th('b'))			#  3- 
	cells.insert(4, html.th('sum'))			#  4- 
	cells.pop()

def pytest_html_results_table_row(report, cells):
	cells.insert(1, html.td( report.description ))	#  1-    
	cells.insert(2, html.td( report.a ))		#  2-    
	cells.insert(3, html.td( report.b ))		#  3-    
	cells.insert(4, html.td( report.sum ))		#  4-    
	cells.pop()


  • cells.insert ( _number , html.th ( _name )) - menyisipkan kolom ke dalam tabel di bawah _number dengan konten _name

Intersepsi pelaksanaan uji coba dan pengisian laporan uji dilakukan melalui kait fungsi:
def pytest_runtest_makereport (item, panggilan) dengan dekorator: @ pytest.hookimpl (hookwrapper = True) .

Kode
# hook       
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
	pytest_html = item.config.pluginmanager.getplugin('html')
	outcome = yield
	report = outcome.get_result()
	#     -     __doc__    
	report.description = str( item.function.__doc__ )
	report.a = str( item.module.log['a'] )
	report.b = str( item.module.log['b'] )
	report.sum = str( item.module.log['sum'] )
	#  html  image    -     
	extra = getattr(report, 'extra', [])
	if report.when == 'call':
		#  html-
		if item.module.log_html != 'none':
			extra.append(pytest_html.extras.html( item.module.log_html ))
		#  img- (    )
		if item.module.log_img != 'none':
			extra.append(pytest_html.extras.image( item.module.log_img, mime_type='image/jpg', extension='jpg' ))
		#  img-  url-
		if item.module.log_img_url != 'none':
			extra.append(pytest_html.extras.image( item.module.log_img_url ))
		report.extra = extra


Itu ketika skrip uji dieksekusi, fungsi pytest_runtest_makereport (item, panggilan) akan dieksekusi , yang pada gilirannya:

  • report.description = str (item.function .__ doc__) - kolom report.description akan diberi nilai atribut __doc__ dari fungsi tes;
  • report.a = str (item.module.log ['a']) - kolom report.a akan diberi nilai log variabel global ['a'];
  • report.b = str (item.module.log ['b']) - kolom report.b akan diberi nilai log variabel global ['b'];
  • report.sum = str (item.module.log ['sum']) - kolom report.sum akan diberi nilai log variabel global ['sum'];
  • extra.append(pytest_html.extras.html( item.module.log_html )) — html-, log_html;
  • extra.append(pytest_html.extras.image( item.module.log_img, mime_type='image/jpg', extension='jpg' )) — img-, log_img;
  • extra.append(pytest_html.extras.image( item.module.log_img_url )) — img-, log_img_url.

test.py.


Parameter ditransfer ke laporan melalui variabel global dan atribut fungsi __doc__; selama setiap tes, kita harus mendefinisikan kembali variabel global.

Kode
#  
log = { 'a':'none', 'b':'none', 'sum':'none' }
log_html = 'none'
log_img = 'none'
log_img_url = 'none'


Kami akan memberikan nilai ke variabel global melalui fungsi:

Kode
#    
def set_global_var(a='none',b='none',sum_='none',html='none',img='none',img_url='none'):
	global log, log_html, log_img, log_img_url
	log = { 'a': a, 'b': b, 'sum': sum_ }
	log_html = html
	log_img = img
	log_img_url = img_url


Untuk mereset nilai variabel global secara otomatis dan tidak mengontrolnya di setiap pengujian, kami menggunakan fixture.

Kode
@pytest.fixture(scope="function", autouse=True)
def default_global_var():
	set_global_var()


Untuk menjalankan tes, buka direktori dengan skrip tes dan jalankan perintah:

pytest test.py -v --html=report.html --self-contained-html

Sebagai hasil dari pengujian, file report.html akan dibuat .

Hasil tes:


  1. test_default ()
    Uji dengan parameter default:

    Kode
    def test_default():
    	'''    '''
    	assert True
    



  2. test_1 ()
    Tes ini memberikan nilai ke variabel global dan memeriksa hasil penjumlahan.

    Kode
    def test_1():
    	''' '''
    	#  
    	a, b = 2, 2
    	sum_ = a + b
    	#    
    	set_global_var( a = a, b = b, sum_ = sum_ )
    	# 
    	assert sum_ == 4
    



  3. test_2()

    ( html-) .

    def test_2():
    	''' '''
    	#  
    	a, b = 3, 3
    	sum_ = a + b
    	#  html 
    	html = '''
    	<p>
    	  <table border="3" width="100%">
    	  <tbody>
    	    <tr>
    	      <td bgcolor="#D3D3D3"><font color="black"><strong>a</strong></font></td>
    	      <td bgcolor="#D3D3D3"><font color="black"><strong>b</strong></font></td>
    	      <td bgcolor="#D3D3D3"><font color="black"><strong>sum</strong></font></td>
    	    </tr>
    	    <tr>
    	      <td><font color="black">{0}</font></td>
    	      <td><font color="black">{1}</font></td>
    	      <td><font color="black">{2}</font></td>
    	    </tr>
    	  </tbody>
    	  </table>
    	  </p>
    	  '''.format( a, b, sum_ )
    	#    
    	set_global_var( a = a, b = b, sum_ = sum_, html = html )
    	# 
    	assert sum_ == 6
    



  4. test_3()
    ( img-) .

    def test_3():
    	''' '''
    	#  
    	a, b = 4, 4
    	sum_ = a + b
    	#     base64
    	image = open('test-1.jpg', 'rb')
    	image_read = image.read()
    	img = base64.encodebytes( image_read ).decode("utf-8")
    	#    
    	set_global_var( a = a, b = b, sum_ = sum_, img = img )
    	# 
    	assert sum_ == 8
    




    :


  5. test_4()

    ( img-) .

    def test_4():
    	''' '''
    	#  
    	a, b = 5, 5
    	sum_ = a + b
    	#    url
    	img_url = 'test-2.jpg'
    	#    
    	set_global_var( a = a, b = b, sum_ = sum_, img_url = img_url )
    	# 
    	assert sum_ == 10
    




    :


  6. test_5()

    ( html-, img-) .

    def test_5():
    	''' '''
    	#  
    	a, b = 5, 1
    	sum_ = a + b
    	#  html 
    	html = '<h1> HTML-</h1>'
    	#     base64
    	image = open('test-1.jpg', 'rb')
    	image_read = image.read()
    	img = base64.encodebytes( image_read ).decode("utf-8")
    	#    url
    	img_url = 'test-2.jpg'
    	#    
    	set_global_var( a = a, b = b, sum_ = sum_, html = html, img = img, img_url = img_url )
    	# 
    	print ('    ...')
    	assert sum_ == 6
    



  7. test_6()

    , .

    #

    @pytest.mark.parametrize("test_a, test_b, test_sum", [(1,2,3), (2,3,5), (4,5,8)])
    def test_6(test_a, test_b, test_sum):
    	'''  '''
    	#  
    	a, b = test_a, test_b
    	sum_ = a + b
    	#    
    	set_global_var( a = a, b = b, sum_ = sum_ )
    	# 
    	assert sum_ == test_sum
    




P.S.:


Dalam hal ini, contoh parameter yang diteruskan ke laporan melalui variabel global diperiksa, untuk tugas saya ini cukup dapat diterima. Tetapi penggunaan variabel global memberikan kesulitan dan masalah yang diketahui, jadi berhati-hatilah.

Semoga artikel ini bermanfaat bagi Anda.

Contoh laporan lain


All Articles