Advent-of-Code/year25/tests/utils_test.go
2025-12-09 01:58:04 +02:00

84 lines
1.7 KiB
Go

package main_test
import (
"bytes"
"fmt"
"io"
"log"
"os"
"testing"
"time"
"git.bizdoc.ro/gabi-public/Advent-of-Code.git/aoc"
)
func getInput(name string) io.Reader {
name = fmt.Sprintf("./data/%s.txt", name)
input, err := os.ReadFile(name)
if err != nil {
panic(err)
}
return bytes.NewReader(input)
}
func assert(t *testing.T, err error, a, b any) {
t.Helper()
if err != nil {
t.Error(err)
}
want := fmt.Sprintf("%v", a)
got := fmt.Sprintf("%v", b)
if got != want {
err = fmt.Errorf("want %s, got %s", want, got)
t.Error(err)
}
}
type TestCase struct {
Name string
File string
Want any
Handler func(ctx aoc.Context) (any, error)
}
var StderrLogger = log.New(os.Stderr, "", 0)
var DiscardLogger = log.New(io.Discard, "", 0)
func handler[T any](f func(ctx aoc.Context) (T, error)) func(ctx aoc.Context) (any, error) {
return func(c aoc.Context) (any, error) {
return f(c)
}
}
func handler2[T any, K any](param T, f func(ctx aoc.Context, param T) (K, error)) func(ctx aoc.Context) (any, error) {
return func(c aoc.Context) (any, error) {
return f(c, param)
}
}
func runTestCase(t *testing.T, cases []TestCase, l *log.Logger) {
t.Helper()
var totalTime time.Duration
defer func() {
t.Log("Total time:", totalTime.String())
}()
for _, test := range cases {
t.Run(test.Name, func(t *testing.T) {
start := time.Now()
defer func() {
end := time.Since(start)
t.Log("elapsed:", end)
totalTime += end
}()
input := getInput(test.File)
if test.Handler == nil {
t.Fatalf("%s handler is nil", test.Name)
}
got, err := test.Handler(aoc.Context{Body: input, Logger: l})
assert(t, err, test.Want, got)
})
}
}