diff --git a/src/color_converter.py b/src/color_converter.py new file mode 100644 index 0000000..0c1df00 --- /dev/null +++ b/src/color_converter.py @@ -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}' \ No newline at end of file diff --git a/tests/test_color_converter.py b/tests/test_color_converter.py new file mode 100644 index 0000000..787d123 --- /dev/null +++ b/tests/test_color_converter.py @@ -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) \ No newline at end of file