HTTPしたい(httpx

1import httpx
2
3try:
4    r = httpx.get("https://httpbin.org/get")
5    r.raise_for_status()
6    print(f"{r.status_code}: {r.reason_phrase}")
7except Exceptions as e:
8    print(f"error: {e}")

httpxでウェブページのソースを取得できます。 非同期(async)に対応しています。 requestsの操作感と同じなので、移行もしやすいです。

モックしたい(@patch(httpx.get)

 1from unittest.mock import patch
 2
 3@patch("pathlib.Path.write_text")
 4@patch("httpx.get")
 5def test_httpx(mock_get, mock_write):
 6    # テスト用の文字列
 7    text_data = "モックしたテキストデータ"
 8
 9    # response.is_success の返り値をモック
10    # response.text の返り値をモック
11    mock_get.return_value.is_success = True
12    mock_get.return_value.text = text_data
13
14
15    関数(引数)
16    # 内部で requests.get している関数
17    #   response = httpx.get(url="URL", follow_redirects=True)
18    #   p = Path("ファイル名")
19    #   p.write_text(response.text)
20
21    # httpx.get の呼び出しを確認
22    mock_get.assert_called_once_with(url="URL", follow_redirects=True)
23    # Path.write_text の呼び出しを確認
24    mock_write.assert_called_once_with(text_data)

httpx.getでGETリクエストして取得したレスポンス(=テキストデータ)を Path.write_textでファイルに保存する関数のユニットテストのサンプルです。

関数のロジックを確認するためのユニットテストの場合、 実際にGETリクエストを発生させたり、 ファイルを作成したりする必要はありません。

httpx.getpathlib.Path.write_textをモックし、 assert_called_once_with(引数)で、 それぞれの関数が適切な引数で呼び出されたことを確認しています。

リファレンス