Fix packet loss stat zero division (#51)

Signed-off-by: Jeremiah Millay <jmillay@fastly.com>
This commit is contained in:
Jeremiah Millay 2023-06-29 01:18:09 -04:00 committed by Kaj Niemi
parent 17096581d8
commit 31b1b44067
2 changed files with 22 additions and 1 deletions

View File

@ -538,7 +538,12 @@ func (p *Pinger) Statistics() *Statistics {
p.statsMu.RLock()
defer p.statsMu.RUnlock()
sent := p.PacketsSent
loss := float64(sent-p.PacketsRecv) / float64(sent) * 100
var loss float64
if sent > 0 {
loss = float64(sent-p.PacketsRecv) / float64(sent) * 100
}
s := Statistics{
PacketsSent: sent,
PacketsRecv: p.PacketsRecv,

View File

@ -475,6 +475,22 @@ func TestStatisticsLossy(t *testing.T) {
}
}
func TestStatisticsZeroDivision(t *testing.T) {
p := New("localhost")
err := p.Resolve()
AssertNoError(t, err)
AssertEqualStrings(t, "localhost", p.Addr())
p.PacketsSent = 0
stats := p.Statistics()
// If packets were not sent (due to send errors), ensure that
// PacketLoss is 0 instead of NaN due to zero division
if stats.PacketLoss != 0 {
t.Errorf("Expected %v, got %v", 0, stats.PacketLoss)
}
}
// Test helpers
func makeTestPinger() *Pinger {
pinger := New("127.0.0.1")