Maths
For all the power of modern computers to perform huge sums at lightning speed, the average developer rarely uses any mathematics to do their job. But not today! Today we'll use mathematics to solve a real problem. And not boring mathematics - we're going to use trigonometry and vectors and all sorts of stuff that you always said you'd never have to use after highschool.

The Problem

You want to make an SVG of a clock. Not a digital clock - no, that would be easy - an analogue clock, with hands. You're not looking for anything fancy, just a nice function that takes a Time from the time package and spits out an SVG of a clock with all the hands - hour, minute and second - pointing in the right direction. How hard can that be?
First we're going to need an SVG of a clock for us to play with. SVGs are a fantastic image format to manipulate programmatically because they're written as a series of shapes, described in XML. So this clock: an svg of a clock
is described like this:
1
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
3
<svg xmlns="http://www.w3.org/2000/svg"
4
width="100%"
5
height="100%"
6
viewBox="0 0 300 300"
7
version="2.0">
8
9
<!-- bezel -->
10
<circle cx="150" cy="150" r="100" style="fill:#fff;stroke:#000;stroke-width:5px;"/>
11
12
<!-- hour hand -->
13
<line x1="150" y1="150" x2="114.150000" y2="132.260000"
14
style="fill:none;stroke:#000;stroke-width:7px;"/>
15
16
<!-- minute hand -->
17
<line x1="150" y1="150" x2="101.290000" y2="99.730000"
18
style="fill:none;stroke:#000;stroke-width:7px;"/>
19
20
<!-- second hand -->
21
<line x1="150" y1="150" x2="77.190000" y2="202.900000"
22
style="fill:none;stroke:#f00;stroke-width:3px;"/>
23
</svg>
Copied!
It's a circle with three lines, each of the lines starting in the middle of the circle (x=150, y=150), and ending some distance away.
So what we're going to do is reconstruct the above somehow, but change the lines so they point in the appropriate directions for a given time.

An Acceptance Test

Before we get too stuck in, lets think about an acceptance test.
Wait, you don't know what an acceptance test is yet. Look, let me try to explain.
Let me ask you: what does winning look like? How do we know we've finished work? TDD provides a good way of knowing when you've finished: when the test passes. Sometimes it's nice - actually, almost all of the time it's nice - to write a test that tells you when you've finished writing the whole usable feature. Not just a test that tells you that a particular function is working in the way you expect, but a test that tells you that the whole thing you're trying to achieve - the 'feature' - is complete.
These tests are sometimes called 'acceptance tests', sometimes called 'feature test'. The idea is that you write a really high level test to describe what you're trying to achieve - a user clicks a button on a website, and they see a complete list of the Pokémon they've caught, for instance. When we've written that test, we can then write test more tests - unit tests - that build towards a working system that will pass the acceptance test. So for our example these tests might be about rendering a webpage with a button, testing route handlers on a web server, performing database look ups, etc. All of these things will be TDD'd, and all of them will go towards making the original acceptance test pass.
Something like this classic picture by Nat Pryce and Steve Freeman img.png
Anyway, let's try and write that acceptance test - the one that will let us know when we're done.
We've got an example clock, so let's think about what the important parameters are going to be.
1
<line x1="150" y1="150" x2="114.150000" y2="132.260000"
2
style="fill:none;stroke:#000;stroke-width:7px;"/>
Copied!
The centre of the clock (the attributes x1 and y1 for this line) is the same for each hand of the clock. The numbers that need to change for each hand of the clock - the parameters to whatever builds the SVG - are the x2 and y2 attributes. We'll need an X and a Y for each of the hands of the clock.
I could think about more parameters - the radius of the clockface circle, the size of the SVG, the colours of the hands, their shape, etc... but it's better to start off by solving a simple, concrete problem with a simple, concrete solution, and then to start adding parameters to make it generalised.
So we'll say that
• every clock has a centre of (150, 150)
• the hour hand is 50 long
• the minute hand is 80 long
• the second hand is 90 long.
A thing to note about SVGs: the origin - point (0,0) - is at the top left hand corner, not the bottom left as we might expect. It'll be important to remember this when we're working out where what numbers to plug in to our lines.
Finally, I'm not deciding how to construct the SVG - we could use a template from the text/template package, or we could just send bytes into a bytes.Buffer or a writer. But we know we'll need those numbers, so let's focus on testing something that creates them.

Write the test first

So my first test looks like this:
1
package clockface_test
2
3
import (
4
"testing"
5
"time"
6
7
"github.com/gypsydave5/learn-go-with-tests/math/v1/clockface"
8
)
9
10
func TestSecondHandAtMidnight(t *testing.T) {
11
tm := time.Date(1337, time.January, 1, 0, 0, 0, 0, time.UTC)
12
13
want := clockface.Point{X: 150, Y: 150 - 90}
14
got := clockface.SecondHand(tm)
15
16
if got != want {
17
t.Errorf("Got %v, wanted %v", got, want)
18
}
19
}
Copied!
Remember how SVGs plot their coordinates from the top left hand corner? To place the second hand at midnight we expect that it hasn't moved from the centre of the clockface on the X axis - still 150 - and the Y axis is the length of the hand 'up' from the centre; 150 minus 90.

Try to run the test

This drives out the expected failures around the missing functions and types:
1
--- FAIL: TestSecondHandAtMidnight (0.00s)
2
./clockface_test.go:13:10: undefined: clockface.Point
3
./clockface_test.go:14:9: undefined: clockface.SecondHand
Copied!
So a Point where the tip of the second hand should go, and a function to get it.

Write the minimal amount of code for the test to run and check the failing test output

Let's implement those types to get the code to compile
1
package clockface
2
3
import "time"
4
5
// A Point represents a two dimensional Cartesian coordinate
6
type Point struct {
7
X float64
8
Y float64
9
}
10
11
// SecondHand is the unit vector of the second hand of an analogue clock at time `t`
12
// represented as a Point.
13
func SecondHand(t time.Time) Point {
14
return Point{}
15
}
Copied!
and now we get:
1
--- FAIL: TestSecondHandAtMidnight (0.00s)
2
clockface_test.go:17: Got {0 0}, wanted {150 60}
3
FAIL
4
exit status 1
5
FAIL github.com/gypsydave5/learn-go-with-tests/math/v1/clockface 0.006s
Copied!

Write enough code to make it pass

When we get the expected failure, we can fill in the return value of SecondHand:
1
// SecondHand is the unit vector of the second hand of an analogue clock at time `t`
2
// represented as a Point.
3
func SecondHand(t time.Time) Point {
4
return Point{150, 60}
5
}
Copied!
Behold, a passing test.
1
PASS
2
ok clockface 0.006s
Copied!

Refactor

No need to refactor yet - there's barely enough code!

Repeat for new requirements

We probably need to do some work here that doesn't just involve returning a clock that shows midnight for every time...

Write the test first

1
func TestSecondHandAt30Seconds(t *testing.T) {
2
tm := time.Date(1337, time.January, 1, 0, 0, 30, 0, time.UTC)
3
4
want := clockface.Point{X: 150, Y: 150 + 90}
5
got := clockface.SecondHand(tm)
6
7
if got != want {
8
t.Errorf("Got %v, wanted %v", got, want)
9
}
10
}
Copied!
Same idea, but now the second hand is pointing downwards so we add the length to the Y axis.
This will compile... but how do we make it pass?

Thinking time

How are we going to solve this problem?
Every minute the second hand goes through the same 60 states, pointing in 60 different directions. When it's 0 seconds it points to the top of the clockface, when it's 30 seconds it points to the bottom of the clockface. Easy enough.
So if I wanted to think about in what direction the second hand was pointing at, say, 37 seconds, I'd want the angle between 12 o'clock and 37/60ths around the circle. In degrees this is (360 / 60 ) * 37 = 222, but it's easier just to remember that it's 37/60 of a complete rotation.
But the angle is only half the story; we need to know the X and Y coordinate that the tip of the second hand is pointing at. How can we work that out?

Math

Imagine a circle with a radius of 1 drawn around the origin - the coordinate 0, 0. picture of the unit circle
This is called the 'unit circle' because... well, the radius is 1 unit!
The circumference of the circle is made of points on the grid - more coordinates. The x and y components of each of these coordinates form a triangle, the hypotenuse of which is always 1 (i.e. the radius of the circle). picture of the unit circle with a point defined on the circumference
Now, trigonometry will let us work out the lengths of X and Y for each triangle if we know the angle they make with the origin. The X coordinate will be cos(a), and the Y coordinate will be sin(a), where a is the angle made between the line and the (positive) x axis. picture of the unit circle with the x and y elements of a ray defined as cos(a) and sin(a) respectively, where a is the angle made by the ray with the x axis
(If you don't believe this, go and look at Wikipedia...)
One final twist - because we want to measure the angle from 12 o'clock rather than from the X axis (3 o'clock), we need to swap the axis around; now x = sin(a) and y = cos(a). unit circle ray defined from by angle from y axis
So now we know how to get the angle of the second hand (1/60th of a circle for each second) and the X and Y coordinates. We'll need functions for both sin and cos.

math

Happily the Go math package has both, with one small snag we'll need to get our heads around; if we look at the description of math.Cos:
Cos returns the cosine of the radian argument x.
It wants the angle to be in radians. So what's a radian? Instead of defining the full turn of a circle to be made up of 360 degrees, we define a full turn as being 2π radians. There are good reasons to do this that we won't go in to.[^2]
Now that we've done some reading, some learning and some thinking, we can write our next test.

Write the test first

All this maths is hard and confusing. I'm not confident I understand what's going on - so let's write a test! We don't need to solve the whole problem in one go - let's start off with working out the correct angle, in radians, for the second hand at a particular time.
I'm going to write these tests within the clockface package; they may never get exported, and they may get deleted (or moved) once I have a better grip on what's going on.
I'm also going to comment out the acceptance test that I was working on while I'm working on these tests - I don't want to get distracted by that test while I'm getting this one to pass.
1
package clockface
2
3
import (
4
"math"
5
"testing"
6
"time"
7
)
8
9
10
thirtySeconds := time.Date(312, time.October, 28, 0, 0, 30, 0, time.UTC)
11
want := math.Pi
12
13
14
if want != got {
15
t.Fatalf("Wanted %v radians, but got %v", want, got)
16
}
17
}
Copied!
Here we're testing that 30 seconds past the minute should put the second hand at halfway around the clock. And it's our first use of the math package! If a full turn of a circle is 2π radians, we know that halfway round should just be π radians. math.Pi provides us with a value for π.

1
Copied!

Write the minimal amount of code for the test to run and check the failing test output

1
2
return 0
3
}
Copied!
1
clockface_test.go:15: Wanted 3.141592653589793 radians, but got 0
Copied!

Write enough code to make it pass

1
2
return math.Pi
3
}
Copied!
1
PASS
2
ok clockface 0.011s
Copied!

Refactor

Nothing needs refactoring yet

Repeat for new requirements

Now we can extend the test to cover a few more scenarios. I'm going to skip forward a bit and show some already refactored test code - it should be clear enough how I got where I want to.
1
2
cases := []struct {
3
time time.Time
4
angle float64
5
}{
6
{simpleTime(0, 0, 30), math.Pi},
7
{simpleTime(0, 0, 0), 0},
8
{simpleTime(0, 0, 45), (math.Pi / 2) * 3},
9
{simpleTime(0, 0, 7), (math.Pi / 30) * 7},
10
}
11
12
for _, c := range cases {
13
t.Run(testName(c.time), func(t *testing.T) {
14
15
if got != c.angle {
16
t.Fatalf("Wanted %v radians, but got %v", c.angle, got)
17
}
18
})
19
}
20
}
Copied!
I added a couple of helper functions to make writing this table based test a little less tedious. testName converts a time into a digital watch format (HH:MM:SS), and simpleTime constructs a time.Time using only the parts we actually care about (again, hours, minutes and seconds).[^1] Here they are:
1
func simpleTime(hours, minutes, seconds int) time.Time {
2
return time.Date(312, time.October, 28, hours, minutes, seconds, 0, time.UTC)
3
}
4
5
func testName(t time.Time) string {
6
return t.Format("15:04:05")
7
}
Copied!
These two functions should help make these tests (and future tests) a little easier to write and maintain.
This gives us some nice test output:
1
clockface_test.go:24: Wanted 0 radians, but got 3.141592653589793
2
3
clockface_test.go:24: Wanted 4.71238898038469 radians, but got 3.141592653589793
Copied!
Time to implement all of that maths stuff we were talking about above:
1
2
return float64(t.Second()) * (math.Pi / 30)
3
}
Copied!
One second is (2π / 60) radians... cancel out the 2 and we get π/30 radians. Multiply that by the number of seconds (as a float64) and we should now have all the tests passing...
1
clockface_test.go:24: Wanted 3.141592653589793 radians, but got 3.1415926535897936
Copied!
Wait, what?

Floats are horrible

Floating point arithmetic is notoriously inaccurate. Computers can only really handle integers, and rational numbers to some extent. Decimal numbers start to become inaccurate, especially when we factor them up and down as we are in the secondsInRadians function. By dividing math.Pi by 30 and then by multiplying it by 30 we've ended up with a number that's no longer the same as math.Pi.
There are two ways around this:
1. 1.
Live with it
2. 2.
Refactor our function by refactoring our equation
Now (1) may not seem all that appealing, but it's often the only way to make floating point equality work. Being inaccurate by some infinitesimal fraction is frankly not going to matter for the purposes of drawing a clockface, so we could write a function that defines a 'close enough' equality for our angles. But there's a simple way we can get the accuracy back: we rearrange the equation so that we're no longer dividing down and then multiplying up. We can do it all by just dividing.
1
numberOfSeconds * π / 30
Copied!
we can write
1
π / (30 / numberOfSeconds)
Copied!
which is equivalent.
In Go:
1
2
return (math.Pi / (30 / (float64(t.Second()))))
3
}
Copied!
And we get a pass.
1
PASS
2
ok clockface 0.005s
Copied!
It should all look something like this.

A note on dividing by zero

Computers often don't like dividing by zero because infinity is a bit strange.
In Go if you try to explicitly divide by zero you will get a compilation error.
1
package main
2
3
import (
4
"fmt"
5
)
6
7
func main() {
8
fmt.Println(10.0 / 0.0) // fails to compile
9
}
Copied!
Obviously the compiler can't always predict that you'll divide by zero, such as our t.Second()
Try this
1
func main() {
2
fmt.Println(10.0 / zero())
3
}
4
5
func zero() float64 {
6
return 0.0
7
}
Copied!
It will print +Inf (infinity). Dividing by +Inf seems to result in zero and we can see this with the following:
1
package main
2
3
import (
4
"fmt"
5
"math"
6
)
7
8
func main() {
9
10
}
11
12
func zero() float64 {
13
return 0.0
14
}
15
16
17
return (math.Pi / (30 / (float64(zero()))))
18
}
Copied!

Repeat for new requirements

So we've got the first part covered here - we know what angle the second hand will be pointing at in radians. Now we need to work out the coordinates.
Again, let's keep this as simple as possible and only work with the unit circle; the circle with a radius of 1. This means that our hands will all have a length of one but, on the bright side, it means that the maths will be easy for us to swallow.

Write the test first

1
func TestSecondHandVector(t *testing.T) {
2
cases := []struct {
3
time time.Time
4
point Point
5
}{
6
{simpleTime(0, 0, 30), Point{0, -1}},
7
}
8
9
for _, c := range cases {
10
t.Run(testName(c.time), func(t *testing.T) {
11
got := secondHandPoint(c.time)
12
if got != c.point {
13
t.Fatalf("Wanted %v Point, but got %v", c.point, got)
14
}
15
})
16
}
17
}
Copied!

Try to run the test

1
./clockface_test.go:40:11: undefined: secondHandPoint
Copied!

Write the minimal amount of code for the test to run and check the failing test output

1
func secondHandPoint(t time.Time) Point {
2
return Point{}
3
}
Copied!
1
clockface_test.go:42: Wanted {0 -1} Point, but got {0 0}
Copied!

Write enough code to make it pass

1
func secondHandPoint(t time.Time) Point {
2
return Point{0, -1}
3
}
Copied!
1
PASS
2
ok clockface 0.007s
Copied!

Repeat for new requirements

1
func TestSecondHandPoint(t *testing.T) {
2
cases := []struct {
3
time time.Time
4
point Point
5
}{
6
{simpleTime(0, 0, 30), Point{0, -1}},
7
{simpleTime(0, 0, 45), Point{-1, 0}},
8
}
9
10
for _, c := range cases {
11
t.Run(testName(c.time), func(t *testing.T) {
12
got := secondHandPoint(c.time)
13
if got != c.point {
14
t.Fatalf("Wanted %v Point, but got %v", c.point, got)
15
}
16
})
17
}
18
}
Copied!

Try to run the test

1
clockface_test.go:43: Wanted {-1 0} Point, but got {0 -1}
Copied!

Write enough code to make it pass

Remember our unit circle picture? picture of the unit circle with the x and y elements of a ray defined as cos(a) and sin(a) respectively, where a is the angle made by the ray with the x axis
Also recall that we want to measure the angle from 12 o'clock which is the Y axis instead of from the X axis which we would like measuring the angle between the second hand and 3 o'clock. unit circle ray defined from by angle from y axis
We now want the equation that produces X and Y. Let's write it into seconds:
1
func secondHandPoint(t time.Time) Point {
2
3
x := math.Sin(angle)
4
y := math.Cos(angle)
5
6
return Point{x, y}
7
}
Copied!
Now we get
1
clockface_test.go:43: Wanted {0 -1} Point, but got {1.2246467991473515e-16 -1}
2
3
clockface_test.go:43: Wanted {-1 0} Point, but got {-1 -1.8369701987210272e-16}
Copied!
Wait, what (again)? Looks like we've been cursed by the floats once more - both of those unexpected numbers are infinitesimal - way down at the 16th decimal place. So again we can either choose to try to increase precision, or to just say that they're roughly equal and get on with our lives.
One option to increase the accuracy of these angles would be to use the rational type Rat from the math/big package. But given the objective is to draw an SVG and not land on the moon landings I think we can live with a bit of fuzziness.
1
func TestSecondHandPoint(t *testing.T) {
2
cases := []struct {
3
time time.Time
4
point Point
5
}{
6
{simpleTime(0, 0, 30), Point{0, -1}},
7
{simpleTime(0, 0, 45), Point{-1, 0}},
8
}
9
10
for _, c := range cases {
11
t.Run(testName(c.time), func(t *testing.T) {
12
got := secondHandPoint(c.time)
13
if !roughlyEqualPoint(got, c.point) {
14
t.Fatalf("Wanted %v Point, but got %v", c.point, got)
15
}
16
})
17
}
18
}
19
20
func roughlyEqualFloat64(a, b float64) bool {
21
const equalityThreshold = 1e-7
22
return math.Abs(a-b) < equalityThreshold
23
}
24
25
func roughlyEqualPoint(a, b Point) bool {
26
return roughlyEqualFloat64(a.X, b.X) &&
27
roughlyEqualFloat64(a.Y, b.Y)
28
}
Copied!
We've defined two functions to define approximate equality between two Points - they'll work if the X and Y elements are within 0.0000001 of each other. That's still pretty accurate.
And now we get:
1
PASS
2
ok clockface 0.007s
Copied!

Refactor

I'm still pretty happy with this.

Repeat for new requirements

Well, saying new isn't entirely accurate - really what we can do now is get that acceptance test passing! Let's remind ourselves of what it looks like:
1
func TestSecondHandAt30Seconds(t *testing.T) {
2
tm := time.Date(1337, time.January, 1, 0, 0, 30, 0, time.UTC)
3
4
want := clockface.Point{X: 150, Y: 150 + 90}
5
got := clockface.SecondHand(tm)
6
7
if got != want {
8
t.Errorf("Got %v, wanted %v", got, want)
9
}
10
}
Copied!

Try to run the test

1
clockface_acceptance_test.go:28: Got {150 60}, wanted {150 240}
Copied!

Write enough code to make it pass

We need to do three things to convert our unit vector into a point on the SVG:
1. 1.
Scale it to the length of the hand
2. 2.
Flip it over the X axis because to account for the SVG having an origin in the top left hand corner
3. 3.
Translate it to the right position (so that it's coming from an origin of (150,150))
Fun times!
1
// SecondHand is the unit vector of the second hand of an analogue clock at time `t`
2
// represented as a Point.
3
func SecondHand(t time.Time) Point {
4
p := secondHandPoint(t)
5
p = Point{p.X * 90, p.Y * 90} // scale
6
p = Point{p.X, -p.Y} // flip
7
p = Point{p.X + 150, p.Y + 150} // translate
8
return p
9
}
Copied!
Scale, flip, and translate in exactly that order. Hooray maths!
1
PASS
2
ok clockface 0.007s
Copied!

Refactor

There's a few magic numbers here that should get pulled out as constants, so let's do that
1
const secondHandLength = 90
2
const clockCentreX = 150
3
const clockCentreY = 150
4
5
// SecondHand is the unit vector of the second hand of an analogue clock at time `t`
6
// represented as a Point.
7
func SecondHand(t time.Time) Point {
8
p := secondHandPoint(t)
9
p = Point{p.X * secondHandLength, p.Y * secondHandLength}
10
p = Point{p.X, -p.Y}
11
p = Point{p.X + clockCentreX, p.Y + clockCentreY} //translate
12
return p
13
}
Copied!

Draw the clock

Well... the second hand anyway...
Let's do this thing - because there's nothing worse than not delivering some value when it's just sitting there waiting to get out into the world to dazzle people. Let's draw a second hand!
We're going to stick a new directory under our main clockface package directory, called (confusingly), clockface. In there we'll put the main package that will create the binary that will build an SVG:
1
|-- clockface
2
| |-- main.go
3
|-- clockface.go
4
|-- clockface_acceptance_test.go
5
|-- clockface_test.go
Copied!
Inside main.go, you'll start with this code but change the import for the clockface package to point at your own version:
1
package main
2
3
import (
4
"fmt"
5
"io"
6
"os"
7
"time"
8
9
"github.com/quii/learn-go-with-tests/math/clockface" // REPLACE THIS!
10
)
11
12
func main() {
13
t := time.Now()
14
sh := clockface.SecondHand(t)
15
io.WriteString(os.Stdout, svgStart)
16
io.WriteString(os.Stdout, bezel)
17
io.WriteString(os.Stdout, secondHandTag(sh))
18
io.WriteString(os.Stdout, svgEnd)
19
}
20
21
func secondHandTag(p clockface.Point) string {
22
return fmt.Sprintf(`<line x1="150" y1="150" x2="%f" y2="%f" style="fill:none;stroke:#f00;stroke-width:3px;"/>`, p.X, p.Y)
23
}
24
25
const svgStart = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
26
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
27
<svg xmlns="http://www.w3.org/2000/svg"
28
width="100%"
29
height="100%"
30
viewBox="0 0 300 300"
31
version="2.0">`
32
33
const bezel = `<circle cx="150" cy="150" r="100" style="fill:#fff;stroke:#000;stroke-width:5px;"/>`
34
35
const svgEnd = `</svg>`
Copied!
Oh boy am I not trying to win any prizes for beautiful code with this mess - but it does the job. It's writing an SVG out to os.Stdout - one string at a time.
If we build this
1
go build
Copied!
and run it, sending the output into a file
1
./clockface > clock.svg
Copied!
We should see something like a clock with only a second hand
And this is how the code looks.

Refactor

This stinks. Well, it doesn't quite stink stink, but I'm not happy about it.
1. 1.
That whole SecondHand function is super tied to being an SVG... without mentioning SVGs or actually producing an SVG...
2. 2.
... while at the same time I'm not testing any of my SVG code.
Yeah, I guess I screwed up. This feels wrong. Let's try to recover with a more SVG-centric test.
What are our options? Well, we could try testing that the characters spewing out of the SVGWriter contain things that look like the sort of SVG tag we're expecting for a particular time. For instance:
1
func TestSVGWriterAtMidnight(t *testing.T) {
2
tm := time.Date(1337, time.January, 1, 0, 0, 0, 0, time.UTC)
3
4
var b strings.Builder
5
clockface.SVGWriter(&b, tm)
6
got := b.String()
7
8
want := `<line x1="150" y1="150" x2="150" y2="60"`
9
10
if !strings.Contains(got, want) {
11
t.Errorf("Expected to find the second hand %v, in the SVG output %v", want, got)
12
}
13
}
Copied!
But is this really an improvement?
Not only will it still pass if I don't produce a valid SVG (as it's only testing that a string appears in the output), but it will also fail if I make the smallest, unimportant change to that string - if I add an extra space between the attributes, for instance.
The biggest smell is that I'm testing a data structure - XML - by looking at its representation as a series of characters - as a string. This is never, ever a good idea as it produces problems just like the ones I outline above: a test that's both too fragile and not sensitive enough. A test that's testing the wrong thing!
So the only solution is to test the output as XML. And to do that we'll need to parse it.

Parsing XML

encoding/xml is the Go package that can handle all things to do with simple XML parsing.
The function xml.Unmarshall takes a []byte of XML data, and a pointer to a struct for it to get unmarshalled in to.
So we'll need a struct to unmarshall our XML into. We could spend some time working out what the correct names for all of the nodes and attributes, and how to write the correct structure but, happily, someone has written zek a program that will automate all of that hard work for us. Even better, there's an online version at https://www.onlinetool.io/xmltogo/. Just paste the SVG from the top of the file into one box and - bam - out pops:
1
type Svg struct {
2
XMLName xml.Name `xml:"svg"`
3
Text string `xml:",chardata"`
4
Xmlns string `xml:"xmlns,attr"`
5
Width string `xml:"width,attr"`
6
Height string `xml:"height,attr"`
7
ViewBox string `xml:"viewBox,attr"`
8
Version string `xml:"version,attr"`
9
Circle struct {
10
Text string `xml:",chardata"`
11
Cx string `xml:"cx,attr"`
12
Cy string `xml:"cy,attr"`
13
R string `xml:"r,attr"`
14
Style string `xml:"style,attr"`
15
} `xml:"circle"`
16
Line []struct {
17
Text string `xml:",chardata"`
18
X1 string `xml:"x1,attr"`
19
Y1 string `xml:"y1,attr"`
20
X2 string `xml:"x2,attr"`
21
Y2 string `xml:"y2,attr"`
22
Style string `xml:"style,attr"`
23
} `xml:"line"`
24
}
Copied!
We could make adjustments to this if we needed to (like changing the name of the struct to SVG) but it's definitely good enough to start us off. Paste the struct into the clockface_test file and let's write a test with it:
1
func TestSVGWriterAtMidnight(t *testing.T) {
2
tm := time.Date(1337, time.January, 1, 0, 0, 0, 0, time.UTC)
3
4
b := bytes.Buffer{}
5
clockface.SVGWriter(&b, tm)
6
7
svg := Svg{}
8
xml.Unmarshal(b.Bytes(), &svg)
9
10
x2 := "150"
11
y2 := "60"
12
13
for _, line := range svg.Line {
14
if line.X2 == x2 && line.Y2 == y2 {
15
return
16
}
17
}
18
19
t.Errorf("Expected to find the second hand with x2 of %+v and y2 of %+v, in the SVG output %v", x2, y2, b.String())
20
}
Copied!
We write the output of clockface.SVGWriter to a bytes.Buffer and then Unmarshall it into an Svg. We then look at each Line in the Svg to see if any of them have the expected X2 and Y2 values. If we get a match we return early (passing the test); if not we fail with a (hopefully) informative message.
1
./clockface_acceptance_test.go:41:2: undefined: clockface.SVGWriter
Copied!
Looks like we'd better write that SVGWriter...
1
package clockface
2
3
import (
4
"fmt"
5
"io"
6
"time"
7
)
8
9
const (
10
secondHandLength = 90
11
clockCentreX = 150
12
clockCentreY = 150
13
)
14
15
//SVGWriter writes an SVG representation of an analogue clock, showing the time t, to the writer w
16
func SVGWriter(w io.Writer, t time.Time) {
17
io.WriteString(w, svgStart)
18
io.WriteString(w, bezel)
19
secondHand(w, t)
20
io.WriteString(w, svgEnd)
21
}
22
23
func secondHand(w io.Writer, t time.Time) {
24
p := secondHandPoint(t)
25
p = Point{p.X * secondHandLength, p.Y * secondHandLength} // scale
26
p = Point{p.X, -p.Y} // flip
27
p = Point{p.X + clockCentreX, p.Y + clockCentreY} // translate
28
fmt.Fprintf(w, `<line x1="150" y1="150" x2="%f" y2="%f" style="fill:none;stroke:#f00;stroke-width:3px;"/>`, p.X, p.Y)
29
}
30
31
const svgStart = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
32
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
33
<svg xmlns="http://www.w3.org/2000/svg"
34
width="100%"
35
height="100%"
36
viewBox="0 0 300 300"
37
version="2.0">`
38
39
const bezel = `<circle cx="150" cy="150" r="100" style="fill:#fff;stroke:#000;stroke-width:5px;"/>`
40
41
const svgEnd = `</svg>`
Copied!
The most beautiful SVG writer? No. But hopefully it'll do the job...
1
clockface_acceptance_test.go:56: Expected to find the second hand with x2 of 150 and y2 of 60, in the SVG output <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
3
<svg xmlns="http://www.w3.org/2000/svg"
4
width="100%"
5
height="100%"
6
viewBox="0 0 300 300"
7
version="2.0"><circle cx="150" cy="150" r="100" style="fill:#fff;stroke:#000;stroke-width:5px;"/><line x1="150" y1="150" x2="150.000000" y2="60.000000" style="fill:none;stroke:#f00;stroke-width:3px;"/></svg>
Copied!
Oooops! The %f format directive is printing our coordinates to the default level of precision - six decimal places. We should be explicit as to what level of precision we're expecting for the coordinates. Let's say three decimal places.
1
fmt.Fprintf(w, `<line x1="150" y1="150" x2="%.3f" y2="%.3f" style="fill:none;stroke:#f00;stroke-width:3px;"/>`, p.X, p.Y)
Copied!
And after we update our expectations in the test
1
x2 := "150.000"
2
y2 := "60.000"
Copied!
We get:
1
PASS
2
ok clockface 0.006s
Copied!
We can now shorten our main function:
1
package main
2
3
import (
4
"os"
5
"time"
6
7
"github.com/gypsydave5/learn-go-with-tests/math/v7b/clockface"
8
)
9
10
func main() {
11
t := time.Now()
12
clockface.SVGWriter(os.Stdout, t)
13
}
Copied!
And we can write a test for another time following the same pattern, but not before...

Refactor

Three things stick out:
1. 1.
We're not really testing for all of the information we need to ensure is present - what about the x1 values, for instance?
2. 2.
Also, those attributes for x1 etc. aren't really strings are they? They're numbers!
3. 3.
Do I really care about the style of the hand? Or, for that matter, the empty Text node that's been generated by zak?
We can do better. Let's make a few adjustments to the Svg struct, and the tests, to sharpen everything up.
1
type SVG struct {
2
XMLName xml.Name `xml:"svg"`
3
Xmlns string `xml:"xmlns,attr"`
4
Width string `xml:"width,attr"`
5
Height string `xml:"height,attr"`
6
ViewBox string `xml:"viewBox,attr"`
7
Version string `xml:"version,attr"`
8
Circle Circle `xml:"circle"`
9
Line []Line `xml:"line"`
10
}
11
12
type Circle struct {
13
Cx float64 `xml:"cx,attr"`
14
Cy float64 `xml:"cy,attr"`
15
R float64 `xml:"r,attr"`
16
}
17
18
type Line struct {
19
X1 float64 `xml:"x1,attr"`
20
Y1 float64 `xml:"y1,attr"`
21
X2 float64 `xml:"x2,attr"`
22
Y2 float64 `xml:"y2,attr"`
23
}
Copied!
Here I've
• Made the important parts of the struct named types -- the Line and the Circle
• Turned the numeric attributes into float64s instead of strings.
• Deleted unused attributes like Style and Text
• Renamed Svg to SVG because it's the right thing to do.
This will let us assert more precisely on the line we're looking for:
1
func TestSVGWriterAtMidnight(t *testing.T) {
2
tm := time.Date(1337, time.January, 1, 0, 0, 0, 0, time.UTC)
3
b := bytes.Buffer{}
4
5
clockface.SVGWriter(&b, tm)
6
7
svg := SVG{}
8
9
xml.Unmarshal(b.Bytes(), &svg)
10
11
want := Line{150, 150, 150, 60}
12
13
for _, line := range svg.Line {
14
if line == want {
15
return
16
}
17
}
18
19
t.Errorf("Expected to find the second hand line %+v, in the SVG lines %+v", want, svg.Line)
20
}
Copied!
Finally we can take a leaf out of the unit tests' tables, and we can write a helper function containsLine(line Line, lines []Line) bool to really make these tests shine:
1
func TestSVGWriterSecondHand(t *testing.T) {
2
cases := []struct {
3
time time.Time
4
line Line
5
}{
6
{
7
simpleTime(0, 0, 0),
8
Line{150, 150, 150, 60},
9
},
10
{
11
simpleTime(0, 0, 30),
12
Line{150, 150, 150, 240},
13
},
14
}
15
16
for _, c := range cases {
17
t.Run(testName(c.time), func(t *testing.T) {
18
b := bytes.Buffer{}
19
clockface.SVGWriter(&b, c.time)
20
21
svg := SVG{}
22
xml.Unmarshal(b.Bytes(), &svg)
23
24
if !containsLine(c.line, svg.Line) {
25
t.Errorf("Expected to find the second hand line %+v, in the SVG lines %+v", c.line, svg.Line)
26
}
27
})
28
}
29
}
30
31
func containsLine(l Line, ls []Line) bool {
32
for _, line := range ls {
33
if line == l {
34
return true
35
}
36
}
37
return false
38
}
Copied!
Here's what it looks like
Now that's what I call an acceptance test!

Write the test first

So that's the second hand done. Now let's get started on the minute hand.
1
func TestSVGWriterMinuteHand(t *testing.T) {
2
cases := []struct {
3
time time.Time
4
line Line
5
}{
6
{
7
simpleTime(0, 0, 0),
8
Line{150, 150, 150, 70},
9
},
10
}
11
12
for _, c := range cases {
13
t.Run(testName(c.time), func(t *testing.T) {
14
b := bytes.Buffer{}
15
clockface.