Python接口測試-使用requests模塊發送GET請求


本篇主要記錄下使用python的requests模塊發送GET請求的實現代碼.

向服務器發送get請求:
無參數時:r = requests.get(url)
帶params時:r = requests.get(url,params=params)
帶params和headers時:r = requests.get(url,params=params,headers=headers)

代碼如下:
#coding=utf-8
import unittest
import requests

class GetTest(unittest.TestCase):

    def setUp(self):
        host = 'https://httpbin.org/'
        endpoint = 'get'
        self.url = ''.join([host, endpoint])

    def test1(self):
        u'''get無參數測試'''
        r1 = requests.get(self.url)# 向服務器發送請求
        code = r1.status_code #狀態碼
        self.assertEqual(200,code)
        print(r1.text) # unicode型文本

    def test2(self):
        u'''get帶參數測試'''
        params = {'show_env': '1'}
        r2 = requests.get(self.url,params=params)
        self.assertEqual(200, r2.status_code)

    def test3(self):
        u'''get帶參數、帶headers測試'''
        params = {'show_env': '8'}
        headers = {'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate',
                   'Accept': '*/*','User-Agent': 'python-requests/2.18.3'}
        r = requests.get(self.url, params=params,headers=headers)
        r3 = r.json()
        print(r3)
        connect = r3.get('headers').get('Connection')
        self.assertEqual('close', connect)  #斷言 校驗header里的Connection值

    def tearDown(self):
        pass

if __name__ == "__main__":
    unittest.main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM