mirror of
https://github.com/go-ping/ping.git
synced 2025-07-16 07:06:00 +00:00
Fix packet loss stat zero division (#51)
Signed-off-by: Jeremiah Millay <jmillay@fastly.com>
This commit is contained in:
parent
17096581d8
commit
31b1b44067
7
ping.go
7
ping.go
@ -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,
|
||||
|
16
ping_test.go
16
ping_test.go
@ -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")
|
||||
|
Loading…
Reference in New Issue
Block a user