Skip to content

Commit

Permalink
fix: add invalid hex input handling
Browse files Browse the repository at this point in the history
  • Loading branch information
AngRodrigues committed Jun 6, 2024
1 parent 899a657 commit 40028a8
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 5 deletions.
21 changes: 16 additions & 5 deletions map2loop/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,22 +325,33 @@ def generate_random_hex_colors(n: int) -> list:
def hex_to_rgba(hex_color: str, alpha: float = 1.0) -> tuple:
"""
Convert a hex color code to an RGBA tuple.
Args:
hex_color (str): The hex color code (e.g., "#RRGGBB" or "#RGB").
alpha (float, optional): The alpha value (opacity) for the color. Defaults to 1.0.
Returns:
tuple: A tuple (r, g, b, a) where r, g, b are in the range 0-1 and a is in the range 0-1.
"""
if not isinstance(hex_color, str) or not hex_color.startswith('#'):
raise ValueError("Invalid hex color code. Must start with '#'.")

hex_color = hex_color.lstrip('#')

if len(hex_color) not in [3, 6]:
raise ValueError("Invalid hex color code. Must be 3 or 6 characters long after '#'.")

# Handle short hex code (e.g., "#RGB")
if len(hex_color) == 3:
hex_color = ''.join([c * 2 for c in hex_color])

r = int(hex_color[0:2], 16) / 255.0
g = int(hex_color[2:4], 16) / 255.0
b = int(hex_color[4:6], 16) / 255.0
try:
r = int(hex_color[0:2], 16) / 255.0
g = int(hex_color[2:4], 16) / 255.0
b = int(hex_color[4:6], 16) / 255.0

except ValueError as e:
raise ValueError(
"Invalid hex color code. Contains non-hexadecimal characters."
) from e

return (r, g, b, alpha)

41 changes: 41 additions & 0 deletions tests/utils/test_rgb_and_hex_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import pytest
import re
from map2loop.utils import generate_random_hex_colors, hex_to_rgba # Replace 'your_module' with the actual module name

#does it return the right number of colors?
def test_generate_random_hex_colors_length():
n = 5
colors = generate_random_hex_colors(n)
assert len(colors) == n, f"utils function generate_random_hex_colors not returning the right number of hex codes.Expected {n} colors, got {len(colors)}"

# are the returned hex strings the right format?
def test_generate_random_hex_colors_format():
n = 10
hex_pattern = re.compile(r'^#[0-9A-Fa-f]{6}$')
colors = generate_random_hex_colors(n)
for color in colors:
assert hex_pattern.match(color), f"utils function generate_random_hex_colors not returning hex strings in the right format. Got {color} instead."

# is hex conversion to rgba working as expected?
def test_hex_to_rgba_long_hex():
hex_color = "#1a2b3c" # long hex versions
expected_output = (0.10196078431372549, 0.16862745098039217, 0.23529411764705882, 1.0)
assert hex_to_rgba(hex_color) == expected_output, f"utils function hex_to_rgba not doing hex to rgba conversion correctly. Expected {expected_output}, got {hex_to_rgba(hex_color)}"


def test_hex_to_rgba_short_hex():
hex_color = "#abc" # short hex versions
expected_output = (0.6666666666666666, 0.7333333333333333, 0.8, 1.0)
assert hex_to_rgba(hex_color) == expected_output

# does it handle alpha values correctly?
def test_hex_to_rgba_with_alpha():
hex_color = "#1a2b3c"
alpha = 0.5
expected_output = (0.10196078431372549, 0.16862745098039217, 0.23529411764705882, alpha)
assert hex_to_rgba(hex_color, alpha) == expected_output, f"utils function hex_to_rgba not handling alpha values correctly. Expected {expected_output}, got {hex_to_rgba(hex_color, alpha)}"

# does it handle invalid inputs correctly?
def test_hex_to_rgba_invalid_hex():
with pytest.raises(ValueError):
hex_to_rgba("12FF456"), "utils function hex_to_rgba is expected to raise a ValueError when an invalid hex string is passed, but it did not."

0 comments on commit 40028a8

Please sign in to comment.