package main

import (
  "bytes"
  "fmt"
  "io"
  "os"
  "strings"
  "testing"
)

// Test the main default settings
func TestPersons(t *testing.T) {

  if len(Persons) != 2 {
    t.Error("Must be 2 persons")
  }

  if Persons[0].Name != "Timo" {
    t.Error("Must be Timo")
  }

  if Persons[1].Name != "Xenia" {
    t.Error("Must be Xenia")
  }
}

func TestMainMethod(t *testing.T) {

  // Capture Stdout for test
  old := os.Stdout // keep backup of the real stdout
  r, w, _ := os.Pipe()
  os.Stdout = w

  // The real test
  main()

  // Analyse capture output
  outC := make(chan string)
  go func() {
    var buf bytes.Buffer
    io.Copy(&buf, r)
    outC <- buf.String()
  }()

  // back to normal state
  w.Close()
  os.Stdout = old // restoring the real stdout

  // Wait for output from go routine
  out := <-outC

  // Check the output
  testStr := fmt.Sprintf("Hello Karl Gustav from golang!\nSay hello to persons in array:\nHello Timo you are 42 years old!\nHello Xenia you are 36 years old!")

  if !strings.Contains(out, testStr) {
    t.Error("ERROR: String must be ", testStr)
  }
}


