简体   繁体   中英

What's the equivalent of the php Laravel's "Http::fake()" in Python/ Django / DRF / Pytest?

Laravel's Http:fake() method allows you to instruct the HTTP client to return stubbed / dummy responses when requests are made. How can I achieve the same using Django Rest Framework APIClient in tests?

I tried requests_mock but it didn't yield the result I was expecting. It only mocks requests made within test function and not anywhere else within the application or project you're testing.

When you use pytest-django you can use import the fixture admin_client and then do requests like this:

def test_get_project_list(admin_client):
    resp = admin_client.get("/projects/")
    assert resp.status_code == 200
    resp_json = resp.json()
    assert resp_json == {"some": "thing"}

The equivalent of Laravel's Http::fake() in Django is requests_mock .

  • You must user python requests module to call external apis
  • Then user requests_mock to fake external APIs

The mocker is a loading mechanism to ensure the adapter is correctly in place to intercept calls from requests. Its goal is to provide an interface that is as close to the real requests library interface as possible.

Let me know if you need me to post an example.

You can read more from the requests mock module official website

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM