Python Data Science Jobs & Interviews
20.6K subscribers
192 photos
4 videos
25 files
335 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @Hussein_Sheikho
Download Telegram
Tip for clean tests in Python:

Structure your tests with the Arrange-Act-Assert pattern to improve readability and maintainability.

Arrange: Set up the test. Initialize objects, prepare data, and configure any mocks or stubs.
Act: Execute the code being tested. Call the specific function or method.
Assert: Check the outcome. Verify that the result of the action is what you expected.

import pytest
from dataclasses import dataclass, field


# Code to be tested
@dataclass
class Product:
name: str
price: float


@dataclass
class ShoppingCart:
items: list[Product] = field(default_factory=list)

def add_item(self, product: Product):
if product.price < 0:
raise ValueError("Product price cannot be negative.")
self.items.append(product)

def get_total_price(self) -> float:
return sum(item.price for item in self.items)


# Tests using the Arrange-Act-Assert pattern
def test_get_total_price_for_multiple_items():
# Arrange
product1 = Product(name="Mouse", price=25.50)
product2 = Product(name="Keyboard", price=75.50)
cart = ShoppingCart()
cart.add_item(product1)
cart.add_item(product2)

# Act
total_price = cart.get_total_price()

# Assert
assert total_price == 101.00


def test_get_total_price_for_empty_cart():
# Arrange
cart = ShoppingCart()

# Act
total_price = cart.get_total_price()

# Assert
assert total_price == 0.0


def test_add_item_with_negative_price_raises_value_error():
# Arrange
cart = ShoppingCart()
product_with_negative_price = Product(name="Invalid Item", price=-50.0)

# Act & Assert
with pytest.raises(ValueError, match="Product price cannot be negative."):
cart.add_item(product_with_negative_price)


#Python #Testing #CleanCode #SoftwareEngineering #Pytest #DeveloperTips #AAA

━━━━━━━━━━━━━━━
By: @DataScienceQ