Learning Tests

Sometimes APIs aren't documented, or the results at corner cases of a function aren't clear. This might be a built-in library, or a third-party one being pulled in as a dependency.

I sometimes write a few tests of these libraries in my own projects to check and document behavior where the behavior is unclear. It also provides a mechanism to check if these corner cases or undocumented assumptions in library code change.

For example, I just started learning Go, and I've been using hsluv-go to do a project with color spaces. It has been a great library. The readme describes RGB inputs as 0 -> 1.0, but it doesn't describe what the reported hue colors will be when converting grayscale colors from RGB to HSLuv.

This is easy to do by writing a simple test and observing the behavior.

func TestGrayscaleColors(t *testing.T) { values := [][3]float64{ {0, 0, 0}, {0.25, 0.25, 0.25}, {0.5, 0.5, 0.5}, {1.0, 1.0, 1.0}, } const tolerance = 1e-6 for i := range values { h, s, _ := hsluv.HsluvFromRGB(values[i][0], values[i][1], values[i][2]) if math.Abs(h) > tolerance { t.Errorf("Hue from grayscale %v, calculated as %f and not 0", values[i], h) } if math.Abs(s) > tolerance { t.Errorf("Saturation from grayscale %v, calculated as %f and not 0", values[i], s) } } }

References