Я новичок в модульном тестировании, так что извините за вопрос newb ie. Я написал небольшой класс с одним атрибутом экземпляра, «name».
Цель здесь состоит в том, чтобы запросить у пользователя ввод, если при создании экземпляра класса не передается параметр «name», и проверить, имя отформатировано, как ожидалось.
Вот определение класса:
class Customer:
def __init__(self, name=None):
self.name = name
@property
def name(self):
return self._name.upper()
@name.setter
def name(self, value):
while True:
try:
if not value:
value = str(input("Please enter the customer's name: "))
else:
print("Customer name found: {}".format(value))
if not bool(re.match("^[A-Za-z0-9 _-]*$", value)) or value == "":
raise (ValueError)
except ValueError:
print("Invalid customer name.")
value = None
continue
break
self._name = value
Он работает, как ожидалось:
>>> customer = Customer()
Please enter the customer's name: &&invalid
Invalid customer name.
Please enter the customer's name: valid
>>> customer.name
'VALID'
>>>
Мой тестовый файл выглядит следующим образом:
import script
import pytest
class TestCustomer:
def setup_method(self):
self.customer = script.Customer("validname")
def teardown_method(self):
self.customer = ""
def test_valid_name(self):
self.customer.name = "validname"
assert self.customer.name == "VALIDNAME"
def test_invalid_name(self):
with pytest.raises(ValueError):
self.customer.name = "&invalidname&"
Однако, когда я пытаюсь проверить это с помощью pytest, происходит следующее:
========================================================================= FAILURES =========================================================================
______________________________________________________________ TestCustomer.test_invalid_name ______________________________________________________________
self = <test_script.TestCustomer object at 0x7f1ad68f39a0>
def test_invalid_name(self):
with pytest.raises(ValueError):
> self.customer.name = "&invalidname&"
test_script.py:18:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
script.py:17: in name
value = str(input("Please enter the customer's name: "))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <_pytest.capture.DontReadFromInput object at 0x7f1ad693d2e0>, args = ()
def read(self, *args):
> raise IOError(
"pytest: reading from stdin while output is captured! Consider using `-s`."
)
E OSError: pytest: reading from stdin while output is captured! Consider using `-s`.
/usr/local/lib/python3.8/dist-packages/_pytest/capture.py:732: OSError
------------------------------------------------------------------ Captured stdout setup -------------------------------------------------------------------
Customer name found: validname
------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------
Customer name found: &invalidname&
Invalid customer name.
Please enter the customer's name:
================================================================= short test summary info ==================================================================
FAILED test_script.py::TestCustomer::test_invalid_name - OSError: pytest: reading from stdin while output is captured! Consider using `-s`.
=============================================================== 1 failed, 1 passed in 0.07s ================================================================
Когда я использую параметр -s и вводю допустимое имя, исключение не возникает:
test_script.py Customer name found: validname
Customer name found: validname
.Customer name found: validname
Customer name found: &invalidname&
Invalid customer name.
Please enter the customer's name: test
F
========================================================================= FAILURES =========================================================================
______________________________________________________________ TestCustomer.test_invalid_name ______________________________________________________________
self = <test_script.TestCustomer object at 0x7f4f2e1f6640>
def test_invalid_name(self):
with pytest.raises(ValueError):
> self.customer.name = "&invalidname&"
E Failed: DID NOT RAISE <class 'ValueError'>
test_script.py:18: Failed
================================================================= short test summary info ==================================================================
FAILED test_script.py::TestCustomer::test_invalid_name - Failed: DID NOT RAISE <class 'ValueError'>
=============================================================== 1 failed, 1 passed in 1.96s ================================================================
Я не могу понять это ... Любая помощь будет очень признательна :).