Style: Preconditions and unit tests for parseColor().

This commit is contained in:
Andreas Schildbach 2016-02-29 10:37:02 +01:00
parent 910b6705b8
commit b1e89921a6
2 changed files with 42 additions and 13 deletions

View file

@ -17,6 +17,7 @@
package de.schildbach.pte.dto;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.Serializable;
@ -110,24 +111,22 @@ public class Style implements Serializable
public static final int MAGENTA = 0xFFFF00FF;
public static final int TRANSPARENT = 0;
public static int parseColor(final String colorString)
public static int parseColor(final String colorStr)
{
if (colorString.charAt(0) == '#')
checkNotNull(colorStr);
checkArgument((colorStr.length() == 7 || colorStr.length() == 9) && colorStr.charAt(0) == '#', "Unknown color: %s", colorStr);
try
{
// Use a long to avoid rollovers on #ffXXXXXX
long color = Long.parseLong(colorString.substring(1), 16);
if (colorString.length() == 7)
{
// Set the alpha value
color |= 0x00000000ff000000;
}
else if (colorString.length() != 9)
{
throw new IllegalArgumentException("Unknown color");
}
long color = Long.parseLong(colorStr.substring(1), 16);
if (colorStr.length() == 7)
color |= 0xff000000; // Amend the alpha value
return (int) color;
}
throw new IllegalArgumentException("Unknown color");
catch (final NumberFormatException x)
{
throw new IllegalArgumentException("Not a number: " + colorStr);
}
}
public static int rgb(final int red, final int green, final int blue)

View file

@ -33,6 +33,36 @@ public class StyleTest
assertEquals(color, Style.rgb(Style.red(color), Style.green(color), Style.blue(color)));
}
@Test
public void parseColor()
{
assertEquals(0x11223344, Style.parseColor("#11223344"));
}
@Test
public void parseColor_noOverflow()
{
assertEquals(0xffffffff, Style.parseColor("#ffffffff"));
}
@Test
public void parseColor_amendAlpha()
{
assertEquals(0xff000000, Style.parseColor("#000000"));
}
@Test(expected = IllegalArgumentException.class)
public void parseColor_failTooShort()
{
Style.parseColor("#");
}
@Test(expected = IllegalArgumentException.class)
public void parseColor_failNotANumber()
{
Style.parseColor("#11111z");
}
@Test
public void deriveForegroundColorForLightBackground()
{