Skip to content

Instantly share code, notes, and snippets.

@maratori
Created July 29, 2022 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maratori/425facf6450dad263ed990dbeb25bca6 to your computer and use it in GitHub Desktop.
Save maratori/425facf6450dad263ed990dbeb25bca6 to your computer and use it in GitHub Desktop.
TestMain to print logs if failed
package componenttests
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
)
func TestMain(m *testing.M) {
deleteAllLogs(".")
result := m.Run()
if result != 0 {
if _, exists := os.LookupEnv("CI"); exists {
fmt.Print("\n\nSome test failed. Find and print logs.\n\n\n")
printLogsForCI(".")
} else {
dir, err := filepath.Abs("logs")
if err != nil {
dir = "logs"
}
fmt.Printf("\n\nSome test failed. You can find logs here: %s\n\n\n", dir)
}
}
os.Exit(result)
}
func deleteAllLogs(root string) {
_ = filepath.Walk(root, func(relativePath string, info os.FileInfo, e error) error {
path, err := filepath.Abs(relativePath)
if err != nil {
path = relativePath
}
if e != nil {
fmt.Printf("Failed to access path %q: %v\n", path, e)
return e
}
if info.IsDir() {
return nil
}
if filepath.Ext(path) != ".log" {
return nil
}
err = os.Remove(path)
if err != nil {
fmt.Printf("Can't delete log %s: %v\n", path, err)
return nil
}
fmt.Printf("Log deleted %s\n", path)
return nil
})
}
func printLogsForCI(root string) {
_ = filepath.Walk(root, func(relativePath string, info os.FileInfo, e error) error {
path, err := filepath.Abs(relativePath)
if err != nil {
path = relativePath
}
if e != nil {
fmt.Printf("Failed to access path %q: %v\n", path, e)
return e
}
if info.IsDir() {
return nil
}
if filepath.Ext(path) != ".log" {
return nil
}
name := strings.ReplaceAll(info.Name(), " ", "_")
fmt.Printf("::group::%s\n", name)
fmt.Printf("=== Found log: %s\n\n", path)
printFile(path)
fmt.Printf("::endgroup::%s\n", name)
return nil
})
}
func printFile(path string) {
file, err := os.Open(path)
if err != nil {
fmt.Printf("Failed to open file %q: %v\n", path, err)
return
}
_, err = io.Copy(os.Stdout, file)
if err != nil {
fmt.Printf("Failed to print file content %q: %v\n", path, err)
return
}
fmt.Print("\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment