github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/services/wireguard/service/stats_publisher_test.go (about)

     1  /*
     2   * Copyright (C) 2020 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package service
    19  
    20  import (
    21  	"testing"
    22  	"time"
    23  
    24  	"github.com/stretchr/testify/assert"
    25  
    26  	"github.com/mysteriumnetwork/node/mocks"
    27  	"github.com/mysteriumnetwork/node/services/wireguard/wgcfg"
    28  	"github.com/mysteriumnetwork/node/session/event"
    29  )
    30  
    31  type fakeSupplier struct{}
    32  
    33  func (f fakeSupplier) PeerStats() (wgcfg.Stats, error) {
    34  	return wgcfg.Stats{
    35  		BytesSent:     25,
    36  		BytesReceived: 52,
    37  		LastHandshake: time.Now(),
    38  	}, nil
    39  }
    40  
    41  func Test_statsPublisher_start(t *testing.T) {
    42  	bus := mocks.NewEventBus()
    43  	publisher := newStatsPublisher(bus, time.Microsecond)
    44  
    45  	go publisher.start("kappa", &fakeSupplier{})
    46  
    47  	assert.Eventually(t, func() bool {
    48  		lastEvt := bus.Pop()
    49  		if lastEvt == nil {
    50  			return false
    51  		}
    52  		evt, ok := lastEvt.(event.AppEventDataTransferred)
    53  		assert.True(t, ok)
    54  		return evt.ID == "kappa" && evt.Down == 52 && evt.Up == 25
    55  	}, 2*time.Second, 10*time.Millisecond)
    56  
    57  	publisher.stop()
    58  
    59  	// After stop publisher may still publish one last event if it was started before stop
    60  	// so we need to wait and drain last event from bus before checking if publisher
    61  	// actually stopped publishing events.
    62  	time.Sleep(time.Millisecond)
    63  	bus.Pop()
    64  	assert.Never(t, func() bool {
    65  		return bus.Pop() != nil
    66  	}, time.Millisecond, time.Microsecond)
    67  }