From 25472f43c337fe8b54b2d237e6027115b818e260 Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Fri, 14 Jun 2024 08:49:37 +0000 Subject: [PATCH] fix(ui): list IPs in reverse chronological order - Fix #730 --- internal/models/history.go | 12 ++++----- internal/models/history_test.go | 46 +++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/internal/models/history.go b/internal/models/history.go index f5ee3a1bc..22fd97f00 100644 --- a/internal/models/history.go +++ b/internal/models/history.go @@ -18,16 +18,16 @@ type HistoryEvent struct { // current and previous ips // GetPreviousIPs returns an antichronological list of previous // IP addresses if there is any. -func (h History) GetPreviousIPs() []netip.Addr { +func (h History) GetPreviousIPs() (previousIPs []netip.Addr) { if len(h) <= 1 { return nil } - IPs := make([]netip.Addr, len(h)-1) - const two = 2 - for i := len(h) - two; i >= 0; i-- { - IPs[i] = h[i].IP + previousIPs = make([]netip.Addr, len(h)-1) + mostRecentPreviousIPIndex := len(h) - 2 //nolint:gomnd + for i := range previousIPs { + previousIPs[i] = h[mostRecentPreviousIPIndex-i].IP } - return IPs + return previousIPs } // GetCurrentIP returns the current IP address (latest in history). diff --git a/internal/models/history_test.go b/internal/models/history_test.go index 823c4104c..47bca81d9 100644 --- a/internal/models/history_test.go +++ b/internal/models/history_test.go @@ -1,12 +1,58 @@ package models import ( + "net/netip" "testing" "time" "github.com/stretchr/testify/assert" ) +func Test_GetPreviousIPs(t *testing.T) { + t.Parallel() + testCases := map[string]struct { + h History + previousIPs []netip.Addr + }{ + "empty_history": { + h: History{}, + }, + "single_event": { + h: History{ + {IP: netip.MustParseAddr("1.2.3.4")}, + }, + }, + "two_events": { + h: History{ + {IP: netip.MustParseAddr("1.2.3.4")}, + {IP: netip.MustParseAddr("5.6.7.8")}, // last one + }, + previousIPs: []netip.Addr{ + netip.MustParseAddr("1.2.3.4"), + }, + }, + "three_events": { + h: History{ + {IP: netip.MustParseAddr("1.2.3.4")}, + {IP: netip.MustParseAddr("5.6.7.8")}, + {IP: netip.MustParseAddr("9.6.7.8")}, // last one + }, + previousIPs: []netip.Addr{ + netip.MustParseAddr("5.6.7.8"), + netip.MustParseAddr("1.2.3.4"), + }, + }, + } + for name, testCase := range testCases { + testCase := testCase + t.Run(name, func(t *testing.T) { + t.Parallel() + previousIPs := testCase.h.GetPreviousIPs() + assert.Equal(t, testCase.previousIPs, previousIPs) + }) + } +} + func Test_GetDurationSinceSuccess(t *testing.T) { t.Parallel() tests := map[string]struct {