Skip to content

Helpers

Joshua Smith edited this page May 7, 2021 · 5 revisions

Helper functions

This collection of functions are provided to make help with the initialization and capturing of values easier. They consist of methods to capture logging/printing values and wrap function that would return multiple values into an easier to use single return value. As this is often down with panic wrapping these methods should only be used in tests, not runnable code.

Table of Contents

  1. Captures
  2. Time
  3. Pointers

Output Capturing

A capture is used to redirect and store messaging being logged or printed. This is helpful when verifying logging behaves as expected or to mute excessive log messages during testing.

  • Capture output written to log, stdout or stderr.
  • Call ReadAll() to get captured data as a single string.
  • Call ReadLines() to get captured data as a []string split by newline. Calling either method closes and reset the output redirection.

CaptureLog

  c := trial.CaptureLog()
  // logic that writes to logs
  log.Print("hello")
  c.ReadAll() // -> returns hello

Note: log is reset to write to stderr

CaptureStdErr

  c := trial.CaptureStdErr()
  // write to stderr
  fmt.Fprint(os.stderr, "hello\n")
  fmt.Fprint(os.stderr, "world")
  c.ReadLines() // []string{"hello","world"}

CaptureStdOut

  c := trial.CaptureStdOut()
  // write to stdout
  fmt.Println("hello")
  fmt.Print("world")
  c.ReadLines() // []string{"hello","world"}

Time Parsing

useful to getting predefined times without having to do an error check. Invalid time parsing will result in a panic instead of an error.

  • TimeHour(s string) - uses format "2006-01-02T15"
  • TimeDay(s string) - uses format "2006-01-02"
  • Time(layout string, value)
  • Times(layout string, values ...string)
  • TimeP(layout string, s string) returns a *time.Time
v := struct{
   Time time.Time
}{Time: trial.TimeDay("2020-02-15")}

Pointer init

convenience functions for initializing a pointer to a basic type

  • int pointer
    • IntP, Int8P, Int16P, Int32P, Int64P
  • uint pointer
    • UintP, Uint8P, Uint16P, Uint32P, Uint64P
  • bool pointer - BoolP
  • float pointer
    • Float32P, Float64P
  • string pointer - StringP
Clone this wiki locally