search
HomeDatabaseMysql TutorialDetailed explanation of the steps for using unittest test interface in Python

This time I will bring you python a detailed explanation of the steps for using the unittest test interface. What are the precautions for using the unittest test interface in Python? The following is a practical case. Let’s take a look. .

1. First use python requests to test the interface

# TestInface.py 
import requests,json 
url = visit.get_test_url() 
news_url = url+'news.info' 
headers = baseToken.basetoken_datas()['headers'] 
def new_data(data): 
   
  r = requests.post(news_url,data=data,headers=headers) 
  cnn = json.loads(r.text) 
  return cnn

2. Use unittest to call the interface and collect statistics on the results of the interface test

# TestCase.py 
# -*- coding:utf-8 -*- 
import unittest 
import TestInface 
 
 
# 对执行的case结果进行统计 
# --------------------------------------------------------------------------------------------------------------------- 
text = "" 
num_success = 0 
num_fail = 0 
 
 
# 测试通过 
def decide_success(joggle): 
  global num_success 
  num_success += 1 
  print_out(joggle + ":接口测试通过\n") 
  return num_success 
 
 
# 测试不通过 
def decide_fail(txt, joggle): 
  global num_fail 
  num_fail += 1 
  print_out(joggle + ":接口测试未通过 \n错误信息: " + txt + "\n") 
  return num_fail 
 
 
# 邮件内容写入 & 客户端输出 
def print_out(message): 
  global text 
  text += "\n" + message 
  return text 
  
# 返回值判断 
def decide_result(result, code, joggle): 
  if result['code'] == code: 
    decide_success(joggle) 
    return "pass" 
  else: 
    txt = u"期望返回值:" + str(code) + u" 实际返回值:" + str(result) + '\n' + result['message'] 
    decide_fail(txt, joggle) 
    return "fail" 
 
 
def decide_Count(): 
  data = { 
    'num_success': num_success, 
    'num_fail': num_fail, 
    'text': text 
  } 
  return data 
# -------------------------------------------------------------------------------------------------------------------- 
# 定义 unittest 
class MyTestCase(unittest.TestCase):  
 
  # 初始化工作 
  def setUp(self): 
    pass  
 
  # 退出清理工作 
  def tearDown(self): 
    pass 
  def test_Case1(self): 
  id = 16 
    data = {'id':id} 
    a = TestInface.new_data(data) 
    decide_result(a,0,'test_Case1')

3. Use suite Manage cases

# TestSuite.py 
# -*- coding:utf-8 -*- 
import unittest 
import TestCase 
  
def test_InterFace(): 
  
  # 构造测试集 
  suite = unittest.TestSuite() 
  suite.addTest(TestCase("test_Case1")) # unittest中的测试用例 
 
 
  runner = unittest.TextTestRunner() 
  runner.run(suite) 
  # 对测试集进行测试需要返回值 
  # return suite 
 
if name == 'main': 
  
  # unittest.main(defaultTest='test_InterFace') 
  # 执行测试 
  runner = unittest.TextTestRunner() 
  runner.run(test_InterFace())

4. Statistics of interface data

# TestCensus.py 
# -*- coding:utf-8 -*- 
import time 
import TestSuite 
import send_email 
import TestCase 
 
class Test_Calss(): 
 
  def census(self): 
    text = '' 
    # 初始化测试起始时间 
    start_time = time.time() 
    # 调用suite测试集 
    TestSuite.test_InterFace() 
    # 结束执行时间计算 
    end_time = time.time() 
 
    result = TestCase.decide_Count() 
    # 接口测试统计说明 
    total_use_case = u"执行用例总数:" + str(result['num_success'] + result['num_fail']) + \ 
             u"\t通过数:" + str(result['num_success']) + \ 
             u"\t不通过数:" + str(result['num_fail']) 
    total_time = u"\t总共耗时:" + str(round((end_time - start_time), 3)) + u'秒' 
    text = result['text'] + total_use_case + total_time 
    print (text) 
 
    # 发生测试报告邮件 
    send_email.email_file(text) 
 
if name == 'main': 
  Test_Calss().census()

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to convert lists, arrays, and matrices to each other in Python

How to convert matrices in Python Convert to list

The above is the detailed content of Detailed explanation of the steps for using unittest test interface in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

MySQL String Data Types: A Comprehensive GuideMySQL String Data Types: A Comprehensive GuideMay 08, 2025 am 12:14 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,idealforconsistentlengthdatalikecountrycodes;2)VARCHARforvariable-lengthstrings,suitableforfieldslikenames;3)TEXTtypesforlargertext,goodforblogpostsbutcanimpactperformance;4)BINARYandVARB

Mastering MySQL BLOBs: A Step-by-Step TutorialMastering MySQL BLOBs: A Step-by-Step TutorialMay 08, 2025 am 12:01 AM

TomasterMySQLBLOBs,followthesesteps:1)ChoosetheappropriateBLOBtype(TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB)basedondatasize.2)InsertdatausingLOAD_FILEforefficiency.3)Storefilereferencesinsteadoffilestoimproveperformance.4)UseDUMPFILEtoretrieveandsaveBLOBsco

BLOB Data Type in MySQL: A Detailed Overview for DevelopersBLOB Data Type in MySQL: A Detailed Overview for DevelopersMay 07, 2025 pm 05:41 PM

BlobdatatypesinmysqlareusedforvoringLargebinarydatalikeImagesoraudio.1) Useblobtypes (tinyblobtolongblob) Basedondatasizeneeds. 2) Storeblobsin Perplate Petooptimize Performance.3) ConsidersxterNal Storage Forel Blob Romana DatabasesizerIndimprovebackupupe

How to Add Users to MySQL from the Command LineHow to Add Users to MySQL from the Command LineMay 07, 2025 pm 05:01 PM

ToadduserstoMySQLfromthecommandline,loginasroot,thenuseCREATEUSER'username'@'host'IDENTIFIEDBY'password';tocreateanewuser.GrantpermissionswithGRANTALLPRIVILEGESONdatabase.*TO'username'@'host';anduseFLUSHPRIVILEGES;toapplychanges.Alwaysusestrongpasswo

What Are the Different String Data Types in MySQL? A Detailed OverviewWhat Are the Different String Data Types in MySQL? A Detailed OverviewMay 07, 2025 pm 03:33 PM

MySQLofferseightstringdatatypes:CHAR,VARCHAR,BINARY,VARBINARY,BLOB,TEXT,ENUM,andSET.1)CHARisfixed-length,idealforconsistentdatalikecountrycodes.2)VARCHARisvariable-length,efficientforvaryingdatalikenames.3)BINARYandVARBINARYstorebinarydata,similartoC

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.