Как тестировать кроме как с помощью pytest и покрытия в django?
Здравствуйте, надеюсь, у вас все отлично. Здесь я хочу перетащить атрибут под названием file_validator_error_message из настроек Django, как написать тест используя Pytest тест, который действителен для покрытия .
try:
# Get Error Message From Django Setting
ERROR_MESSAGE = settings.FILE_VALIDATOR_ERROR_MESSAGE
except AttributeError:
ERROR_MESSAGE = "{file} is not valid"
except ImproperlyConfigured:
ERROR_MESSAGE = "{file} is not valid"
Как написать тестовый код для этой части?
Похоже, вы спрашиваете, как проверить, что исключение поднимается, когда оно должно быть поднято, и что исключение ведет себя так, как ожидается - Если это действительно то, о чем вы спрашиваете, следующий код/пример должен проиллюстрировать, как это сделать.
Если вы спрашиваете о чем-то другом, не могли бы вы точно указать, что вы пытаетесь сделать и каким должно быть результирующее поведение?
import pytest
# Here's an example function that sums two integers, and if both arguments are
# not integers, raises the TypeError exception with a custom error message.
def add_2_integers_with_custom_exception(a: int, b: int) -> int:
# Check if both arguments are integers
if isinstance(a, int) and isinstance(b, int):
# If both, return their sum
return a + b
else:
# Otherwise raise this exception:
raise TypeError(f'"a" ({a}) and "b" ({b}) must be integers!')
# This test checks that it works correctly when given two integers.
def test_sums_correctly():
assert add_2_integers_with_custom_exception(3, 4) == 7
# This test checks that when passed a non-integer argument, two things happen:
# An exception is raised
# The exception message is as expected
def test_raises_error():
# "with pytest.raises()" verifies that the right exception is raised.
# "as exceptioninfo" catches the message that's returned by the exception
# and stores it in the variable named "exceptioninfo"
with pytest.raises(TypeError) as exceptioninfo:
# Here we check only that the exception is raised.
add_2_integers_with_custom_exception(3, 4.0)
# If the exception was correctly raised within the "with" block, we now
# take the "value" attribute of the "exceptioninfo" object, convert it to
# a string with str(), and then check that the resulting string is precisely
# as expected.
assert str(exceptioninfo.value) == '"a" (3) and "b" (4.0) must be integers!'
# Here we run our two tests
test_sums_correctly()
test_raises_error()
# And both tests pass.