Skip to content

Instantly share code, notes, and snippets.

@nnathan
Created February 28, 2016 16:54
Show Gist options
  • Save nnathan/9a5b1e39976a8c34cf9d to your computer and use it in GitHub Desktop.
Save nnathan/9a5b1e39976a8c34cf9d to your computer and use it in GitHub Desktop.
testing notes from go

Lessons learned testing in Go

  • components should be silent when on the road, noisy when manufacturing

    • log/printf for debugging as you develop
  • use testing to help eliminate noise as your components are built

    • look at test output, when everything reads PASS, everything should be quiet. That means no more remaining log/printf output!
  • good unit tests help eliminate noise; less noise = more coverage!

  • exploit table-driven tests

  • aid yourself with good messages, visual cues, etc.

  • logging in your tests can give huge wins for debugging, especially when you enter/exit a test case with obvious cues like BEGIN/END headers

  • if you're doing something clever or trying to mock a concrete implementation (like somehow "injecting stdin"), then you're doing something wrong; being unable to mock or fighting the testing framework means you're doing something wrong

  • avoid the temptation using testing frameworks like testify as a crutch, less is more i know how it feels when someone doesn't hold your hand :(

Exercise in testing

Example Implementation:

    ParseEvenNumberLines(pathname string), int[], error

Input:

# header comment

# even numbers
6 # finally a good even number! (oh and comments can be in-line)
8

# odd numbers
5
1341 # end bad numbers

# back to the good shit
10
20

An exercise in futility:

Do the following:

  1. Implement ParseEvenNumberLines(pathname string), int[], error

    • return all parsed even numbers until first error
    • pathname == "-" should read from stdin
    • feel free to leave logging all over the place using log.Errorf
      • useful to show the raw line, transformations at every stage, etc.
  2. Now get 100% test coverage :)

    • load named tempfiles and feed it in
    • try using log.SetOutput to write to stdin for testing with filename "-"
  3. So you probably found yourself being too clever. Find a way to make your implementation testable. Do you really have to rely on named files? Seems yuck right? Well it bloody is!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment