Enhancing Functionality and Tests with Pytest
Consider a scenario where a user enter non-string input in ‘reverse_text()’ function. Now, we refine the above function to raise an exception in such cases and test this behaviour.
In the below code, Pytest runs the test function ‘test_reverse_text_not_string()’. This test function calls ‘reverse_text(1234)’. As ‘1234’ is a number not a string so, ‘reverse_text()’ raises a ‘ValueError’. The ‘with pytest.raises(ValueError)’ in the test function is expecting this ‘ValueError’, that why the test passes.
# test_reversal2.py
import pytest
def reverse_text(text):
if not isinstance(text, str):
raise ValueError('Expected a string')
return text[::-1]
def test_reverse_text_non_string():
with pytest.raises(ValueError):
reverse_text(1234)
Output:
Pytest Tutorial | Unit Testing in Python using Pytest Framework
In the process of development of applications, testing plays a crucial role. It ensures the developers that the application is error-free and the application is running as per the expectation. It should be done to ensure a seamless experience for the user. In this article, we will learn about testing Python applications using Pytest.
Contact Us