github.com/ethersphere/bee/v2@v2.2.0/pkg/jsonhttp/jsonhttptest/testing_mock_test.go (about)

     1  // Copyright 2020 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package jsonhttptest_test
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"reflect"
    11  	"sort"
    12  	"testing"
    13  )
    14  
    15  type testResult struct {
    16  	errors []string
    17  	fatal  string
    18  }
    19  
    20  // assert is a test helper that validates a functionality of another helper
    21  // function by mocking Errorf, Fatal and Helper methods on testing.TB.
    22  func assert(t *testing.T, want testResult, f func(m *mock)) {
    23  	t.Helper()
    24  
    25  	defer func() {
    26  		if v := recover(); v != nil {
    27  			if err, ok := v.(error); ok && errors.Is(err, errFailed) {
    28  				return // execution of the goroutine is stopped by a mock Fatal function
    29  			}
    30  			t.Fatalf("panic: %v", v)
    31  		}
    32  	}()
    33  
    34  	m := &mock{}
    35  
    36  	f(m)
    37  
    38  	if !m.isHelper { // Request function is tested and it must be always a helper
    39  		t.Error("not a helper function")
    40  	}
    41  
    42  	gotErrors := sort.StringSlice(m.got.errors)
    43  	wantErrors := sort.StringSlice(want.errors)
    44  	if !reflect.DeepEqual(gotErrors, wantErrors) {
    45  		t.Errorf("errors not as expected: got  %v, want %v", gotErrors, wantErrors)
    46  	}
    47  
    48  	if m.got.fatal != want.fatal {
    49  		t.Errorf("got error %v, want %v", m.got.fatal, want.fatal)
    50  	}
    51  }
    52  
    53  // mock provides the same interface as testing.TB with overridden Errorf, Fatal
    54  // and Heleper methods.
    55  type mock struct {
    56  	testing.TB
    57  	isHelper bool
    58  	got      testResult
    59  }
    60  
    61  func (m *mock) Helper() {
    62  	m.isHelper = true
    63  }
    64  
    65  func (m *mock) Errorf(format string, args ...interface{}) {
    66  	m.got.errors = append(m.got.errors, fmt.Sprintf(format, args...))
    67  }
    68  
    69  func (m *mock) Fatal(args ...interface{}) {
    70  	m.got.fatal = fmt.Sprint(args...)
    71  	panic(errFailed) // terminate the goroutine to detect it in the assert function
    72  }
    73  
    74  var errFailed = errors.New("failed")