forked from porech/caddy-maxmind-geolocation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_test.go
More file actions
322 lines (284 loc) · 8.77 KB
/
github_test.go
File metadata and controls
322 lines (284 loc) · 8.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package caddy_maxmind_geolocation
import (
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/oschwald/maxminddb-golang"
)
func TestParseRepo(t *testing.T) {
tests := []struct {
repo string
wantOwner string
wantName string
wantErr bool
}{
{"P3TERX/GeoLite.mmdb", "P3TERX", "GeoLite.mmdb", false},
{"owner/repo", "owner", "repo", false},
{"owner/repo/", "owner", "repo", false},
{"", "", "", true},
{"single", "", "", true},
{"a/", "", "", true},
{"/b", "", "", true},
}
for _, tt := range tests {
owner, name, err := parseRepo(tt.repo)
if (err != nil) != tt.wantErr {
t.Errorf("parseRepo(%q) err = %v, wantErr %v", tt.repo, err, tt.wantErr)
continue
}
if !tt.wantErr && (owner != tt.wantOwner || name != tt.wantName) {
t.Errorf("parseRepo(%q) = %q, %q; want %q, %q", tt.repo, owner, name, tt.wantOwner, tt.wantName)
}
}
}
func TestFetchLatestReleaseTagAndAssetURL_Mock(t *testing.T) {
release := githubReleaseResponse{
TagName: "2026.02.25",
Assets: []githubAsset{
{Name: "GeoLite2-Country.mmdb", BrowserDownloadURL: "https://example.com/country.mmdb"},
{Name: "GeoLite2-City.mmdb", BrowserDownloadURL: "https://example.com/city.mmdb"},
},
}
body, _ := json.Marshal(release)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/repos/P3TERX/GeoLite.mmdb/releases/latest" {
t.Errorf("unexpected path %s", r.URL.Path)
http.Error(w, "not found", http.StatusNotFound)
return
}
if r.Header.Get("Accept") != "application/vnd.github+json" {
t.Errorf("missing Accept header")
}
w.Header().Set("Content-Type", "application/json")
w.Write(body)
}))
defer server.Close()
oldBase := githubAPIBaseURL
oldClient := githubHTTPClient
githubAPIBaseURL = server.URL
githubHTTPClient = server.Client()
defer func() {
githubAPIBaseURL = oldBase
githubHTTPClient = oldClient
}()
tag, url, err := fetchLatestReleaseTagAndAssetURL("P3TERX/GeoLite.mmdb", "GeoLite2-Country.mmdb", "")
if err != nil {
t.Fatalf("fetchLatestReleaseTagAndAssetURL: %v", err)
}
if tag != "2026.02.25" {
t.Errorf("tag = %q, want 2026.02.25", tag)
}
if url != "https://example.com/country.mmdb" {
t.Errorf("download URL = %q, want https://example.com/country.mmdb", url)
}
_, _, err = fetchLatestReleaseTagAndAssetURL("P3TERX/GeoLite.mmdb", "Missing.mmdb", "")
if err == nil {
t.Error("expected error for missing asset")
}
}
func TestFetchLatestReleaseTagAndAssetURL_APIError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("not found"))
}))
defer server.Close()
oldBase := githubAPIBaseURL
oldClient := githubHTTPClient
githubAPIBaseURL = server.URL
githubHTTPClient = server.Client()
defer func() {
githubAPIBaseURL = oldBase
githubHTTPClient = oldClient
}()
_, _, err := fetchLatestReleaseTagAndAssetURL("P3TERX/GeoLite.mmdb", "GeoLite2-Country.mmdb", "")
if err == nil {
t.Fatal("expected error on 404")
}
}
func TestDownloadFile_Mock(t *testing.T) {
fakeContent := []byte("fake mmdb content")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(fakeContent)
}))
defer server.Close()
oldClient := githubHTTPClient
githubHTTPClient = server.Client()
defer func() { githubHTTPClient = oldClient }()
dir := t.TempDir()
dest := filepath.Join(dir, "GeoLite2-Country.mmdb")
err := downloadFile(server.URL, dest, "")
if err != nil {
t.Fatalf("downloadFile: %v", err)
}
got, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
if string(got) != string(fakeContent) {
t.Errorf("content = %q, want %q", got, fakeContent)
}
}
func TestSyncFromGitHubRelease_Mock(t *testing.T) {
fakeContent := []byte("fake mmdb")
var downloadURL string
release := githubReleaseResponse{
TagName: "v1.0.0",
Assets: []githubAsset{{Name: "GeoLite2-Country.mmdb", BrowserDownloadURL: ""}},
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/repos/P3TERX/GeoLite.mmdb/releases/latest" {
release.Assets[0].BrowserDownloadURL = "http://" + r.Host + "/asset"
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(release)
return
}
if r.URL.Path == "/asset" {
downloadURL = "http://" + r.Host + "/asset"
w.Write(fakeContent)
return
}
http.NotFound(w, r)
}))
defer server.Close()
release.Assets[0].BrowserDownloadURL = server.URL + "/asset"
oldBase := githubAPIBaseURL
oldClient := githubHTTPClient
githubAPIBaseURL = server.URL
githubHTTPClient = server.Client()
defer func() {
githubAPIBaseURL = oldBase
githubHTTPClient = oldClient
}()
dir := t.TempDir()
cachePath := filepath.Join(dir, "GeoLite2-Country.mmdb")
tag, updated, err := syncFromGitHubRelease("P3TERX/GeoLite.mmdb", "GeoLite2-Country.mmdb", cachePath, "")
if err != nil {
t.Fatalf("syncFromGitHubRelease: %v", err)
}
if tag != "v1.0.0" {
t.Errorf("tag = %q, want v1.0.0", tag)
}
if !updated {
t.Error("expected updated = true on first sync")
}
content, _ := os.ReadFile(cachePath)
if string(content) != string(fakeContent) {
t.Errorf("cache content = %q", content)
}
if readStoredTag(cachePath) != "v1.0.0" {
t.Error("stored tag mismatch")
}
// Second call: same tag -> no update
_, updated2, err := syncFromGitHubRelease("P3TERX/GeoLite.mmdb", "GeoLite2-Country.mmdb", cachePath, "")
if err != nil {
t.Fatalf("second sync: %v", err)
}
if updated2 {
t.Error("expected updated = false when tag unchanged")
}
_ = downloadURL
}
func TestCleanupStaleTempFiles(t *testing.T) {
dir := t.TempDir()
base := "GeoLite2-Country.mmdb"
tagPath := filepath.Join(dir, base+".tag")
realPath := filepath.Join(dir, base)
stalePath := filepath.Join(dir, base+".stale123")
if err := os.WriteFile(tagPath, []byte("v1"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(realPath, []byte("data"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(stalePath, []byte("old"), 0644); err != nil {
t.Fatal(err)
}
cleanupStaleTempFiles(dir, base)
if _, err := os.Stat(tagPath); os.IsNotExist(err) {
t.Error(".tag file was removed but should be kept")
}
if _, err := os.Stat(realPath); os.IsNotExist(err) {
t.Error("real file was removed")
}
if _, err := os.Stat(stalePath); err == nil {
t.Error("stale temp file was not removed")
}
}
func TestTagPathReadWrite(t *testing.T) {
dir := t.TempDir()
cachePath := filepath.Join(dir, "db.mmdb")
if readStoredTag(cachePath) != "" {
t.Error("readStoredTag on missing file should return empty")
}
if err := writeStoredTag(cachePath, "v2.0"); err != nil {
t.Fatal(err)
}
if readStoredTag(cachePath) != "v2.0" {
t.Errorf("readStoredTag = %q", readStoredTag(cachePath))
}
}
// TestGitHubIntegration hits the real GitHub API. Run with:
// go test -v -run TestGitHubIntegration
// Optional: GITHUB_TOKEN for higher rate limit.
func TestGitHubIntegration(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
token := os.Getenv("GITHUB_TOKEN")
tag, url, err := fetchLatestReleaseTagAndAssetURL("P3TERX/GeoLite.mmdb", "GeoLite2-Country.mmdb", token)
if err != nil {
t.Fatalf("fetchLatestReleaseTagAndAssetURL (real API): %v", err)
}
if tag == "" {
t.Error("tag is empty")
}
if url == "" {
t.Error("download URL is empty")
}
t.Logf("latest release tag: %s", tag)
t.Logf("download URL: %s", url)
}
// TestDownloadFromGitHubIntegration performs a real download from GitHub and verifies
// the file is a valid MaxMind DB. Run with:
//
// go test -v -run TestDownloadFromGitHubIntegration
//
// Skips in short mode. Optional: GITHUB_TOKEN for rate limit.
func TestDownloadFromGitHubIntegration(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
token := os.Getenv("GITHUB_TOKEN")
tag, downloadURL, err := fetchLatestReleaseTagAndAssetURL("P3TERX/GeoLite.mmdb", "GeoLite2-Country.mmdb", token)
if err != nil {
t.Fatalf("fetch latest release: %v", err)
}
dir := t.TempDir()
cachePath := filepath.Join(dir, "GeoLite2-Country.mmdb")
if err := downloadFile(downloadURL, cachePath, token); err != nil {
t.Fatalf("download file: %v", err)
}
fi, err := os.Stat(cachePath)
if err != nil {
t.Fatalf("stat: %v", err)
}
t.Logf("downloaded %s, size %d bytes", tag, fi.Size())
if fi.Size() == 0 {
t.Fatal("downloaded file is empty")
}
db, err := maxminddb.Open(cachePath)
if err != nil {
t.Fatalf("open as maxmind db: %v", err)
}
defer db.Close()
var record Record
ip := net.ParseIP("8.8.8.8")
if err := db.Lookup(ip, &record); err != nil {
t.Fatalf("lookup 8.8.8.8: %v", err)
}
t.Logf("lookup 8.8.8.8 -> country: %s", record.Country.ISOCode)
}