Continue Developing the calculateDiscount Function

Introduction to TDD and pytest

Welcome to your second lesson in this course dedicated to practicing Test Driven Development (TDD) utilizing Python and pytest. In this unit, we will continue adding features to our calculate_discount function. We have five more requirements for you to implement!

In this course, emphasis is placed on hands-on practice, where you'll receive requirements through tests, one at a time. Your task is to implement code that makes each test pass, simulating a real-world TDD environment. As the course guide, it's akin to being your pair programmer, providing test-driven prompts to hone your skills as you progress.

Understanding the Red-Green-Refactor Cycle

As a reminder, the Red-Green-Refactor cycle is central to TDD, guiding your development process:

  • Red: Start by writing a failing test to define the next step.
  • Green: Implement just enough code to pass the test, focusing on functionality.
  • Refactor: Optimize the code for clarity and efficiency without changing its behavior.

More Requirements for `calculate_discount` Function

Building on our previous unit's work, we'll now implement advanced validation and business logic for the calculate_discount function. These requirements address input validation, edge cases, and business rules that ensure our function behaves correctly under various scenarios. The following test cases will guide our implementation through Test-Driven Development:

7. Non-Numeric Price Input Handling

  • Description: The function should validate that the price is a numeric value and raise an error if a non-numeric input is provided.
  • Test Case:
    Python
      def test_throw_error_for_non_numeric_price_inputs(self):
          # Arrange
          original_price = 'invalid'
          discount_percentage = 10
    
          # Act, Assert
          with pytest.raises(TypeError, match='Price must be a valid number'):
              calculate_discount(original_price, discount_percentage)

8. Non-Numeric Discount Input Handling

  • Description: The function should validate that the discount percentage is a numeric value and raise an error if a non-numeric input is provided.
  • Test Case:
    Python
      def test_throw_error_for_non_numeric_discount_inputs(self):
          # Arrange
          original_price = 100
          discount_percentage = 'invalid'
          
          # Act, Assert
          with pytest.raises(TypeError, match='Discount must be a valid number'):
              calculate_discount(original_price, discount_percentage)
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal