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
26 changes: 26 additions & 0 deletions src/color_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
def rgb_to_hex(r: int, g: int, b: int) -> str:
"""
Convert RGB color values to a hexadecimal 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: Hexadecimal color code (e.g., '#FF0000')

Raises:
ValueError: If any color value is not in the range 0-255
TypeError: If color values are not integers
"""
# Validate input types
if not all(isinstance(x, int) for x in (r, g, b)):
raise TypeError("RGB values must be integers")

# Validate input ranges
if not all(0 <= x <= 255 for x in (r, g, b)):
raise ValueError("RGB values must be between 0 and 255")

# Convert to hex and ensure two-digit representation
return f'#{r:02X}{g:02X}{b:02X}'
38 changes: 38 additions & 0 deletions tests/test_color_converter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import pytest
from src.color_converter import rgb_to_hex

def test_basic_rgb_to_hex_conversion():
"""Test basic 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(0, 0, 0) == '#000000' # Black
assert rgb_to_hex(255, 255, 255) == '#FFFFFF' # White

def test_edge_case_values():
"""Test conversion with edge case values."""
assert rgb_to_hex(0, 0, 0) == '#000000'
assert rgb_to_hex(255, 255, 255) == '#FFFFFF'

def test_intermediate_values():
"""Test conversion with intermediate color values."""
assert rgb_to_hex(128, 128, 128) == '#808080'
assert rgb_to_hex(17, 34, 51) == '#112233'

def test_invalid_input_types():
"""Test error handling for invalid input types."""
with pytest.raises(TypeError):
rgb_to_hex('255', 0, 0)
with pytest.raises(TypeError):
rgb_to_hex(255, '0', 0)
with pytest.raises(TypeError):
rgb_to_hex(255, 0, '0')

def test_out_of_range_inputs():
"""Test error handling for out-of-range input values."""
with pytest.raises(ValueError):
rgb_to_hex(-1, 0, 0)
with pytest.raises(ValueError):
rgb_to_hex(0, 256, 0)
with pytest.raises(ValueError):
rgb_to_hex(0, 0, 300)