Question

storytelling with functions unit test

Answers

GPT-4o mini
Certainly! Unit testing is an essential part of software development that helps ensure that individual functions (or units of code) work as intended. Below, I'll provide you with an example of a story-driven approach where we create a simple program with functions and then write unit tests for them.

### Story Setup

Let's imagine we are building a simple text-based adventure game. Our protagonist, Alex, is on a quest to retrieve a magical gem from a mysterious cave. During this quest, Alex will encounter various challenges that we can represent as functions.

### Tasks/Functions

1. **`explore_cave()`**: A function that simulates Alex exploring the cave.
2. **`find_gem()`**: A function that determines if Alex finds the gem based on a random chance.
3. **`confront_monster()`**: A function that simulates a confrontation with a monster.

### Main Code

Here’s the code implementing our story with the defined functions:

```python
import random

def explore_cave():
"""Simulates exploring the cave. Returns a string."""
return "You ventured deep into the dark cave."

def find_gem():
"""Returns 'found' or 'not found' based on a random chance."""
if random.random() < 0.5: # 50% chance to find the gem
return "found"
else:
return "not found"

def confront_monster():
"""Simulates confronting a monster."""
if random.random() < 0.3: # 30% chance of winning
return "defeated the monster"
else:
return "ran away from the monster"
```

### Unit Tests

Now, let's write some unit tests for these functions. We'll use the `unittest` framework that comes with Python.

```python
import unittest
from unittest.mock import patch

class TestAdventureGame(unittest.TestCase):

def test_explore_cave(self):
"""Test the explore_cave function"""
result = explore_cave()
self.assertEqual(result, "You ventured deep into the dark cave.")

@patch('random.random', return_value=0.4) # Mocking random to 0.4
def test_find_gem_found(self, mock_random):
"""Test when the gem is found"""
result = find_gem()
self.assertEqual(result, "found")

@patch('random.random', return_value=0.6) # Mocking random to 0.6
def test_find_gem_not_found(self, mock_random):
"""Test when the gem is not found"""
result = find_gem()
self.assertEqual(result, "not found")

@patch('random.random', return_value=0.2) # Mocking random to 0.2
def test_confront_monster_defeat(self, mock_random):
"""Test defeating the monster"""
result = confront_monster()
self.assertEqual(result, "defeated the monster")

@patch('random.random', return_value=0.8) # Mocking random to 0.8
def test_confront_monster_run_away(self, mock_random):
"""Test running away from the monster"""
result = confront_monster()
self.assertEqual(result, "ran away from the monster")

if __name__ == "__main__":
unittest.main()
```

### Explanation

1. **`explore_cave()`**: Simply returns a string indicating that Alex is exploring.
2. **`find_gem()`**: Uses a random chance to determine if the gem is found.
3. **`confront_monster()`**: Uses a random chance to determine the outcome of the encounter with a monster.

### Unit Tests

- **`test_explore_cave`**: Validates the output of the `explore_cave` function.
- **`test_find_gem_found` and `test_find_gem_not_found`**: Tests the `find_gem` function with some mocked values to simulate the chance of finding the gem.
- **`test_confront_monster_defeat` and `test_confront_monster_run_away`**: Tests the `confront_monster` function the same way.

### Running the Tests

To run these tests, you can execute the script, and the `unittest` framework will take care of running the test cases and showing the results.

This storytelling approach helps illustrate how to integrate unit testing into a coding project, blending creative story elements with practical software engineering practices.

Related Questions