我正在撰寫一個自動化測驗,它使用 3 個檔案helpers.py來存盤注冊功能,test_mails.py在其中執行測驗,并運行檢查串列中 5 封郵件的注冊,login_credentials.py其中存盤 json 字典。test_mails.py使用 unittest 庫和 import mainsing_up函式嘗試通過 api 請求注冊 5 封電子郵件。測驗的目的是檢查系統是否不讓這些郵件通過。但是,當test_mails.py我嘗試使用庫中的方法json或函式時requesrts,sing_up我會遇到這些型別的錯誤。AttributeError: 'function' object has no attribute 'json'. 這也適用于status_codemethod 如何解決呢?這里是檔案:
helpers.py
import json
import requests
def sign_up(data):
with requests.Session() as session:
sign_up = session.post(
f'https://siteexample/api/register',
headers={
'content-type': 'application/json',
},
data=json.dumps(data)
)
print(sign_up.content)
print(sign_up.status_code)
測驗郵件.py
import unittest
import requests
import json
from login_credentials import data, emails_list
from helpers import *
class Mails(unittest.TestCase):
def test_sign_up_public_emails(self):
emails_dict_ls = {}
for email in emails_list:
data_copy = data.copy()
data_copy["email"] = email
emails_dict_ls.update(data_copy)
sign_up(emails_dict_ls)
if 'email' in sign_up.json() and "User with this Email already exists." in
sign_up.json()['email']:
registering = False
else:
registering = True
assert self.assertEqual(sign_up.status_code, 400)
assert sign_up.json()['status_code'] == "NOT_CONFIRMED_EMAIL"
return registering
login_credentials.py
data = {
"company": "Company",
"phone": " 1111111",
"email": "",
"password1": "defaultpassword",
"password2": "defaultpassword",
"terms_agree": True,
"first_name": "TestUser",
"last_name": "One"
}
emails_list = ['[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
]
uj5u.com熱心網友回復:
sign_up在helpers.py的函式中。您必須回傳回應以便.json()可以呼叫它。
此外,您可以使用json=data代替,data=json.dumps(data)因為它已經是 python-requests 的內置函式。
def sign_up(data):
with requests.Session() as session:
response = session.post(
f'https://siteexample/api/register',
headers={
'content-type': 'application/json',
},
json=data
)
return response
在 test_mails.py 中,您只是呼叫函式而不是將值存盤在變數中。
def test_sign_up_public_emails(self):
emails_dict_ls = {}
for email in emails_list:
data_copy = data.copy()
data_copy["email"] = email
emails_dict_ls.update(data_copy)
sign_resp = sign_up(emails_dict_ls)
if 'email' in sign_resp.json()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453632.html
標籤:Python python-3.x 单元测试
