...
In this example, we will check the majority number of possible cases when exceptions can occur. For tutorial purposes let's write a function called get_triangle_area which returns triangle area calculated from base and height values read from input files (input files are function functions' arguments).
Code Block | ||||
---|---|---|---|---|
| ||||
def get_triangle_area(file_base, file_height): base = float(open(file_base, 'r').readline()) height = float(open(file_height, 'r').readline()) if base not in range(1, 100): raise ValueError() if height not in range(1, 100): raise ValueError() return 0.5 * base * height |
...
- The input file doesn't exist.
- Bad input file extension.
- Empty input file.
- Bad value type (e.g. base and height can't be strings).
- A negative value of base or/and height.
- Call function without arguments.
- Base or height value bigger than 100 (in get_triangle_area function base and height values should be in the range from 1 to 100).
The next step is writing to write the tests.
Info |
---|
All rules of testing exceptions are explained in 3. Testing exceptions chapter. |
...
Code Block | ||||
---|---|---|---|---|
| ||||
def test_get_triangle_area():
# PROPER RESULT TEST
assert get_triangle_area("./../resources/base.txt",
"./../resources/height.txt") == 25
# BAD FILENAME
with pytest.raises(FileNotFoundError):
get_triangle_area("./../resources/flower.txt",
"./../resources/height.txt")
# EMPTY FILE
with pytest.raises(ValueError):
get_triangle_area("./../resources/empty.txt",
"./../resources/height.txt")
# BAD VALUE TYPE
with pytest.raises(ValueError):
get_triangle_area("./../resources/string_base.txt",
"./../resources/height.txt")
# NEGATIVE VALUE
with pytest.raises(ValueError):
get_triangle_area("./../resources/negative_base.txt",
"./../resources/height.txt")
# BAD FILE EXTENSION
with pytest.raises(FileNotFoundError):
get_triangle_area("./../resources/base.txt",
"./../resources/height.csv")
# CALL FUNC WITHOUT ARGUMENTS
with pytest.raises(TypeError):
get_triangle_area()
# BASE EQUAL 1000
with pytest.raises(ValueError):
get_triangle_area("./../resources/mega_base.txt",
"./../resources/height.txt") |
Let's run the test_get_triangle_area and inspect the result.
As we suspected all tests passed. It means that get_triangle_area() returns proper results and whenever something goes wrong proper exceptions would occur.