+ 1

Hi,all what is the purpose of the following statement with pytest.raise(TypeError)?

I have searched a lot but all what I found is testing exception what does it mean?

20th Oct 2024, 10:46 AM
Yusof
Yusof - avatar
4 Answers
+ 4
pytest - is a package that helps you create tests for your app. You can write a bunch of tests for your various functions and then compare the results to see if your function did what it's supposed to do. raises - is a function that checks if your app raised an error. Sometimes you want your code to raise an error in certain circumstances. When you are testing a function to make sure it raises an error, this function does that. TypeError - is the error type. This means the data is the wrong type. There are a number of errors that can be raised or checked for. So in this case, there is no context to what you are asking about. But this one command would be a test to see if the function you are testing raises a TypeError. NOTE: Instead of googling the whole thing - just google the first part and read the docs from there. You're question is about PyTest. Then google that. When you are on the PyTest documentation, look for RAISES.
20th Oct 2024, 12:35 PM
Jerry Hobby
Jerry Hobby - avatar
+ 1
A file called calculator def main(): x = int(input("What's x? ")) print("x squared is", square(x)) def square(n): return n * n if __name__ == "__main__": main() ______________ A file to test import pytest from calculator import square def test_positive(): assert square(2) == 4 assert square(3) == 9 def test_negative(): assert square(-2) == 4 assert square(-3) == 9 def test_zero(): assert square(0) == 0 def test_str(): with pytest.raises(TypeError): square("cat") This my context Jerry Hobby . Anyway THX for your clarification But to make sure of my understanding Do you mean with pytest.raises (TypeError) it test the error that I want my function to catch when some error occurred by the user ?and Then I use a suitable try except statements to deal with that error to avoid runtime errors for user?
20th Oct 2024, 1:57 PM
Yusof
Yusof - avatar
+ 1
Yusof yeah your right according to your code it is integer based code and while testing you gave the string so it raised the type error so it's handling it properly so that users don't type in wrong values other than integers.
20th Oct 2024, 3:34 PM
Aysha
Aysha - avatar
+ 1
20th Oct 2024, 3:42 PM
Yusof
Yusof - avatar