1

When my methods in a View class are executed by pytest, the logging statements don't produce any outputs on the console. Is that expected behavior or am I missing something?

This is the view:

import logging
from django.views import View
logger = logging.getLogger(__name__)

class FancyWebhook(View):
    def post(self, request, *args, **kwargs):
        logger.info("DUMMY logging")
        print("DUMMY printing")
        return HttpResponse(status=200)

The logging configuration in configs/settings/test.py:

# ...
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "console": {"class": "logging.StreamHandler"},
    },
    "loggers": {
        "django": {
            "handlers": ["console"],
            "level": os.getenv("DJANGO_LOG_LEVEL", "INFO"),
        },
    },
}

The test method:

import pytest
@pytest.mark.django_db
def test_fancy_webook_empty_payload_fails(client):
    print("calling client.post()...")
    response = client.post('/pricing/fancywebhook', {}, content_type='application/json')
    assert response.status_code == 403

Running the test via pytest --ds=config.settings.test only prints the error that assert 301 == 403 to the console, but neither the "DUMMY logging" nor the "DUMMY printing" statements.

I'm surely missing the obvious, am I not?

Windowlicker
  • 498
  • 11
  • 18
  • `assert 301 == 403` - the 301 suggests that the response was a 301 redirect. Should the URL in the test be `'/pricing/fancywebhook/'`? If so, Django is redirecting to add the slash. – Alasdair Sep 21 '20 at 13:24
  • 1
    You have to specify `-s` for the print output and `--log-level=INFO` for logging output or configure it in pytest.ini. – MrBean Bremen Sep 21 '20 at 13:37
  • See [How to print to console in pytest](https://stackoverflow.com/questions/24617397/how-to-print-to-console-in-pytest) and [Pytest logging ignores options in pytest.ini](https://stackoverflow.com/questions/50677656/pytest-logging-ignores-options-in-pytest-ini). – MrBean Bremen Sep 21 '20 at 13:39
  • OK, the `-s` and `--log-level=INFO` did help. I added the latter to my `Makefile`. That's much better now. Thanks, @MrBeanBremen. – Windowlicker Sep 22 '20 at 13:57
  • 1
    Just for the record, @Alasdair is completely right: Adding the `/` at the end of the test URL does prevent the 301 redirect. – Windowlicker Sep 22 '20 at 13:58

0 Answers0