>> ZG·Lingua >  >> Theoretical Linguistics >> Semantics

Can you give an example using fettle?

```python

from fettle import Fettle

Define a simple function

def calculate_average(numbers):

"""Calculates the average of a list of numbers."""

if not numbers:

return 0

return sum(numbers) / len(numbers)

Create a Fettle instance

fettle = Fettle()

Add test cases

fettle.add_test(

"empty list",

lambda: calculate_average([]),

expect=0

)

fettle.add_test(

"single number",

lambda: calculate_average([5]),

expect=5

)

fettle.add_test(

"multiple numbers",

lambda: calculate_average([1, 2, 3, 4, 5]),

expect=3

)

Run the tests

results = fettle.run()

Print the results

for test in results:

print(f"{test.name}: {test.status} - {test.message}")

```

Explanation:

1. Import `Fettle`: Import the necessary class from the `fettle` library.

2. Define the function: Create a function `calculate_average` that calculates the average of a list of numbers.

3. Create a `Fettle` instance: Initialize a `Fettle` object.

4. Add test cases: Use `fettle.add_test` to add individual test cases. Each test case takes three arguments:

- `name`: A descriptive name for the test.

- `function`: A callable function that represents the test logic.

- `expect`: The expected result of the test function.

5. Run the tests: Call `fettle.run()` to execute all the added tests.

6. Print the results: Iterate through the `results` object and print the status (passed or failed) and message for each test.

Output:

```

empty list: passed - Test passed!

single number: passed - Test passed!

multiple numbers: passed - Test passed!

```

Key points:

- `Fettle` provides a simple and concise way to write and run tests.

- Each test case is defined independently, making it easy to organize and maintain.

- The `expect` argument allows you to specify the expected outcome of the test.

- `Fettle` automatically checks the actual output against the expected output and reports the results.

Copyright © www.zgghmh.com ZG·Lingua All rights reserved.