diff --git a/src/color_converter.py b/src/color_converter.py new file mode 100644 index 00000000..fab48043 --- /dev/null +++ b/src/color_converter.py @@ -0,0 +1,36 @@ +def rgb_to_hex(*args): + """ + Convert RGB color values to a hexadecimal color code. + + Args: + *args: Either 3 individual integer values (r, g, b) + or a single tuple/list of 3 RGB values + + Returns: + str: Hexadecimal color code (e.g., '#FF0000' for bright red) + + Raises: + ValueError: If RGB values are not in the range 0-255 + or incorrect number of arguments is provided + """ + # Handle different input formats + if len(args) == 1 and isinstance(args[0], (tuple, list)): + rgb = args[0] + elif len(args) == 3: + rgb = args + else: + raise ValueError("Input must be either 3 separate values or a single tuple/list of 3 values") + + # Validate input + if len(rgb) != 3: + raise ValueError("Exactly 3 color values (R, G, B) are required") + + # Check each value is in valid range + for color in rgb: + if not isinstance(color, int): + raise ValueError("RGB values must be integers") + if color < 0 or color > 255: + raise ValueError("RGB values must be between 0 and 255") + + # Convert to hexadecimal + return '#{:02X}{:02X}{:02X}'.format(rgb[0], rgb[1], rgb[2]) \ 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 00000000..91ea45cc --- /dev/null +++ b/tests/test_color_converter.py @@ -0,0 +1,54 @@ +import pytest +from src.color_converter import rgb_to_hex + +def test_rgb_to_hex_individual_values(): + """Test conversion with individual RGB values""" + assert rgb_to_hex(255, 0, 0) == '#FF0000' + assert rgb_to_hex(0, 255, 0) == '#00FF00' + assert rgb_to_hex(0, 0, 255) == '#0000FF' + +def test_rgb_to_hex_tuple(): + """Test conversion with RGB tuple""" + assert rgb_to_hex((255, 0, 0)) == '#FF0000' + assert rgb_to_hex((0, 255, 0)) == '#00FF00' + assert rgb_to_hex((0, 0, 255)) == '#0000FF' + +def test_rgb_to_hex_mixed_colors(): + """Test conversion with mixed RGB values""" + assert rgb_to_hex(128, 128, 128) == '#808080' + assert rgb_to_hex(255, 165, 0) == '#FFA500' + +def test_rgb_to_hex_edge_cases(): + """Test edge case values""" + assert rgb_to_hex(0, 0, 0) == '#000000' + assert rgb_to_hex(255, 255, 255) == '#FFFFFF' + +def test_rgb_to_hex_invalid_input(): + """Test error handling for invalid inputs""" + # Too few arguments + with pytest.raises(ValueError): + rgb_to_hex(255, 0) + + # Too many arguments + with pytest.raises(ValueError): + rgb_to_hex(255, 0, 0, 0) + + # Non-integer values + with pytest.raises(ValueError): + rgb_to_hex(255.5, 0, 0) + + # Out of range values + with pytest.raises(ValueError): + rgb_to_hex(256, 0, 0) + + # Negative values + with pytest.raises(ValueError): + rgb_to_hex(-1, 0, 0) + + # Invalid input type + with pytest.raises(ValueError): + rgb_to_hex("255", "0", "0") + + # Invalid tuple/list + with pytest.raises(ValueError): + rgb_to_hex([255, 0]) \ No newline at end of file