إضافة الحقول الخاصة بك إلى تقرير Pytest

واجهت مهمة تعديل تقرير html عند العمل مع pytest ، ونتيجة لذلك وجدت حلاً مناسبًا لمهمتي ، أريد مشاركته - ربما يكون شخص ما في متناول اليد. * جميع الصور قابلة للنقر




المكونات التالية مطلوبة للتشغيل:
* 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-

هيكل المشروع :
| - test.py (النص البرمجي الرئيسي للاختبار)
| - conftest.py (مكون إضافي محلي يتم فيه تنفيذ نصوص الخطاف)
| - test-1.jpg (ملف صورة)
| - test-2.jpg (ملف باستخدام صورة)

محتويات 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
 


محتويات 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


يتم تعديل التقرير في الملف conftest.py


يتم إنشاء أعمدة جديدة من خلال الدالات: pytest_html_results_table_header (الخلايا) و pytest_html_results_table_row (التقرير والخلايا) :

الرمز
#   
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 )) - إدراج عمود في الجدول تحت _number مع محتويات _name

يتم اعتراض تنفيذ الاختبار وملء تقرير الاختبار من خلال ربط الوظيفة:
def pytest_runtest_makereport (عنصر ، استدعاء) مع الديكور: @ pytest.hookimpl (hookwrapper = True) .

الرمز
# 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


أولئك. عند تنفيذ البرنامج النصي للاختبار ، سيتم تنفيذ وظيفة pytest_runtest_makereport (عنصر ، مكالمة) ، والتي بدورها:

  • report.description = str (item.function .__ doc__) - سيتم تعيين عمود report.description قيمة السمة __doc__ لوظيفة الاختبار ؛
  • report.a = str (item.module.log ['a']) - سيتم تعيين العمود report.a قيمة سجل المتغير العام ['a'] ؛
  • report.b = str (item.module.log ['b']) - سيتم تعيين العمود report.b قيمة سجل المتغير العام ['b'] ؛
  • report.sum = str (item.module.log ['sum']) - سيتم تعيين عمود report.sum قيمة سجل المتغير العام ['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.


يتم نقل المعلمات إلى التقرير من خلال المتغيرات العامة وسمة الدالة __doc__ ؛ أثناء كل اختبار ، يجب علينا إعادة تعريف المتغيرات العامة.

الرمز
#  
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()


لتشغيل الاختبار ، انتقل إلى الدليل باستخدام البرنامج النصي للاختبار وشغّل الأمر:

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

نتيجة الاختبار ، سيتم إنشاء ملف report.html .

نتيجة الفحص:


  1. test_default ()
    الاختبار بالمعلمات الافتراضية:

    الرمز
    def test_default():
    	'''    '''
    	assert True
    



  2. test_1 ()
    يقوم الاختبار بتعيين القيم للمتغيرات العامة والتحقق من نتيجة الجمع.

    الرمز
    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.:


في هذه الحالة ، تم فحص مثال لتمرير المعلمات إلى تقرير من خلال المتغيرات العالمية ، بالنسبة لمهمتي هذا مقبول تمامًا. لكن استخدام المتغيرات العالمية يفرض صعوبات ومشكلات معروفة ، لذا كن حذرًا.

آمل أن تكون هذه المقالة مفيدة لك.

مثال تقرير آخر


All Articles