禁止在单元测试django应用时记录错误请求

mzillmmw  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(134)

我在Django应用中进行了一个测试,运行良好,但我想禁用显示控制台日志,如.Bad Request: /api/v1/users/register/
我的一个测试代码

def test_user_register_username_error(self):
        data = {
            'username': 'us',
            'email': 'mail@mail.mail',
            'password': 'pass123123',
            'password_again': 'pass123123'
        }

        url = self.register_url

        response = client.post(url, data=data)

        self.assertEqual(response.status_code, 400)
        self.assertFalse(User.objects.filter(username='us').first())

控制台输出

Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.Bad Request: /api/v1/users/register/
----------------------------------------------------------------------
Ran 1 tests in 0.414s

OK

一切工作正常,但我想禁用Bad Request: /api/v1/users/register/输出到控制台。我仔细检查,没有printlogging函数,可能会记录到控制台。
如何在测试时禁用Bad Request: /api/v1/users/register/日志记录之类的消息

编辑

为了使问题更容易理解,下面是当前的控制台输出:

Found 22 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...........Bad Request: /api/v1/users/register/
.Bad Request: /api/v1/users/register/
.Bad Request: /api/v1/users/register/
.Bad Request: /api/v1/users/register/
.Bad Request: /api/v1/users/register/
..Bad Request: /api/v1/users/register/
.Bad Request: /api/v1/users/activate/
.Bad Request: /api/v1/users/login/
.Bad Request: /api/v1/users/recovery/
Bad Request: /api/v1/users/recovery/
.Bad Request: /api/v1/users/register/
.
----------------------------------------------------------------------
Ran 22 tests in 6.350s

OK

而我所期望的是:

Found 22 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
......................
----------------------------------------------------------------------
Ran 22 tests in 6.350s

OK
zzlelutf

zzlelutf1#

您可以只记录测试期间的错误,并在测试完成后返回正常的日志记录级别。

class SampleTestCase(TestCase):
    def setUp(self) -> None:
        """Reduce the log level to avoid messages like 'bad request'"""
        logger = logging.getLogger('django.request')
        self.previous_level = logger.getEffectiveLevel()
        logger.setLevel(logging.ERROR)

    def tearDown(self) -> None:
        """Reset the log level back to normal"""
        logger = logging.getLogger("django.request")
        logger.setLevel(self.previous_level)

相关问题