Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/rgb_to_hex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def rgb_to_hex(r: int, g: int, b: int) -> str:
"""
Convert RGB color values to a hex color code.

Args:
r (int): Red color value (0-255)
g (int): Green color value (0-255)
b (int): Blue color value (0-255)

Returns:
str: Hex color code (e.g., '#FF0000' for pure red)

Raises:
ValueError: If any color value is outside the range 0-255
"""
# Validate input ranges
for color, name in [(r, 'Red'), (g, 'Green'), (b, 'Blue')]:
if not isinstance(color, int):
raise TypeError(f"{name} must be an integer")
if color < 0 or color > 255:
raise ValueError(f"{name} must be between 0 and 255")

# Convert to hex and pad with zeros if needed
return f'#{r:02X}{g:02X}{b:02X}'
44 changes: 44 additions & 0 deletions tests/test_rgb_to_hex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import pytest
from src.rgb_to_hex import rgb_to_hex

def test_basic_conversion():
"""Test standard RGB to hex conversion"""
assert rgb_to_hex(255, 0, 0) == '#FF0000' # Red
assert rgb_to_hex(0, 255, 0) == '#00FF00' # Green
assert rgb_to_hex(0, 0, 255) == '#0000FF' # Blue
assert rgb_to_hex(128, 128, 128) == '#808080' # Gray

def test_zero_values():
"""Test conversion with zero values"""
assert rgb_to_hex(0, 0, 0) == '#000000' # Black

def test_padding():
"""Test that single-digit hex values are padded"""
assert rgb_to_hex(1, 2, 3) == '#010203'

def test_invalid_inputs():
"""Test error handling for invalid inputs"""
# Values below 0
with pytest.raises(ValueError, match="must be between 0 and 255"):
rgb_to_hex(-1, 0, 0)
with pytest.raises(ValueError, match="must be between 0 and 255"):
rgb_to_hex(0, -1, 0)
with pytest.raises(ValueError, match="must be between 0 and 255"):
rgb_to_hex(0, 0, -1)

# Values above 255
with pytest.raises(ValueError, match="must be between 0 and 255"):
rgb_to_hex(256, 0, 0)
with pytest.raises(ValueError, match="must be between 0 and 255"):
rgb_to_hex(0, 256, 0)
with pytest.raises(ValueError, match="must be between 0 and 255"):
rgb_to_hex(0, 0, 256)

def test_type_errors():
"""Test error handling for incorrect input types"""
with pytest.raises(TypeError, match="Red must be an integer"):
rgb_to_hex('255', 0, 0)
with pytest.raises(TypeError, match="Green must be an integer"):
rgb_to_hex(0, '255', 0)
with pytest.raises(TypeError, match="Blue must be an integer"):
rgb_to_hex(0, 0, '255')