Sure, here's an example feature file, test code, and production code for calculating Fibonacci numbers using Behave as the test framework in Python:
Feature File: fibonacci.feature
Calculate Fibonacci Number
Feature: Calculating Fibonacci numbers
Scenario: Calculate Fibonacci number for a given number
Given a number n
When I ask for the Fibonacci number of n
Then the Fibonacci number of n should be returned
Scenario: Calculate Fibonacci number for a range of numbers
Given a range of numbers (n1, n2)
When I ask for the Fibonacci numbers of the range
Then the Fibonacci numbers of the range should be returned
Test Code: fibonacci_steps.py
from behave import given, when, then
@given('a number n')
def step_impl(context):
context.n = int(context.text)
@when('I ask for the Fibonacci number of n')
def step_impl(context):
context.result = fibonacci(context.n)
@then('the Fibonacci number of n should be returned')
def step_impl(context):
assert context.result == fibonacci(context.n)
@given('a range of numbers (n1, n2)')
def step_impl(context):
context.n1 = int(context.text.split(',')[0])
context.n2 = int(context.text.split(',')[1])
@when('I ask for the Fibonacci numbers of the range')
def step_impl(context):
context.results = [fibonacci(n) for n in range(context.n1, context.n2 + 1)]
@then('the Fibonacci numbers of the range should be returned')
def step_impl(context):
assert context.results == [fibonacci(n) for n in range(context.n1, context.n2 + 1)]
Production Code: fibonacci.py
def fibonacci(n):
"""
Calculate the nth Fibonacci number.
"""
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
def main():
n = int(input("Enter a number or a range of numbers (e.g. 5 or 3-7): "))
if n == 0:
print("Fibonacci numbers cannot be calculated for 0.")
elif n == 1:
print("The Fibonacci number of 1 is 1.")
elif n == 2:
print("The Fibonacci number of 2 is 1.")
else:
results = [fibonacci(n) for n in range(n)]
print("Fibonacci numbers for the range of", n, "are:", results)
if name == "main":
main()
Note:
- The feature file describes the desired behavior of the Fibonacci number calculator.
- The test code, fibonacci_steps.py, defines the steps for the scenarios described in the feature file.
- The production code, fibonacci.py, implements the Fibonacci number calculator and is tested by the test code.
- The main function in the production code calls the fibonacci function with the input value(s) and prints the result(s).
- The test code uses the Behave framework to run the scenarios and assert that the results match the expected output.