github.com/freiheit-com/kuberpult@v1.24.2-0.20240328135542-315d5630abe6/pkg/logger/testlogger/testlogger.go (about)

     1  /*This file is part of kuberpult.
     2  
     3  Kuberpult is free software: you can redistribute it and/or modify
     4  it under the terms of the Expat(MIT) License as published by
     5  the Free Software Foundation.
     6  
     7  Kuberpult is distributed in the hope that it will be useful,
     8  but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    10  MIT License for more details.
    11  
    12  You should have received a copy of the MIT License
    13  along with kuberpult. If not, see <https://directory.fsf.org/wiki/License:Expat>.
    14  
    15  Copyright 2023 freiheit.com*/
    16  
    17  package testlogger
    18  
    19  import (
    20  	"context"
    21  	"testing"
    22  
    23  	"go.uber.org/zap"
    24  	"go.uber.org/zap/zaptest/observer"
    25  
    26  	"github.com/freiheit-com/kuberpult/pkg/logger"
    27  )
    28  
    29  func Wrap(ctx context.Context, inner func(ctx context.Context)) *observer.ObservedLogs {
    30  	config, obs := observer.New(zap.DebugLevel)
    31  	log := zap.New(config)
    32  	defer func() {
    33  		if err := log.Sync(); err != nil {
    34  			panic(err)
    35  		}
    36  	}()
    37  	inner(logger.WithLogger(ctx, log))
    38  	return obs
    39  }
    40  
    41  func AssertEmpty(t *testing.T, logs *observer.ObservedLogs) {
    42  	l := logs.All()
    43  	if len(l) != 0 {
    44  		t.Errorf("expected no logs, but got %d\nexample: \t%#v", len(l), l[0])
    45  	}
    46  }
    47  
    48  type LogAssertion func(*testing.T, observer.LoggedEntry)
    49  
    50  func AssertLogs(t *testing.T, logs *observer.ObservedLogs, tests ...LogAssertion) {
    51  	l := logs.All()
    52  	if len(l) > len(tests) {
    53  		t.Errorf("expected %d logs, but got %d\nexample: \t%#v", len(tests), len(l), l[len(tests)])
    54  	} else if len(l) < len(tests) {
    55  		t.Errorf("expected %d logs, but got %d", len(tests), len(l))
    56  	} else {
    57  		for i, j := range l {
    58  			tests[i](t, j)
    59  		}
    60  	}
    61  }