Skip to content

Commit

Permalink
Fix packet loss stat zero division (#51)
Browse files Browse the repository at this point in the history
Signed-off-by: Jeremiah Millay <jmillay@fastly.com>
  • Loading branch information
floatingstatic committed Jun 29, 2023
1 parent 1530f0f commit 631cd38
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion ping.go
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,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,
Expand Down
16 changes: 16 additions & 0 deletions ping_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,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")
Expand Down

0 comments on commit 631cd38

Please sign in to comment.