5 "github.com/stretchr/testify/assert"
13 func TestNewBanFile(t *testing.T) {
15 str := "2024-06-29T11:34:43.245899-07:00"
16 testTime, _ := time.Parse(time.RFC3339Nano, str)
25 wantErr assert.ErrorAssertionFunc
28 name: "Valid path with valid content",
29 args: args{path: filepath.Join(cwd, "test", "config", "Banlist.yaml")},
31 filePath: filepath.Join(cwd, "test", "config", "Banlist.yaml"),
32 banList: map[string]*time.Time{"192.168.86.29": &testTime},
34 wantErr: assert.NoError,
37 for _, tt := range tests {
38 t.Run(tt.name, func(t *testing.T) {
39 got, err := NewBanFile(tt.args.path)
40 if !tt.wantErr(t, err, fmt.Sprintf("NewBanFile(%v)", tt.args.path)) {
43 assert.Equalf(t, tt.want, got, "NewBanFile(%v)", tt.args.path)
48 // TestAdd tests the Add function.
49 func TestAdd(t *testing.T) {
50 // Create a temporary directory.
51 tmpDir, err := os.MkdirTemp("", "banfile_test")
53 t.Fatalf("Failed to create temp directory: %v", err)
55 defer os.RemoveAll(tmpDir) // Clean up the temporary directory.
57 // Path to the temporary ban file.
58 tmpFilePath := filepath.Join(tmpDir, "banfile.yaml")
60 // Initialize BanFile.
62 filePath: tmpFilePath,
63 banList: make(map[string]*time.Time),
66 // Define the test cases.
71 expect map[string]*time.Time
74 name: "Add IP with no expiration",
77 expect: map[string]*time.Time{
82 name: "Add IP with expiration",
84 until: func() *time.Time { t := time.Date(2024, 6, 29, 11, 34, 43, 245899000, time.UTC); return &t }(),
85 expect: map[string]*time.Time{
87 "192.168.1.2": func() *time.Time { t := time.Date(2024, 6, 29, 11, 34, 43, 245899000, time.UTC); return &t }(),
92 // Run the test cases.
93 for _, tt := range tests {
94 t.Run(tt.name, func(t *testing.T) {
95 err := bf.Add(tt.ip, tt.until)
96 assert.NoError(t, err, "Add() error")
98 // Load the file to check its contents.
99 loadedBanFile := &BanFile{filePath: tmpFilePath}
100 err = loadedBanFile.Load()
101 assert.NoError(t, err, "Load() error")
102 assert.Equal(t, tt.expect, loadedBanFile.banList, "Ban list does not match")
107 func TestBanFile_IsBanned(t *testing.T) {
109 banList map[string]*time.Time
123 name: "with permanent ban",
125 banList: map[string]*time.Time{
129 args: args{ip: "192.168.86.1"},
136 banList: map[string]*time.Time{},
138 args: args{ip: "192.168.86.1"},
143 for _, tt := range tests {
144 t.Run(tt.name, func(t *testing.T) {
146 banList: tt.fields.banList,
149 got, got1 := bf.IsBanned(tt.args.ip)
150 assert.Equalf(t, tt.want, got, "IsBanned(%v)", tt.args.ip)
151 assert.Equalf(t, tt.want1, got1, "IsBanned(%v)", tt.args.ip)