Home Backend Development Python Tutorial Building a String Calculator with Test-Driven Development (TDD): A Step-by-Step Guide

Building a String Calculator with Test-Driven Development (TDD): A Step-by-Step Guide

Jan 15, 2025 pm 06:09 PM

Building a String Calculator with Test-Driven Development (TDD): A Step-by-Step Guide

We will implement a string calculator in Python using a test-driven development (TDD) approach. This means we will write tests for each feature before implementing the corresponding functionality.

You can refer to the link https://osherove.com/tdd-kata-1 as your checkpoints for implementing TDD. The link provides step-by-step instructions that you can follow.

Getting started

In your project folder, create two files: string_calculator.py and tests/test_string_calculator.py. We'll implement the features step by step. First, we need to create a StringCalculator class with an add method.

Step 1: Empty String Should Return "0"

Let's write the first test for our application using the unittest library. Open the tests/test_string_calculator.py file and start with the following code:

import unittest
from string_calculator import StringCalculator

class TestStringCalculator(unittest.TestCase):
    """Test suite for the StringCalculator class."""

    def setUp(self):
        """
        Create a new instance of StringCalculator for each test.
        Can use static method to avoid creating a new instance.
        """
        self.calculator = StringCalculator()

    def test_empty_string_returns_zero(self):
        """
        Test case: Adding an empty string should return 0.
        Input: "" 
        Expected Output: 0
        """
        self.assertEqual(self.calculator.add(""), 0)
Copy after login
Copy after login
Copy after login

Now, let's implement the StringCalculator class in the string_calculator.py file:

class StringCalculator:
    def add(self, numbers:str):
        if not numbers:
            return 0

Copy after login
Copy after login
Copy after login

To run the tests, follow these steps:

  1. Ensure that you are in the project directory where your string_calculator.py and tests/test_string_calculator.py files are located.

  2. Open your terminal or command prompt.

  3. Run the following command to execute the tests:

python -m unittest discover tests
Copy after login
Copy after login
Copy after login

This command will automatically discover and run all tests within the tests folder.

Expected Output:

You should see something like this if the test passes:


----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Copy after login
Copy after login
Copy after login

If everything is set up correctly and the test case passes, it means your implementation for handling an empty string is working as expected.

Step 2: Adding One or Two Numbers Should Return Their Sum

We need to update the method to handle the case where there is only one number or two numbers in the input string, and it should return their sum. For an empty string, the method should return 0.

Writing the Test

Open the tests/test_string_calculator.py file and add the following test cases to cover all the scenarios:

    def test_add_single_number(self):
        """
        Test case: Adding a single number should return the number itself.
        Input: "1"
        Expected Output: 1
        """
        self.assertEqual(self.calculator.add("1"), 1)

    def test_add_two_numbers(self):
        """
        Test case: Adding two numbers should return their sum.
        Input: "1,2"
        Expected Output: 3
        """
        self.assertEqual(self.calculator.add("1,2"),3)
Copy after login
Copy after login
Copy after login

Implementing the Code

Now, update the add method in the string_calculator.py file to handle the addition of one or two numbers:

class StringCalculator:
    def add(self, numbers:str):
        if not numbers:
            return 0
        '''
        Split the string by commas, convert each value to an integer, 
        and sum them up
        '''
        numbers_list = map(int,numbers.split(',')) 
        return sum(numbers_list)
Copy after login
Copy after login
Copy after login

You can test the code again by following the previous steps.

Step 3 : Handling Multiple Numbers

We'll write a test case to check if the method can handle multiple numbers separated by commas.

Writing the Test

Open the tests/test_string_calculator.py file and add a test case to handle multiple numbers:

import unittest
from string_calculator import StringCalculator

class TestStringCalculator(unittest.TestCase):
    """Test suite for the StringCalculator class."""

    def setUp(self):
        """
        Create a new instance of StringCalculator for each test.
        Can use static method to avoid creating a new instance.
        """
        self.calculator = StringCalculator()

    def test_empty_string_returns_zero(self):
        """
        Test case: Adding an empty string should return 0.
        Input: "" 
        Expected Output: 0
        """
        self.assertEqual(self.calculator.add(""), 0)
Copy after login
Copy after login
Copy after login

The functionality has already been implemented, so we can proceed to test the code and then move on to the next step.

Step 4: Handling New Lines Between Numbers

Now, we need to enhance the add method to handle new lines (n) as valid separators between numbers, in addition to commas.

Writing the Test

Open the tests/test_string_calculator.py file and add a test case to check if the method correctly handles new lines as separators:

class StringCalculator:
    def add(self, numbers:str):
        if not numbers:
            return 0

Copy after login
Copy after login
Copy after login

Implementing the Code

Next, update the add method in the string_calculator.py file to handle new lines (n) as separators. We can modify the method to replace n with commas, then split the string by commas.

Here's the updated code for the add method:

python -m unittest discover tests
Copy after login
Copy after login
Copy after login

You can test the code again by following the previous steps defined in step1.

Step 5: Handling Custom Delimiters

In this step, we will enhance the functionality further to allow custom delimiters. For instance, users should be able to specify a custom delimiter at the beginning of the string. For example:

  • The input string could start with // followed by a custom delimiter, e.g., //;n1;2;3 should return 6.
  • We will support delimiters like //;n1;2;3.

Writing the Test

Open the tests/test_string_calculator.py file and add a test case to handle the custom delimiter functionality:


----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Copy after login
Copy after login
Copy after login

Implementing the Code

To handle custom delimiters, update the add method to look for the delimiter in the input string. The delimiter should be specified at the beginning of the string after //.

Here’s the updated add method:

    def test_add_single_number(self):
        """
        Test case: Adding a single number should return the number itself.
        Input: "1"
        Expected Output: 1
        """
        self.assertEqual(self.calculator.add("1"), 1)

    def test_add_two_numbers(self):
        """
        Test case: Adding two numbers should return their sum.
        Input: "1,2"
        Expected Output: 3
        """
        self.assertEqual(self.calculator.add("1,2"),3)
Copy after login
Copy after login
Copy after login

Step 6: Handling Negative Numbers

In this step, we need to modify the add method to handle negative numbers. When a negative number is passed, it should throw an exception with the message "negatives not allowed", and include the negative numbers that were passed.

Writing the Test

Open the tests/test_string_calculator.py file and add a test case to handle the negative number exception:

class StringCalculator:
    def add(self, numbers:str):
        if not numbers:
            return 0
        '''
        Split the string by commas, convert each value to an integer, 
        and sum them up
        '''
        numbers_list = map(int,numbers.split(',')) 
        return sum(numbers_list)
Copy after login
Copy after login
Copy after login

Implementing the Code

Now, modify the add method to check for negative numbers and raise a ValueError with the appropriate message.

Here's the updated add method:

def test_add_multiple_numbers(self):
    """
    Test case: Adding multiple numbers should return their sum.
    Input: "1,2,3,4,5"
    Expected Output: 15
    """
    self.assertEqual(self.calculator.add("1,2,3,4,5"), 15)
Copy after login
Copy after login

Step 7: Counting Add Method Calls

In this step, we will add a method called GetCalledCount() to the StringCalculator class that will return how many times the add() method has been invoked. We will follow the TDD process by writing a failing test first, and then implementing the feature.

Writing the Test

Start by adding a test case for the GetCalledCount() method. This test should check that the method correctly counts the number of times add() is called.

Open the tests/test_string_calculator.py file and add the following test:

import unittest
from string_calculator import StringCalculator

class TestStringCalculator(unittest.TestCase):
    """Test suite for the StringCalculator class."""

    def setUp(self):
        """
        Create a new instance of StringCalculator for each test.
        Can use static method to avoid creating a new instance.
        """
        self.calculator = StringCalculator()

    def test_empty_string_returns_zero(self):
        """
        Test case: Adding an empty string should return 0.
        Input: "" 
        Expected Output: 0
        """
        self.assertEqual(self.calculator.add(""), 0)
Copy after login
Copy after login
Copy after login

Implementing the Code

Now, implement the GetCalledCount() method in the StringCalculator class. This method will need to keep track of how many times add() has been invoked.

Here’s the updated StringCalculator class:

class StringCalculator:
    def add(self, numbers:str):
        if not numbers:
            return 0

Copy after login
Copy after login
Copy after login

Step 8 & 9: Ignore Numbers Greater Than 1000 and Handle Custom Delimiters of Any Length

In this step, we will implement two requirements:

  1. Numbers greater than 1000 should be ignored in the sum.
  2. Custom delimiters can be of any length, with the format //[delimiter]n, and the method should handle them.

We will first write the tests for both of these requirements, then implement the functionality in the StringCalculator class.

Writing the Tests

Add the following tests for both the ignore numbers greater than 1000 and handling custom delimiters of any length. Open the tests/test_string_calculator.py file and add the following:

python -m unittest discover tests
Copy after login
Copy after login
Copy after login

Implementing the Code

Now, implement the functionality in the StringCalculator class. This will include:

  1. Ignoring numbers greater than 1000.
  2. Handling custom delimiters of any length.

Here’s the updated StringCalculator class:


----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Copy after login
Copy after login
Copy after login

Step 10: Multiple Delimiters Support

In this step, we will modify the add() method to support multiple delimiters of any length. This will allow us to handle cases where there are multiple delimiters in the format //[delimiter1][delimiter2]n.

Writing the Test

Start by adding a test case to check for multiple delimiters. Open the tests/test_string_calculator.py file and add the following test:

    def test_add_single_number(self):
        """
        Test case: Adding a single number should return the number itself.
        Input: "1"
        Expected Output: 1
        """
        self.assertEqual(self.calculator.add("1"), 1)

    def test_add_two_numbers(self):
        """
        Test case: Adding two numbers should return their sum.
        Input: "1,2"
        Expected Output: 3
        """
        self.assertEqual(self.calculator.add("1,2"),3)
Copy after login
Copy after login
Copy after login

Implementing the Code

Now, modify the add() method to handle multiple delimiters. The delimiters will be passed inside [], and we need to support handling multiple delimiters in the format //[delimiter1][delimiter2]n.

Here's the updated StringCalculator class to support this:

class StringCalculator:
    def add(self, numbers:str):
        if not numbers:
            return 0
        '''
        Split the string by commas, convert each value to an integer, 
        and sum them up
        '''
        numbers_list = map(int,numbers.split(',')) 
        return sum(numbers_list)
Copy after login
Copy after login
Copy after login

Testing It

Run the tests again to verify that everything works, including backward compatibility with the old format and support for the new multiple delimiters format:

def test_add_multiple_numbers(self):
    """
    Test case: Adding multiple numbers should return their sum.
    Input: "1,2,3,4,5"
    Expected Output: 15
    """
    self.assertEqual(self.calculator.add("1,2,3,4,5"), 15)
Copy after login
Copy after login

Expected Output

The tests should pass for both old and new formats:

def test_add_numbers_with_newlines(self):
    """
    Test case: Adding numbers separated by newlines should return their sum.
    Input: "1\n2\n3"
    Expected Output: 6
    """
    self.assertEqual(self.calculator.add("1\n2\n3"), 6)
Copy after login

Appreciate you following along with this TDD series! I hope you found it useful.

The above is the detailed content of Building a String Calculator with Test-Driven Development (TDD): A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles