Editor

Test the Edge Cases

Intermediate · Write the code · from Python Testing with pytest: Write Tests That Actually Help

From the lesson: Python Testing with pytest: Write Tests That Actually Help

Imagine you wrote a spell-checker. It works great on the word "hello." But what about "HeLLo"? Or an empty string? Or a number? You won't know until something breaks - unless you write tests.

Read the lesson

The truncate function shortens a string to a maximum length and adds "..." if it was cut. Write a test_truncate function that tests at least 4 edge cases: a string shorter than the limit, a string exactly at the limit, a string longer than the limit, and an empty string. Call the test and print All tests passed!.

def truncate(text, max_length):
if len(text) <= max_length:
return text
return text[:max_length] + '...'
def test_truncate():
# Test: string shorter than limit
# Test: string exactly at limit
# Test: string longer than limit
# Test: empty string
pass
test_truncate()
print('All tests passed!')

More pytest exercises

All Python exercises · 50 practice problems · Testing quiz