vishalanandl177 / DRF-API-Logger

An API Logger for your Django Rest Framework project.
https://github.com/vishalanandl177/DRF-API-Logger
Apache License 2.0
303 stars 57 forks source link

Guidance on how to test this #80

Closed mrchrisadams closed 6 months ago

mrchrisadams commented 1 year ago

Hi there,

Thank you for making this package. When using it in a recent feature on an open source project, I had a hard time figuring out how to test it reliably.

I think this is because of how by default it spawns a logger thread, that then writes to the database inside the middleware, as outlined below:

https://github.com/vishalanandl177/DRF-API-Logger/blob/master/drf_api_logger/middleware/api_logger_middleware.py#L169-L182

Is there a recommended approach for testing this when using it? I'm happy to contribute some docs for doing so if you can give me some pointers.

You can see the tests I ended up writing here in this PR:

https://github.com/thegreenwebfoundation/admin-portal/pull/500/

This largely revolved around spinning up a live server, which would start the logger thread as part of the usual work, and then visiting various API endpoints with a full HTTP client like requests.

This is a pretty heavyweight approach though, and I see a few other places that might make make more sense, like using a mock in the middleware and so on.

Something like this for example:


@pytest.mark.django_db
def test_request_is_logged(client, mocker):
    mocked_api_logger = mocker.patch(
        "drf_api_logger.start_logger_when_server_starts.LOGGER_THREAD.put_log_data"
    )

    # given: a request has been made to the high traffic endpoint use for most greenchecks
    client.get(reverse("my-api-view-name", )

    # then: we should see an attempt to log the requests
    assert mocked_api_logger.call_count == 1
mrchrisadams commented 1 year ago

Ah, I spent a bit more time looking into thism and there's this PR that demonstrates the mocking approach I describe above.

Would you accept a PR adding a couple of tests along these lines to this project?

https://github.com/thegreenwebfoundation/admin-portal/pull/501