Nội dung chính
- Mục lục
- Cài đặt
- Phản đối và con đường di chuyển
- Các tính năng beta
- Ghi lại phản hồi cho các tệp
- Phát lại các phản hồi [đăng ký dân cư] từ các tệp
- Điều cơ bản
- Giao diện chính
- Phím tắt
- Phản hồi với tư cách là người quản lý bối cảnh
- Ngoại lệ là cơ thể phản hồi
- Yêu cầu phù hợp
- URL [STR hoặc Biểu thức chính quy được biên dịch]str or compiled regular expression]
- cơ thể [str hoặc bộ đệm hoặc ngoại lệ]str or BufferedReader or Exception]
- Yêu cầu từ khóa đối số đối diện
- Yêu cầu xác thực dữ liệu nhiều dữ liệu/hình thức
- Yêu cầu xác thực định danh đoạn
- Tạo trình khớp tùy chỉnh
- Đăng ký phản hồi
- Đăng ký mặc định
- Đã đặt hàng đăng ký
- Đăng ký tùy chỉnh
- Phản ứng năng động
- Tích hợp với khung kiểm tra đơn vị
- Phản hồi như một vật cố định nhấtpytest fixture
- Thêm phản hồi mặc định cho mỗi bài kiểm tra
- Phương pháp requestMock: Bắt đầu, dừng lại, đặt lại
- Xác nhận về các câu trả lời được tuyên bố
- Khẳng định số lượng cuộc gọi yêu cầu
- Khẳng định dựa trên đối tượng phản hồiResponse object
- Khẳng định dựa trên url chính xác
- Nhiều câu trả lời
- Chuyển hướng URL
- Xác nhận cơ chế thử lạiRetry mechanism
- Sử dụng một cuộc gọi lại để sửa đổi phản hồi
- Truyền qua các yêu cầu thực
- Xem/sửa đổi các phản hồi đã đăng ký
- Coroutines và đa luồng
- Đóng góp
- Cấu hình môi trường
- Kiểm tra và xác thực chất lượng mã
- Chất lượng mã và phong cách
- Phản hồi của Python là gì?
- Văn bản phản hồi làm gì?
- Làm thế nào để bạn xử lý các câu trả lời trong Python?
Nội dung chính
- Mục lục
- Cài đặt
- Phản đối và con đường di chuyển
- Các tính năng beta
- Ghi lại phản hồi cho các tệp
- Phát lại các phản hồi [đăng ký dân cư] từ các tệp
- Điều cơ bản
- Giao diện chính
- Phím tắt
- Phản hồi với tư cách là người quản lý bối cảnh
- Ngoại lệ là cơ thể phản hồi
- Yêu cầu phù hợp
- URL [STR hoặc Biểu thức chính quy được biên dịch]str or compiled regular expression]
- cơ thể [str hoặc bộ đệm hoặc ngoại lệ]str or BufferedReader or Exception]
- Yêu cầu từ khóa đối số đối diện
- Yêu cầu xác thực dữ liệu nhiều dữ liệu/hình thức
- Yêu cầu xác thực định danh đoạn
- Tạo trình khớp tùy chỉnh
- Đăng ký phản hồi
- Đăng ký mặc định
- Đã đặt hàng đăng ký
- Đăng ký tùy chỉnh
- Phản ứng năng động
- Tích hợp với khung kiểm tra đơn vị
- Phản hồi như một vật cố định nhấtpytest fixture
- Thêm phản hồi mặc định cho mỗi bài kiểm tra
- Phương pháp requestMock: Bắt đầu, dừng lại, đặt lại
- Xác nhận về các câu trả lời được tuyên bố
- Khẳng định số lượng cuộc gọi yêu cầu
- Khẳng định dựa trên đối tượng phản hồiResponse object
- Khẳng định dựa trên url chính xác
- Nhiều câu trả lời
- Chuyển hướng URL
- Xác nhận cơ chế thử lạiRetry mechanism
- Sử dụng một cuộc gọi lại để sửa đổi phản hồi
- Truyền qua các yêu cầu thực
- Xem/sửa đổi các phản hồi đã đăng ký
- Coroutines và đa luồng
- Đóng góp
- Cấu hình môi trường
- Kiểm tra và xác thực chất lượng mã
- Phản hồi của Python là gì?
- Văn bản phản hồi làm gì?
- Làm thế nào để bạn xử lý các câu trả lời trong Python?
- Nội dung thân thể phù hợp
Truy vấn tham số Matcherrequests Python library.
Mục lục
Đóng góp
Mục lục
Đóng góp
Cài đặt
Phản đối và con đường di chuyển
Các tính năng beta
Ghi lại phản hồi cho các tệp
Phát lại các phản hồi [đăng ký dân cư] từ các tệp
Điều cơ bản
Giao diện chính
Phím tắt
Phản hồi với tư cách là người quản lý bối cảnh
Ngoại lệ là cơ thể phản hồi
Ngoại lệ là cơ thể phản hồi
Yêu cầu phù hợp
URL [STR hoặc Biểu thức chính quy được biên dịch]str or compiled regular expression]
cơ thể [str hoặc bộ đệm hoặc ngoại lệ]str or BufferedReader or Exception]
Yêu cầu từ khóa đối số đối diện
cơ thể [str hoặc bộ đệm hoặc ngoại lệ]str or BufferedReader or Exception]
Yêu cầu từ khóa đối số đối diện
Yêu cầu xác thực dữ liệu nhiều dữ liệu/hình thức
Yêu cầu từ khóa đối số đối diện
Yêu cầu xác thực dữ liệu nhiều dữ liệu/hình thức
Yêu cầu xác thực định danh đoạn
Tạo trình khớp tùy chỉnh
Tạo trình khớp tùy chỉnh
Đăng ký phản hồi
Đăng ký mặc định
Đã đặt hàng đăng ký
Đăng ký tùy chỉnh
Phản ứng năng động
Tích hợp với khung kiểm tra đơn vịpytest fixture
Phản hồi như một vật cố định nhấtpytest fixture
Thêm phản hồi mặc định cho mỗi bài kiểm tra
Phương pháp requestMock: Bắt đầu, dừng lại, đặt lại
Xác nhận về các câu trả lời được tuyên bố
Khẳng định số lượng cuộc gọi yêu cầuResponse object
Khẳng định dựa trên đối tượng phản hồiResponse object
Khẳng định dựa trên url chính xác
Nhiều câu trả lời
Chuyển hướng URLRetry mechanism
Xác nhận cơ chế thử lạiRetry mechanism
Sử dụng một cuộc gọi lại để sửa đổi phản hồi
Truyền qua các yêu cầu thực
Xem/sửa đổi các phản hồi đã đăng ký
Coroutines và đa luồng
Đóng góp
Cấu hình môi trường
Kiểm tra và xác thực chất lượng mã
Phản hồi của Python là gì?
Văn bản phản hồi làm gì?
Đóng góp
Làm thế nào để tôi biết loại phản hồi trong Python?
Cài đặt
Một thư viện tiện ích để chế giễu thư viện Python yêu cầu.requests Python library.requests Python library.
Nội dungresponses.json_params_matcher | 0.14.0 | responses.matchers.json_params_matcher |
responses.urlencoded_params_matcher | 0.14.0 | responses.matchers.urlencoded_params_matcher |
Tích hợp với khung kiểm tra đơn vịpytest fixture argument in Response and CallbackResponse argument in Response and CallbackResponse | 0.15.0 | Phản hồi như một vật cố định nhấtstream argument in request directly.stream argument in request directly. |
Khẳng định số lượng cuộc gọi yêu cầuResponse object argument in Response and CallbackResponse. argument in Response and CallbackResponse. | 0.17.0 | Khẳng định dựa trên đối tượng phản hồiresponses.matchers.query_param_matcher or responses.matchers.query_string_matcherresponses.matchers.query_param_matcher or responses.matchers.query_string_matcher |
Chuyển hướng URLRetry mechanism, responses.passthru_prefixes, responses.target, responses.passthru_prefixes, responses.target | 0.20.0 | Xác nhận cơ chế thử lạiresponses.mock.assert_all_requests_are_fired, responses.mock.passthru_prefixes, responses.mock.target instead.responses.mock.assert_all_requests_are_fired, responses.mock.passthru_prefixes, responses.mock.target instead. |
Phản đối và con đường di chuyển
Đóng góp
Các tính năng beta
Bài kiểm tra đơn vịresponses will automatically record the output to the file. Recorded data is stored in toml format.responses will automatically record the output to the file. Recorded data is stored in toml format.
Loại xác thực@responses._recorder.record[file_path="out.toml"] decorator to any function where you perform requests to record responses to out.toml file.@responses._recorder.record[file_path="out.toml"] decorator to any function where you perform requests to record responses to out.toml file.
Điều cơ bản
import requests
from responses import _recorder
def another[]:
rsp = requests.get["//httpstat.us/500"]
rsp = requests.get["//httpstat.us/202"]
@_recorder.record[file_path="out.toml"]
def test_recorder[]:
rsp = requests.get["//httpstat.us/404"]
rsp = requests.get["//httpbin.org/status/wrong"]
another[]
Giao diện chính
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
Ghi lại phản hồi cho các tệp
Chất lượng mã và phong cáchtoml file with recorded responses. [See Record Responses to files to understand how to obtain a file]. To do that you need to execute responses._add_from_file[file_path="out.toml"] within an activated decorator or a context manager.toml file with recorded responses. [See Record Responses to files to understand how to obtain a file]. To do that you need to execute responses._add_from_file[file_path="out.toml"] within an activated decorator or a context manager.
Điều cơ bảnpatch response, then all responses present in out.toml file and a post response at the end.patch response, then all responses present in out.toml file and a post response at the end.patch response, then all responses present in out.toml file and a post response at the end.
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
Phát lại các phản hồi [đăng ký dân cư] từ các tệp
Điều cơ bảnresponses comes from registering mock responses and covering test function with responses.activate decorator. responses provides similar interface as requests.responses comes from registering mock responses and covering test function with responses.activate decorator. responses provides similar interface as requests.responses comes from registering mock responses and covering test function with responses.activate decorator. responses provides similar interface as requests.
Điều cơ bản
Giao diện chínhResponse or Response args] - allows either to register Response object or directly provide arguments of Response object. See Response Parameters
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
Ghi lại phản hồi cho các tệpresponses will raise a ConnectionError:
import responses
import requests
from requests.exceptions import ConnectionError
@responses.activate
def test_simple[]:
with pytest.raises[ConnectionError]:
requests.get["//twitter.com/api/1/foobar"]
Giao diện chính
Ghi lại phản hồi cho các tệpresponses.add[] where method argument is prefilled
Chất lượng mã và phong cáchtoml file with recorded responses. [See Record Responses to files to understand how to obtain a file]. To do that you need to execute responses._add_from_file[file_path="out.toml"] within an activated decorator or a context manager.Response args] - register DELETE response
Điều cơ bảnpatch response, then all responses present in out.toml file and a post response at the end.patch response, then all responses present in out.toml file and a post response at the end.Response args] - register GET response
Phát lại các phản hồi [đăng ký dân cư] từ các tệpResponse args] - register HEAD response
Điều cơ bảnresponses comes from registering mock responses and covering test function with responses.activate decorator. responses provides similar interface as requests.responses comes from registering mock responses and covering test function with responses.activate decorator. responses provides similar interface as requests.Response args] - register OPTIONS response
Giao diện chínhResponse or Response args] - allows either to register Response object or directly provide arguments of Response object. See Response ParametersResponse or Response args] - allows either to register Response object or directly provide arguments of Response object. See Response ParametersResponse args] - register PATCH response
Phím tắtresponses will raise a ConnectionError:responses will raise a ConnectionError:Response args] - register POST response
Phím tắtresponses.add[] where method argument is prefilledresponses.add[] where method argument is prefilledResponse args] - register PUT response
import responses
import requests
@responses.activate
def test_simple[]:
responses.get[
"//twitter.com/api/1/foobar",
json={"type": "get"},
]
responses.post[
"//twitter.com/api/1/foobar",
json={"type": "post"},
]
responses.patch[
"//twitter.com/api/1/foobar",
json={"type": "patch"},
]
resp_get = requests.get["//twitter.com/api/1/foobar"]
resp_post = requests.post["//twitter.com/api/1/foobar"]
resp_patch = requests.patch["//twitter.com/api/1/foobar"]
assert resp_get.json[] == {"type": "get"}
assert resp_post.json[] == {"type": "post"}
assert resp_patch.json[] == {"type": "patch"}
Phản hồi với tư cách là người quản lý bối cảnhResponse args] - register DELETE responseResponse args] - register DELETE response
Tham số phản hồiResponse args] - register GET responseResponse args] - register GET response
import responses
import requests
def test_my_api[]:
with responses.RequestsMock[] as rsps:
rsps.add[
responses.GET,
"//twitter.com/api/1/foobar",
body="{}",
status=200,
content_type="application/json",
]
resp = requests.get["//twitter.com/api/1/foobar"]
assert resp.status_code == 200
# outside the context manager requests will hit the remote server
resp = requests.get["//twitter.com/api/1/foobar"]
resp.status_code == 404
Tham số phản hồiResponse args] - register GET responseResponse args] - register GET response
Ngoại lệ là cơ thể phản hồiResponse args] - register HEAD responseResponse args] - register HEAD response
Yêu cầu phù hợpResponse args] - register OPTIONS responseResponse args] - register OPTIONS responsestr]Nội dung thân thể phù hợpResponse args] - register PATCH responseResponse args] - register PATCH response
Dữ liệu được mã hóa URLResponse args] - register POST responseResponse args] - register POST responsestr or compiled regular expression]Dữ liệu được mã hóa JSONResponse args] - register PUT responseResponse args] - register PUT response
Phím tắtbool]Phản hồi với tư cách là người quản lý bối cảnhresponses.matchers.query_param_matcher or responses.matchers.query_string_matcher
Tham số phản hồi
Ngoại lệ là cơ thể phản hồistr]str]str or BufferedReader or Exception]Yêu cầu phù hợp
URL [STR hoặc Biểu thức chính quy được biên dịch]str or compiled regular expression]str or compiled regular expression]URL tài nguyên đầy đủ.
Match_queryString [Bool]bool]bool]int]Dành: Sử dụng Phản hồi.Matchers.Query_Param_Matcher hoặc Trả lời.Matchers.Query_String_Matcherresponses.matchers.query_param_matcher or responses.matchers.query_string_matcherresponses.matchers.query_param_matcher or responses.matchers.query_string_matcher
Bao gồm chuỗi truy vấn khi các yêu cầu khớp. Được bật theo mặc định nếu URL phản hồi chứa chuỗi truy vấn, bị tắt nếu nó không hoặc URL là biểu thức chính quy.content_type]cơ thể [str hoặc bộ đệm hoặc ngoại lệ]str or BufferedReader or Exception]str or BufferedReader or Exception]text/plain.
Cơ thể phản ứng. Đọc thêm ngoại lệ dưới dạng cơ thể phản hồidict]json
Một đối tượng Python đại diện cho cơ thể phản ứng JSON. Tự động cấu hình loại nội dung thích hợp.bool]Trạng thái [int]int]int]stream argument in request directly
auto_calculation_content_length [bool]bool]bool]Bị vô hiệu hóa theo mặc định. Tự động tính toán độ dài của một chuỗi được cung cấp hoặc thân JSON.
khớp [tuple]tuple]tuple]Một sự lặp lại [tuple được khuyến nghị] của các cuộc gọi lại để phù hợp với các yêu cầu dựa trên các thuộc tính yêu cầu. Mô -đun hiện tại cung cấp nhiều trình kết hợp mà bạn có thể sử dụng để khớp:tuple is recommended] of callbacks to match requests based on request attributes. Current module provides multiple matchers that you can use to match:tuple is recommended] of callbacks to match requests based on request attributes. Current module provides multiple matchers that you can use to match:
Nội dung cơ thể ở định dạng JSON
Nội dung cơ thể ở định dạng dữ liệu được mã hóa URL
Yêu cầu tham số truy vấn
Yêu cầu chuỗi truy vấn [tương tự như tham số truy vấn nhưng lấy chuỗi làm đầu vào]
KWARGS được cung cấp để yêu cầu, ví dụ: Phát trực tuyến, xác minhstream, verifystream, verify
Nội dung và tiêu đề đa dữ liệu hình thức trong các yêu cầu
yêu cầu tiêu đề
yêu cầu định danh đoạn
Ngoài ra, người dùng có thể tạo trình kết hợp tùy chỉnh. Đọc thêm các yêu cầu phù hợp
Ngoại lệ là cơ thể phản hồi
Bạn có thể vượt qua một ngoại lệ khi cơ thể kích hoạt lỗi trên yêu cầu:Exception as the body to trigger an error on the request:Exception as the body to trigger an error on the request:
import responses
import requests
@responses.activate
def test_simple[]:
responses.get["//twitter.com/api/1/foobar", body=Exception["..."]]
with pytest.raises[Exception]:
requests.get["//twitter.com/api/1/foobar"]
Yêu cầu phù hợp
URL [STR hoặc Biểu thức chính quy được biên dịch]str or compiled regular expression]
URL tài nguyên đầy đủ.responses provides matchers for JSON and URL-encoded request bodies.
Match_queryString [Bool]bool]
import responses
import requests
from responses import matchers
@responses.activate
def test_calc_api[]:
responses.post[
url="//calc.com/sum",
body="4",
match=[matchers.urlencoded_params_matcher[{"left": "1", "right": "3"}]],
]
requests.post["//calc.com/sum", data={"left": 1, "right": 3}]
Dành: Sử dụng Phản hồi.Matchers.Query_Param_Matcher hoặc Trả lời.Matchers.Query_String_Matcherresponses.matchers.query_param_matcher or responses.matchers.query_string_matcher
Bao gồm chuỗi truy vấn khi các yêu cầu khớp. Được bật theo mặc định nếu URL phản hồi chứa chuỗi truy vấn, bị tắt nếu nó không hoặc URL là biểu thức chính quy.matchers.json_params_matcher[].
import responses
import requests
from responses import matchers
@responses.activate
def test_calc_api[]:
responses.post[
url="//example.com/",
body="one",
match=[
matchers.json_params_matcher[{"page": {"name": "first", "type": "json"}}]
],
]
resp = requests.request[
"POST",
"//example.com/",
headers={"Content-Type": "application/json"},
json={"page": {"name": "first", "type": "json"}},
]
cơ thể [str hoặc bộ đệm hoặc ngoại lệ]str or BufferedReader or Exception]
Cơ thể phản ứng. Đọc thêm ngoại lệ dưới dạng cơ thể phản hồi
jsonmatchers.query_param_matcher function to match against the params request parameter. Just use the same dictionary as you will use in params argument in request.
Một đối tượng Python đại diện cho cơ thể phản ứng JSON. Tự động cấu hình loại nội dung thích hợp.match_querystring deprecated argument.
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
0Theo mặc định, Matcher sẽ xác nhận rằng tất cả các tham số khớp nghiêm ngặt. Để xác thực rằng chỉ các tham số được chỉ định trong trình kết hợp có mặt trong yêu cầu ban đầu, sử dụng strict_match = false.strict_match=False.strict_match=False.
Truy vấn tham số dưới dạng chuỗi
Thay thế, bạn có thể sử dụng giá trị chuỗi truy vấn trong Matchers.Query_String_Matcher để khớp các tham số truy vấn trong yêu cầu của bạnmatchers.query_string_matcher to match query parameters in your requestmatchers.query_string_matcher to match query parameters in your request
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
1Yêu cầu từ khóa đối số đối diện
Để xác nhận các đối số yêu cầu, sử dụng hàm Matchers.Request_KWARGS_MATCHER để khớp với yêu cầu kwargs.matchers.request_kwargs_matcher function to match against the request kwargs.matchers.request_kwargs_matcher function to match against the request kwargs.
Lưu ý, chỉ các đối số được cung cấp cho Matchers.Request_Kwargs_Matcher sẽ được xác thực.matchers.request_kwargs_matcher will be validated.matchers.request_kwargs_matcher will be validated.
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
2Yêu cầu xác thực dữ liệu nhiều dữ liệu/hình thức
Để xác nhận yêu cầu cơ thể và tiêu đề cho dữ liệu đa dạng/dữ liệu hình thức, bạn có thể sử dụng Matchers.Multipart_Matcher. Các tham số dữ liệu và tệp được cung cấp sẽ được so sánh với yêu cầu:multipart/form-data data you can use matchers.multipart_matcher. The data, and files parameters provided will be compared to the request:multipart/form-data data you can use matchers.multipart_matcher. The data, and files parameters provided will be compared to the request:
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
3Yêu cầu xác thực định danh đoạn
Để xác thực Định danh phân đoạn URL yêu cầu, bạn có thể sử dụng Matchers.Fragment_Identifier_Matcher. Trình kết hợp lấy chuỗi phân đoạn [mọi thứ sau # ký hiệu] làm đầu vào để so sánh:matchers.fragment_identifier_matcher. The matcher takes fragment string [everything after # sign] as input for comparison:matchers.fragment_identifier_matcher. The matcher takes fragment string [everything after # sign] as input for comparison:
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
4Tạo trình khớp tùy chỉnh
Nếu ứng dụng của bạn yêu cầu mã hóa khác hoặc xác thực dữ liệu khác nhau, bạn có thể xây dựng trình khớp của riêng mình trả về tuple [khớp: bool, lý do: str]. Trong đó Boolean biểu thị đúng hoặc sai nếu các tham số yêu cầu khớp và chuỗi là một lý do trong trường hợp lỗi đối sánh. Trình kết hợp của bạn có thể mong đợi một tham số PreadedRequest được cung cấp bởi các phản hồi.Tuple[matches: bool, reason: str]. Where boolean represents True or False if the request parameters match and the string is a reason in case of match failure. Your matcher can expect a PreparedRequest parameter to be provided by responses.Tuple[matches: bool, reason: str]. Where boolean represents True or False if the request parameters match and the string is a reason in case of match failure. Your matcher can expect a PreparedRequest parameter to be provided by responses.
Lưu ý, PreadRequest được tùy chỉnh và có các thuộc tính bổ sung PARAMS và REQ_KWARGS.PreparedRequest is customized and has additional attributes params and req_kwargs.PreparedRequest is customized and has additional attributes params and req_kwargs.
Đăng ký phản hồi
Đăng ký mặc định
Theo mặc định, các phản hồi sẽ tìm kiếm tất cả các đối tượng phản hồi đã đăng ký và trả về một trận đấu. Nếu chỉ có một phản hồi được đăng ký, sổ đăng ký được giữ không thay đổi. Tuy nhiên, nếu nhiều trận đấu được tìm thấy cho cùng một yêu cầu, thì trận đấu đầu tiên được trả về và xóa khỏi sổ đăng ký.responses will search all registered Response objects and return a match. If only one Response is registered, the registry is kept unchanged. However, if multiple matches are found for the same request, then first match is returned and removed from registry.responses will search all registered Response objects and return a match. If only one Response is registered, the registry is kept unchanged. However, if multiple matches are found for the same request, then first match is returned and removed from registry.
Đã đặt hàng đăng ký
Trong một số kịch bản, điều quan trọng là duy trì thứ tự của các yêu cầu và phản hồi. Bạn có thể sử dụng Đăng ký.orderedregistry để buộc tất cả các đối tượng phản hồi phải phụ thuộc vào lệnh chèn và chỉ số gọi. Trong ví dụ sau, chúng tôi thêm nhiều đối tượng phản hồi nhắm vào cùng một URL. Tuy nhiên, bạn có thể thấy, mã trạng thái đó sẽ phụ thuộc vào thứ tự gọi.registries.OrderedRegistry to force all Response objects to be dependent on the insertion order and invocation index. In following example we add multiple Response objects that target the same URL. However, you can see, that status code will depend on the invocation order.registries.OrderedRegistry to force all Response objects to be dependent on the insertion order and invocation index. In following example we add multiple Response objects that target the same URL. However, you can see, that status code will depend on the invocation order.
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
5Đăng ký tùy chỉnh
Các cơ quan đăng ký tích hợp phù hợp cho hầu hết các trường hợp sử dụng, nhưng để xử lý các điều kiện đặc biệt, bạn có thể thực hiện đăng ký tùy chỉnh phải tuân theo giao diện của các cơ quan đăng ký.firstMatchRegistry. Xác định lại phương thức Tìm sẽ cho phép bạn tạo logic tìm kiếm tùy chỉnh và trả về phản hồi thích hợpregistries are suitable for most of use cases, but to handle special conditions, you can implement custom registry which must follow interface of registries.FirstMatchRegistry. Redefining the find method will allow you to create custom search logic and return appropriate Responseregistries are suitable for most of use cases, but to handle special conditions, you can implement custom registry which must follow interface of registries.FirstMatchRegistry. Redefining the find method will allow you to create custom search logic and return appropriate Response
Ví dụ cho thấy cách đặt sổ đăng ký tùy chỉnh
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
6Phản ứng năng động
Bạn có thể sử dụng các cuộc gọi lại để cung cấp các phản hồi động. Cuộc gọi lại phải trả về một tuple [trạng thái, tiêu đề, cơ thể].status, headers, body].status, headers, body].
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
7Bạn cũng có thể chuyển một Regex đã biên dịch cho add_callback để khớp với nhiều URL:add_callback to match multiple urls:add_callback to match multiple urls:
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
8Nếu bạn muốn chuyển các đối số từ khóa bổ sung cho chức năng gọi lại, ví dụ khi sử dụng lại chức năng gọi lại để đưa ra kết quả hơi khác, bạn có thể sử dụng functools.partial:functools.partial:functools.partial:
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/404"
body = "404 Not Found"
status = 404
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpbin.org/status/wrong"
body = "Invalid status code"
status = 400
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/500"
body = "500 Internal Server Error"
status = 500
content_type = "text/plain"
auto_calculate_content_length = false
[[responses]]
[responses.response]
method = "GET"
url = "//httpstat.us/202"
body = "202 Accepted"
status = 202
content_type = "text/plain"
auto_calculate_content_length = false
9Tích hợp với khung kiểm tra đơn vị
Phản hồi như một vật cố định nhấtpytest fixture
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
0Thêm phản hồi mặc định cho mỗi bài kiểm tra
Khi chạy với các bài kiểm tra Unittest, điều này có thể được sử dụng để thiết lập một số phản hồi cấp lớp chung, có thể được bổ sung bởi mỗi bài kiểm tra. Giao diện tương tự có thể được áp dụng trong khung pytest.unittest tests, this can be used to set up some generic class-level responses, that may be complemented by each test. Similar interface could be applied in pytest framework.unittest tests, this can be used to set up some generic class-level responses, that may be complemented by each test. Similar interface could be applied in pytest framework.
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
1Phương pháp requestMock: Bắt đầu, dừng lại, đặt lại
Phản hồi đã bắt đầu, dừng, đặt lại các phương thức rất tương tự như unittest.mock.patch. Chúng làm cho nó đơn giản hơn để thực hiện các yêu cầu chế giễu trong các phương thức thiết lập hoặc nơi bạn muốn thực hiện nhiều bản vá mà không cần trang trí làm tổ hoặc với các câu lệnh. has start, stop, reset methods very analogous to unittest.mock.patch. These make it simpler to do requests mocking in setup methods or where you want to do multiple patches without nesting decorators or with statements. has start, stop, reset methods very analogous to unittest.mock.patch. These make it simpler to do requests mocking in setup methods or where you want to do multiple patches without nesting decorators or with statements.
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
2Xác nhận về các câu trả lời được tuyên bố
Khi được sử dụng làm trình quản lý ngữ cảnh, theo mặc định, các phản hồi sẽ gây ra lỗi xác nhận nếu URL được đăng ký nhưng không được truy cập. Điều này có thể được vô hiệu hóa bằng cách chuyển giá trị ASSERT_ALL_REQUESTS_ARE_FIRED:assert_all_requests_are_fired value:assert_all_requests_are_fired value:assert_all_requests_are_fired value:
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
3Khẳng định số lượng cuộc gọi yêu cầu
Khẳng định dựa trên đối tượng phản hồiResponse object
Mỗi đối tượng phản hồi có thuộc tính CALL_COUNT có thể được kiểm tra để kiểm tra số lần mỗi yêu cầu được khớp.Response object has call_count attribute that could be inspected to check how many times each request was matched.Response object has call_count attribute that could be inspected to check how many times each request was matched.Response object has call_count attribute that could be inspected to check how many times each request was matched.
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
4Khẳng định dựa trên url chính xác
Khẳng định rằng yêu cầu được gọi là chính xác n lần.
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
5Nhiều câu trả lời
Bạn cũng có thể thêm nhiều phản hồi cho cùng một URL:
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
6Chuyển hướng URL
Trong ví dụ sau, bạn có thể thấy cách tạo chuỗi chuyển hướng và thêm ngoại lệ tùy chỉnh sẽ được nêu trong chuỗi thực thi và chứa lịch sử chuyển hướng.
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
7import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
8Xác nhận cơ chế thử lạiRetry mechanism
Nếu bạn đang sử dụng các tính năng thử lại của Urllib3 và muốn bao gồm các tình huống kiểm tra giới hạn thử lại của bạn, bạn cũng có thể kiểm tra các kịch bản đó bằng các phản hồi. Cách tiếp cận tốt nhất sẽ là sử dụng sổ đăng ký được đặt hàngRetry features of urllib3 and want to cover scenarios that test your retry limits, you can test those scenarios with responses as well. The best approach will be to use an Ordered RegistryRetry features of urllib3 and want to cover scenarios that test your retry limits, you can test those scenarios with responses as well. The best approach will be to use an Ordered RegistryRetry features of urllib3 and want to cover scenarios that test your retry limits, you can test those scenarios with responses as well. The best approach will be to use an Ordered Registry
import responses
@responses.activate
def run[]:
responses.patch["//httpbin.org"]
responses._add_from_file[file_path="out.toml"]
responses.post["//httpbin.org/form"]
run[]
9Sử dụng một cuộc gọi lại để sửa đổi phản hồi
Nếu bạn sử dụng xử lý tùy chỉnh trong các yêu cầu thông qua phân lớp/mixin hoặc nếu bạn có các công cụ thư viện tương tác với các yêu cầu ở mức thấp, bạn có thể cần thêm xử lý mở rộng vào đối tượng phản hồi bị chế giễu để mô phỏng đầy đủ môi trường cho các thử nghiệm của bạn. Một phản hồi_callback có thể được sử dụng, sẽ được thư viện bao bọc trước khi được trả lại cho người gọi. Cuộc gọi lại chấp nhận phản hồi vì đối số duy nhất của nó và dự kiến sẽ trả về một đối tượng phản hồi duy nhất.requests via subclassing/mixins, or if you have library tools that interact with requests at a low level, you may need to add extended processing to the mocked Response object to fully simulate the environment for your tests. A response_callback can be used, which will be wrapped by the library before being returned to the caller. The callback accepts a response as it’s single argument, and is expected to return a single response object.requests via subclassing/mixins, or if you have library tools that interact with requests at a low level, you may need to add extended processing to the mocked Response object to fully simulate the environment for your tests. A response_callback can be used, which will be wrapped by the library before being returned to the caller. The callback accepts a response as it’s single argument, and is expected to return a single response object.requests via subclassing/mixins, or if you have library tools that interact with requests at a low level, you may need to add extended processing to the mocked Response object to fully simulate the environment for your tests. A response_callback can be used, which will be wrapped by the library before being returned to the caller. The callback accepts a response as it’s single argument, and is expected to return a single response object.
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
0Truyền qua các yêu cầu thực
Trong một số trường hợp, bạn có thể muốn cho phép các yêu cầu nhất định chuyển qua các phản hồi và nhấn một máy chủ thực. Điều này có thể được thực hiện với các phương thức add_passthru:add_passthru methods:add_passthru methods:add_passthru methods:
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
1Điều này sẽ cho phép bất kỳ yêu cầu nào khớp với tiền tố đó, nếu không thì không được đăng ký dưới dạng phản hồi giả, đối với thông qua bằng cách sử dụng hành vi tiêu chuẩn.
Đi qua các điểm cuối có thể được cấu hình với các mẫu regex nếu bạn cần cho phép toàn bộ miền phụ hoặc con đường dẫn để gửi yêu cầu:
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
2Cuối cùng, bạn có thể sử dụng đối số truyền qua của đối tượng phản hồi để buộc phản hồi để hành xử như một thông qua.passthrough argument of the Response object to force a response to behave as a pass through.passthrough argument of the Response object to force a response to behave as a pass through.passthrough argument of the Response object to force a response to behave as a pass through.
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
3Xem/sửa đổi các phản hồi đã đăng ký
Phản hồi đã đăng ký có sẵn như một phương thức công khai của phiên bản yêu cầu. Đôi khi nó hữu ích cho mục đích gỡ lỗi để xem ngăn xếp các câu trả lời đã đăng ký có thể được truy cập thông qua các câu trả lời. Đã đăng ký [].responses.registered[].responses.registered[].responses.registered[].
Hàm thay thế cho phép thay đổi phản hồi đã đăng ký trước đó. Chữ ký phương pháp giống hệt nhau để thêm. Phản hồi s được xác định bằng phương pháp và URL. Chỉ có phản ứng phù hợp đầu tiên được thay thế.replace function allows a previously registered response to be changed. The method signature is identical to add. response s are identified using method and url. Only the first matched response is replaced.replace function allows a previously registered response to be changed. The method signature is identical to add. response s are identified using method and url. Only the first matched response is replaced.replace function allows a previously registered response to be changed. The method signature is identical to add. response s are identified using method and url. Only the first matched response is replaced.
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
4Hàm UPSERT cho phép thay đổi phản hồi đã đăng ký trước đó như thay thế. Nếu phản hồi được đăng ký, chức năng UPSERT sẽ đăng ký như thêm.upsert function allows a previously registered response to be changed like replace. If the response is registered, the upsert function will registered it like add.upsert function allows a previously registered response to be changed like replace. If the response is registered, the upsert function will registered it like add.upsert function allows a previously registered response to be changed like replace. If the response is registered, the upsert function will registered it like add.
Xóa lấy một đối số phương thức và URL và sẽ xóa tất cả các phản hồi phù hợp khỏi danh sách đã đăng ký. takes a method and url argument and will remove all matched responses from the registered list. takes a method and url argument and will remove all matched responses from the registered list. takes a method and url argument and will remove all matched responses from the registered list.
Cuối cùng, RESET sẽ đặt lại tất cả các phản hồi đã đăng ký.reset will reset all registered responses.reset will reset all registered responses.reset will reset all registered responses.
Coroutines và đa luồng
Phản hồi hỗ trợ cả coroutines và đa luồng ra khỏi hộp. Lưu ý, các phản hồi khóa luồng trên đối tượng requestMock chỉ cho phép một luồng duy nhất truy cập nó. supports both Coroutines and Multithreading out of the box. Note, responses locks threading on RequestMock object allowing only single thread to access it. supports both Coroutines and Multithreading out of the box. Note, responses locks threading on RequestMock object allowing only single thread to access it. supports both Coroutines and Multithreading out of the box. Note, responses locks threading on RequestMock object allowing only single thread to access it.
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
5Đóng góp
Cấu hình môi trường
Các phản hồi sử dụng một số tiện ích LINTING và AUTOFORMATTING, do đó, điều quan trọng là khi gửi các bản vá, bạn sử dụng công cụ thích hợp:
Sao chép kho lưu trữ:
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
6Tạo một môi trường [ví dụ: với VirtualEnv]:virtualenv]:virtualenv]:virtualenv]:
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
7Định cấu hình các yêu cầu phát triển:
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
8Kiểm tra và xác thực chất lượng mã
Cách dễ nhất để xác thực mã của bạn là chạy các bài kiểm tra qua TOX. Cấu hình Tox hiện tại chạy các kiểm tra tương tự được sử dụng trong đường ống CI/CD của GitHub.tox. Current tox configuration runs the same checks that are used in GitHub Actions CI/CD pipeline.tox. Current tox configuration runs the same checks that are used in GitHub Actions CI/CD pipeline.tox. Current tox configuration runs the same checks that are used in GitHub Actions CI/CD pipeline.
Vui lòng thực thi dòng lệnh sau từ gốc dự án để xác thực mã của bạn đối với:
Các bài kiểm tra đơn vị trong tất cả các phiên bản Python được hỗ trợ bởi dự án này
Nhập xác thực thông qua mypymypymypymypy
Tất cả các móc tiền trướcpre-commit hookspre-commit hookspre-commit hooks
import responses
import requests
@responses.activate
def test_simple[]:
# Register via 'Response' object
rsp1 = responses.Response[
method="PUT",
url="//example.com",
]
responses.add[rsp1]
# register via direct arguments
responses.add[
responses.GET,
"//twitter.com/api/1/foobar",
json={"error": "not found"},
status=404,
]
resp = requests.get["//twitter.com/api/1/foobar"]
resp2 = requests.put["//example.com"]
assert resp.json[] == {"error": "not found"}
assert resp.status_code == 404
assert resp2.status_code == 200
assert resp2.request.method == "PUT"
9Ngoài ra, bạn luôn có thể chạy một bài kiểm tra duy nhất. Xem tài liệu dưới đây.
Bài kiểm tra đơn vị
Phản hồi sử dụng pytest để kiểm tra. Bạn có thể chạy tất cả các bài kiểm tra bằng cách:
import responses
import requests
from requests.exceptions import ConnectionError
@responses.activate
def test_simple[]:
with pytest.raises[ConnectionError]:
requests.get["//twitter.com/api/1/foobar"]
0Hoặc kích hoạt thủ công phiên bản cần thiết của python và chạy
import responses
import requests
from requests.exceptions import ConnectionError
@responses.activate
def test_simple[]:
with pytest.raises[ConnectionError]:
requests.get["//twitter.com/api/1/foobar"]
1Và chạy một bài kiểm tra duy nhất bằng cách:
import responses
import requests
from requests.exceptions import ConnectionError
@responses.activate
def test_simple[]:
with pytest.raises[ConnectionError]:
requests.get["//twitter.com/api/1/foobar"]
2Loại xác thực
Để xác minh loại tuân thủ, hãy chạy MyPy Linter:type compliance, run mypy linter:type compliance, run mypy linter:type compliance, run mypy linter:
import responses
import requests
from requests.exceptions import ConnectionError
@responses.activate
def test_simple[]:
with pytest.raises[ConnectionError]:
requests.get["//twitter.com/api/1/foobar"]
3HOẶC
import responses
import requests
from requests.exceptions import ConnectionError
@responses.activate
def test_simple[]:
with pytest.raises[ConnectionError]:
requests.get["//twitter.com/api/1/foobar"]
4Chất lượng mã và phong cách
Để kiểm tra kiểu mã và định dạng lại nó chạy:
import responses
import requests
from requests.exceptions import ConnectionError
@responses.activate
def test_simple[]:
with pytest.raises[ConnectionError]:
requests.get["//twitter.com/api/1/foobar"]
5HOẶC
import responses
import requests
from requests.exceptions import ConnectionError
@responses.activate
def test_simple[]:
with pytest.raises[ConnectionError]:
requests.get["//twitter.com/api/1/foobar"]
6Chất lượng mã và phong cách
Để kiểm tra kiểu mã và định dạng lại nó chạy:. Now, this response object would be used to access certain features such as content, headers, etc.
Để kiểm tra kiểu mã và định dạng lại nó chạy:. Now, this response object would be used to access certain features such as content, headers, etc.
Phản hồi của Python là gì?takes a Response stream and reads it to completion. It returns a promise that resolves with a String .
Bất cứ khi nào chúng tôi đưa ra yêu cầu cho một URI được chỉ định thông qua Python, nó sẽ trả về một đối tượng phản hồi.Bây giờ, đối tượng phản hồi này sẽ được sử dụng để truy cập một số tính năng nhất định như nội dung, tiêu đề, v.v.. Now, this response object would be used to access certain features such as content, headers, etc.takes a Response stream and reads it to completion. It returns a promise that resolves with a String .
Văn bản phản hồi làm gì?. This Response object in terms of python is returned by requests. method[], method being – get, post, put, etc.
Text [] Phương thức văn bản [] của giao diện phản hồi lấy luồng phản hồi và đọc nó để hoàn thành.Nó trả lại một lời hứa giải quyết với một chuỗi.takes a Response stream and reads it to completion. It returns a promise that resolves with a String .. This Response object in terms of python is returned by requests. method[], method being – get, post, put, etc.
Làm thế nào để bạn xử lý các câu trả lời trong Python?look at the Content-Type header on the response, that tells you what the body represents.