accounting: fix total duration calculation

Fixes: #3498
This commit is contained in:
Aleksandar Jankovic 2019-09-10 13:55:16 +02:00 committed by Nick Craig-Wood
parent 29b4f211ab
commit 934440a9df
2 changed files with 80 additions and 42 deletions

View File

@ -138,7 +138,7 @@ func (s *StatsInfo) totalDuration() time.Duration {
var total time.Duration var total time.Duration
var i, j = 0, 1 var i, j = 0, 1
for i < len(timeRanges) { for i < len(timeRanges) {
if j < len(timeRanges)-1 { if j < len(timeRanges) {
if timeRanges[j].start.Before(timeRanges[i].end) { if timeRanges[j].start.Before(timeRanges[i].end) {
if timeRanges[i].end.Before(timeRanges[j].end) { if timeRanges[i].end.Before(timeRanges[j].end) {
timeRanges[i].end = timeRanges[j].end timeRanges[i].end = timeRanges[j].end

View File

@ -130,10 +130,40 @@ func TestStatsError(t *testing.T) {
} }
func TestStatsTotalDuration(t *testing.T) { func TestStatsTotalDuration(t *testing.T) {
time1 := time.Now().Add(-40 * time.Second) startTime := time.Now()
time1 := startTime.Add(-40 * time.Second)
time2 := time1.Add(10 * time.Second) time2 := time1.Add(10 * time.Second)
time3 := time2.Add(10 * time.Second) time3 := time2.Add(10 * time.Second)
time4 := time3.Add(10 * time.Second) time4 := time3.Add(10 * time.Second)
t.Run("Single completed transfer", func(t *testing.T) {
s := NewStats()
s.AddTransfer(&Transfer{
startedAt: time1,
completedAt: time2,
})
s.mu.Lock()
total := s.totalDuration()
s.mu.Unlock()
assert.Equal(t, 10*time.Second, total)
})
t.Run("Single uncompleted transfer", func(t *testing.T) {
s := NewStats()
s.AddTransfer(&Transfer{
startedAt: time1,
})
s.mu.Lock()
total := s.totalDuration()
s.mu.Unlock()
assert.Equal(t, time.Since(time1)/time.Second, total/time.Second)
})
t.Run("Overlapping without ending", func(t *testing.T) {
s := NewStats() s := NewStats()
s.AddTransfer(&Transfer{ s.AddTransfer(&Transfer{
startedAt: time2, startedAt: time2,
@ -161,21 +191,29 @@ func TestStatsTotalDuration(t *testing.T) {
total := s.totalDuration() total := s.totalDuration()
s.mu.Unlock() s.mu.Unlock()
assert.True(t, 30*time.Second < total && total < 31*time.Second, total) assert.Equal(t, time.Duration(30), total/time.Second)
} })
func TestStatsTotalDuration2(t *testing.T) { t.Run("Mixed completed and uncompleted transfers", func(t *testing.T) {
time1 := time.Now().Add(-40 * time.Second)
time2 := time1.Add(10 * time.Second)
s := NewStats() s := NewStats()
s.AddTransfer(&Transfer{ s.AddTransfer(&Transfer{
startedAt: time1, startedAt: time1,
completedAt: time2, completedAt: time2,
}) })
s.AddTransfer(&Transfer{
startedAt: time2,
})
s.AddTransfer(&Transfer{
startedAt: time3,
})
s.AddTransfer(&Transfer{
startedAt: time3,
})
s.mu.Lock() s.mu.Lock()
total := s.totalDuration() total := s.totalDuration()
s.mu.Unlock() s.mu.Unlock()
assert.Equal(t, 10*time.Second, total) assert.Equal(t, startTime.Sub(time1)/time.Second, total/time.Second)
})
} }