aboutsummaryrefslogtreecommitdiff
path: root/internal/modules/handler_test.go
blob: 943c74c75234a002de6ffd2d063ed16e85e72e88 (plain)
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
package modules

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"git.ofmax.li/go-git-server/internal/admin"
)

func TestNewModuleHandler_WithNilConfig(t *testing.T) {
	handler := NewModuleHandler("/tmp/repos", "example.com", nil)

	// Test that it returns a valid http.Handler even with nil config
	if handler == nil {
		t.Error("NewModuleHandler should return a non-nil handler")
	}
}

func TestNewModuleHandler_WithConfig(t *testing.T) {
	config := &admin.ServerRepos{
		Repos: []*admin.GitRepo{
			{
				Name:     "mylib",
				GoModule: true,
			},
		},
	}

	handler := NewModuleHandler("/tmp/repos", "example.com", config)

	// Test that it returns a valid http.Handler
	if handler == nil {
		t.Error("NewModuleHandler should return a non-nil handler")
	}
}

func TestHandleGoImport_ConfiguredModule(t *testing.T) {
	config := &admin.ServerRepos{
		Repos: []*admin.GitRepo{
			{
				Name:     "mymodule",
				GoModule: true,
			},
		},
	}

	handler := NewModuleHandler("/tmp/repos", "git.example.com", config)

	req := httptest.NewRequest("GET", "/mymodule?go-get=1", nil)
	w := httptest.NewRecorder()

	handler.ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d", w.Code)
	}

	body := w.Body.String()

	// Check for go-import meta tag
	if !strings.Contains(body, `<meta name="go-import"`) {
		t.Error("response should contain go-import meta tag")
	}

	// Check for correct module path and VCS info
	expectedContent := `content="git.example.com/mymodule git https://git.example.com/mymodule"`
	if !strings.Contains(body, expectedContent) {
		t.Errorf("response should contain %s", expectedContent)
	}

	// Check for go-source meta tag
	if !strings.Contains(body, `<meta name="go-source"`) {
		t.Error("response should contain go-source meta tag")
	}

	// Check content type
	contentType := w.Header().Get("Content-Type")
	if contentType != "text/html; charset=utf-8" {
		t.Errorf("expected content type text/html; charset=utf-8, got %s", contentType)
	}
}

func TestModuleHandler_ServeHTTP_VersionList(t *testing.T) {
	config := &admin.ServerRepos{
		Repos: []*admin.GitRepo{
			{
				Name:     "mymodule",
				GoModule: true,
			},
		},
	}

	handler := NewModuleHandler("/tmp/repos", "git.example.com", config)

	req := httptest.NewRequest("GET", "/mymodule/@v/list", nil)
	w := httptest.NewRecorder()

	handler.ServeHTTP(w, req)

	// Since we don't have a real repo, this should return 500 (internal server error)
	// But we can test that it tries to handle the request correctly
	if w.Code == http.StatusOK {
		contentType := w.Header().Get("Content-Type")
		if contentType != "text/plain; charset=utf-8" {
			t.Errorf("expected content type text/plain; charset=utf-8, got %s", contentType)
		}
	}
}

func TestGoModuleConfiguration(t *testing.T) {
	config := &admin.ServerRepos{
		Repos: []*admin.GitRepo{
			{
				Name:     "mylib",
				GoModule: true, // This should have module endpoints
			},
			{
				Name:     "website",
				GoModule: false, // This should not have module endpoints
			},
		},
	}

	handler := NewModuleHandler("/tmp/repos", "git.example.com", config)

	// Test Go module repo (should work)
	t.Run("go_module_true", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mylib?go-get=1", nil)
		w := httptest.NewRecorder()
		handler.ServeHTTP(w, req)

		if w.Code != http.StatusOK {
			t.Errorf("expected status 200 for Go module, got %d", w.Code)
		}
	})

	// Test non-Go module repo (should return 404)
	t.Run("go_module_false", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/website?go-get=1", nil)
		w := httptest.NewRecorder()
		handler.ServeHTTP(w, req)

		if w.Code != http.StatusNotFound {
			t.Errorf("expected status 404 for non-Go module, got %d", w.Code)
		}
	})

	// Test proxy endpoints for Go module
	t.Run("go_module_proxy_endpoints", func(t *testing.T) {
		endpoints := []string{
			"/mylib/@v/list",
			"/mylib/@latest",
		}

		for _, endpoint := range endpoints {
			req := httptest.NewRequest("GET", endpoint, nil)
			w := httptest.NewRecorder()
			handler.ServeHTTP(w, req)

			// Should get 500 (repo doesn't exist) not 404 (route doesn't exist)
			if w.Code == http.StatusNotFound {
				t.Errorf("endpoint %s should be routed (got 404, want 500 or 200)", endpoint)
			}
		}
	})

	// Test proxy endpoints for non-Go module (should all be 404)
	t.Run("non_go_module_proxy_endpoints", func(t *testing.T) {
		endpoints := []string{
			"/website/@v/list",
			"/website/@latest",
		}

		for _, endpoint := range endpoints {
			req := httptest.NewRequest("GET", endpoint, nil)
			w := httptest.NewRecorder()
			handler.ServeHTTP(w, req)

			if w.Code != http.StatusNotFound {
				t.Errorf("endpoint %s should return 404 for non-Go module, got %d", endpoint, w.Code)
			}
		}
	})
}

// Test the catch-all handler (handleAllRequests) - currently 0% coverage
func TestHandleAllRequests(t *testing.T) {
	handler := &ModuleHandler{
		reposDir:   "/tmp/repos",
		serverHost: "git.example.com",
	}

	t.Run("version_list_endpoint", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/list", nil)
		w := httptest.NewRecorder()

		handler.handleAllRequests(w, req)

		// Should get 500 (repo doesn't exist) not 404 (route doesn't exist)
		if w.Code == http.StatusNotFound {
			t.Error("handleAllRequests should route version list requests")
		}
	})

	t.Run("latest_endpoint", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@latest", nil)
		w := httptest.NewRecorder()

		handler.handleAllRequests(w, req)

		// Should get 500 (repo doesn't exist) not 404 (route doesn't exist)
		if w.Code == http.StatusNotFound {
			t.Error("handleAllRequests should route latest version requests")
		}
	})

	t.Run("version_info_endpoint", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.info", nil)
		w := httptest.NewRecorder()

		handler.handleAllRequests(w, req)

		// Should get 500/404 (repo/version doesn't exist) not 404 (route doesn't exist)
		if w.Code == http.StatusOK {
			t.Error("expected error for nonexistent repository/version")
		}
	})

	t.Run("mod_file_endpoint", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.mod", nil)
		w := httptest.NewRecorder()

		handler.handleAllRequests(w, req)

		// Should get 500/404 (repo/version doesn't exist) not 404 (route doesn't exist)
		if w.Code == http.StatusOK {
			t.Error("expected error for nonexistent repository/version")
		}
	})

	t.Run("zip_file_endpoint", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.zip", nil)
		w := httptest.NewRecorder()

		handler.handleAllRequests(w, req)

		// Should get 500/404 (repo/version doesn't exist) not 404 (route doesn't exist)
		if w.Code == http.StatusOK {
			t.Error("expected error for nonexistent repository/version")
		}
	})

	t.Run("go_import_request", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule?go-get=1", nil)
		w := httptest.NewRecorder()

		handler.handleAllRequests(w, req)

		if w.Code != http.StatusOK {
			t.Errorf("expected 200 for go-import request, got %d", w.Code)
		}

		body := w.Body.String()
		if !strings.Contains(body, "go-import") {
			t.Error("response should contain go-import meta tag")
		}
	})

	t.Run("regular_request", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule", nil)
		w := httptest.NewRecorder()

		handler.handleAllRequests(w, req)

		// Should get 404 because go-get=1 is required for go-import
		if w.Code != http.StatusNotFound {
			t.Errorf("expected 404 for regular request without go-get, got %d", w.Code)
		}
	})
}

// Test non-"ForModule" handler functions - currently 0% coverage
func TestNonForModuleHandlers(t *testing.T) {
	handler := &ModuleHandler{
		reposDir:   "/tmp/repos",
		serverHost: "git.example.com",
	}

	t.Run("handleGoImport", func(t *testing.T) {
		// Test without go-get parameter
		req := httptest.NewRequest("GET", "/mymodule", nil)
		w := httptest.NewRecorder()

		handler.handleGoImport(w, req)

		if w.Code != http.StatusNotFound {
			t.Error("expected 404 when go-get parameter is missing")
		}

		// Test with go-get=1
		req = httptest.NewRequest("GET", "/mymodule?go-get=1", nil)
		w = httptest.NewRecorder()

		handler.handleGoImport(w, req)

		if w.Code != http.StatusOK {
			t.Errorf("expected 200 with go-get=1, got %d", w.Code)
		}

		body := w.Body.String()
		if !strings.Contains(body, "go-import") {
			t.Error("response should contain go-import meta tag")
		}
	})

	t.Run("handleVersionList", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/list", nil)
		w := httptest.NewRecorder()

		handler.handleVersionList(w, req)

		// Should get 500 (repo doesn't exist)
		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("handleLatestVersion", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@latest", nil)
		w := httptest.NewRecorder()

		handler.handleLatestVersion(w, req)

		// Should get 500 (repo doesn't exist)
		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("handleVersionInfo", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.info", nil)
		w := httptest.NewRecorder()

		handler.handleVersionInfo(w, req)

		// Should get 500 (repo doesn't exist)
		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("handleModFile", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.mod", nil)
		w := httptest.NewRecorder()

		handler.handleModFile(w, req)

		// Should get 500 (repo doesn't exist)
		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("handleModuleZip", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.zip", nil)
		w := httptest.NewRecorder()

		handler.handleModuleZip(w, req)

		// Should get 500 (repo doesn't exist)
		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})
}

// Test ForModule handlers that have 0% coverage
func TestForModuleHandlersZeroCoverage(t *testing.T) {
	handler := &ModuleHandler{
		reposDir:   "/tmp/repos",
		serverHost: "git.example.com",
	}

	t.Run("handleVersionInfoForModule", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.info", nil)
		w := httptest.NewRecorder()

		handler.handleVersionInfoForModule(w, req, "mymodule", "v1.0.0")

		// Should get 500 (repo doesn't exist)
		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("handleModFileForModule", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.mod", nil)
		w := httptest.NewRecorder()

		handler.handleModFileForModule(w, req, "mymodule", "v1.0.0")

		// Should get 500 (repo doesn't exist)
		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("handleModuleZipForModule", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.zip", nil)
		w := httptest.NewRecorder()

		handler.handleModuleZipForModule(w, req, "mymodule", "v1.0.0")

		// Should get 500 (repo doesn't exist)
		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("handleGoImportForModule_without_go_get", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule", nil)
		w := httptest.NewRecorder()

		handler.handleGoImportForModule(w, req, "mymodule")

		if w.Code != http.StatusNotFound {
			t.Error("expected 404 when go-get parameter is missing")
		}
	})

	t.Run("handleGoImportForModule_with_go_get", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule?go-get=1", nil)
		w := httptest.NewRecorder()

		handler.handleGoImportForModule(w, req, "mymodule")

		if w.Code != http.StatusOK {
			t.Errorf("expected 200 with go-get=1, got %d", w.Code)
		}

		body := w.Body.String()
		if !strings.Contains(body, "go-import") {
			t.Error("response should contain go-import meta tag")
		}
	})
}

// Test createGenericVersionHandler which has low coverage (8.3%)
func TestCreateGenericVersionHandler(t *testing.T) {
	handler := &ModuleHandler{
		reposDir:   "/tmp/repos",
		serverHost: "git.example.com",
	}

	genericHandler := handler.createGenericVersionHandler("mymodule")

	t.Run("info_file", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.info", nil)
		w := httptest.NewRecorder()

		genericHandler(w, req)

		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("mod_file", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.mod", nil)
		w := httptest.NewRecorder()

		genericHandler(w, req)

		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("zip_file", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/v1.0.0.zip", nil)
		w := httptest.NewRecorder()

		genericHandler(w, req)

		if w.Code != http.StatusInternalServerError {
			t.Errorf("expected 500 for nonexistent repo, got %d", w.Code)
		}
	})

	t.Run("unknown_endpoint", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/unknown", nil)
		w := httptest.NewRecorder()

		genericHandler(w, req)

		if w.Code != http.StatusNotFound {
			t.Errorf("expected 404 for unknown endpoint, got %d", w.Code)
		}
	})
}

// Test middleware coverage
func TestModuleMiddleware(t *testing.T) {
	moduleHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("module-response"))
	})

	nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("next-response"))
	})

	middleware := ModuleMiddleware(moduleHandler, nextHandler)

	t.Run("module_request_go_get", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule?go-get=1", nil)
		w := httptest.NewRecorder()

		middleware.ServeHTTP(w, req)

		if w.Body.String() != "module-response" {
			t.Error("should route to module handler for go-get requests")
		}
	})

	t.Run("module_request_version_list", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule/@v/list", nil)
		w := httptest.NewRecorder()

		middleware.ServeHTTP(w, req)

		if w.Body.String() != "module-response" {
			t.Error("should route to module handler for version list requests")
		}
	})

	t.Run("non_module_request", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/mymodule.git/info/refs", nil)
		w := httptest.NewRecorder()

		middleware.ServeHTTP(w, req)

		if w.Body.String() != "next-response" {
			t.Error("should route to next handler for git requests")
		}
	})
}

// Tests for new helper functions
func TestNormalizeImportPath(t *testing.T) {
	handler := &ModuleHandler{
		reposDir:   "/tmp/repos",
		serverHost: "git.example.com",
	}

	tests := []struct {
		name       string
		serverHost string
		modulePath string
		expected   string
		shouldErr  bool
	}{
		{
			name:       "valid_simple_path",
			serverHost: "git.example.com",
			modulePath: "mymodule",
			expected:   "git.example.com/mymodule",
			shouldErr:  false,
		},
		{
			name:       "trailing_slash_on_host",
			serverHost: "git.example.com/",
			modulePath: "mymodule",
			expected:   "git.example.com/mymodule",
			shouldErr:  false,
		},
		{
			name:       "leading_slash_on_module",
			serverHost: "git.example.com",
			modulePath: "/mymodule",
			expected:   "git.example.com/mymodule",
			shouldErr:  false,
		},
		{
			name:       "nested_module_path",
			serverHost: "git.example.com",
			modulePath: "company/mymodule",
			expected:   "git.example.com/company/mymodule",
			shouldErr:  false,
		},
		{
			name:       "empty_server_host",
			serverHost: "",
			modulePath: "mymodule",
			expected:   "",
			shouldErr:  true,
		},
		{
			name:       "empty_module_path",
			serverHost: "git.example.com",
			modulePath: "",
			expected:   "",
			shouldErr:  true,
		},
		{
			name:       "path_traversal_attempt",
			serverHost: "git.example.com",
			modulePath: "../../../etc/passwd",
			expected:   "",
			shouldErr:  true,
		},
		{
			name:       "whitespace_in_module_path",
			serverHost: "git.example.com",
			modulePath: "my module",
			expected:   "",
			shouldErr:  true,
		},
		{
			name:       "tab_in_module_path",
			serverHost: "git.example.com",
			modulePath: "my\tmodule",
			expected:   "",
			shouldErr:  true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Update handler for this test
			handler.serverHost = tt.serverHost

			result, err := handler.normalizeImportPath(tt.modulePath)

			if tt.shouldErr {
				if err == nil {
					t.Errorf("expected error but got none")
				}
			} else {
				if err != nil {
					t.Errorf("unexpected error: %v", err)
				}
				if result != tt.expected {
					t.Errorf("expected %q, got %q", tt.expected, result)
				}
			}
		})
	}
}

func TestBuildRepoURL(t *testing.T) {
	handler := &ModuleHandler{
		reposDir:   "/tmp/repos",
		serverHost: "git.example.com",
	}

	tests := []struct {
		name       string
		modulePath string
		expected   string
		shouldErr  bool
	}{
		{
			name:       "simple_module",
			modulePath: "mymodule",
			expected:   "https://git.example.com/mymodule",
			shouldErr:  false,
		},
		{
			name:       "nested_module",
			modulePath: "company/mymodule",
			expected:   "https://git.example.com/company/mymodule",
			shouldErr:  false,
		},
		{
			name:       "invalid_module_path",
			modulePath: "",
			expected:   "",
			shouldErr:  true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result, err := handler.buildRepoURL(tt.modulePath)

			if tt.shouldErr {
				if err == nil {
					t.Errorf("expected error but got none")
				}
			} else {
				if err != nil {
					t.Errorf("unexpected error: %v", err)
				}
				if result != tt.expected {
					t.Errorf("expected %q, got %q", tt.expected, result)
				}
			}
		})
	}
}

func TestGenerateGoImportHTML(t *testing.T) {
	handler := &ModuleHandler{
		reposDir:   "/tmp/repos",
		serverHost: "git.example.com",
	}

	tests := []struct {
		name         string
		modulePath   string
		shouldErr    bool
		expectedHTML []string // Strings that should be present in the HTML
	}{
		{
			name:       "valid_module",
			modulePath: "mymodule",
			shouldErr:  false,
			expectedHTML: []string{
				`<meta name="go-import" content="git.example.com/mymodule git https://git.example.com/mymodule">`,
				`<meta name="go-source" content="git.example.com/mymodule https://git.example.com/mymodule`,
				`go get git.example.com/mymodule`,
			},
		},
		{
			name:         "invalid_module",
			modulePath:   "",
			shouldErr:    true,
			expectedHTML: nil,
		},
		{
			name:         "module_with_path_traversal",
			modulePath:   "../../../etc/passwd",
			shouldErr:    true,
			expectedHTML: nil,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result, err := handler.generateGoImportHTML(tt.modulePath)

			if tt.shouldErr {
				if err == nil {
					t.Errorf("expected error but got none")
				}
			} else {
				if err != nil {
					t.Errorf("unexpected error: %v", err)
				}

				for _, expected := range tt.expectedHTML {
					if !strings.Contains(result, expected) {
						t.Errorf("HTML should contain %q, got:\n%s", expected, result)
					}
				}
			}
		})
	}
}

// Integration test that simulates the full go-get flow
func TestGoGetIntegration(t *testing.T) {
	config := &admin.ServerRepos{
		Repos: []*admin.GitRepo{
			{
				Name:     "mymodule",
				GoModule: true,
			},
		},
	}

	handler := NewModuleHandler("/tmp/repos", "git.example.com", config)

	// Test the complete go-get flow:
	// 1. Initial request with go-get=1
	// 2. Verify correct meta tags are returned
	// 3. Verify import path format is correct

	req := httptest.NewRequest("GET", "/mymodule?go-get=1", nil)
	w := httptest.NewRecorder()

	handler.ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Fatalf("expected status 200, got %d", w.Code)
	}

	body := w.Body.String()

	// Verify the response contains proper go-import directive
	expectedImport := `content="git.example.com/mymodule git https://git.example.com/mymodule"`
	if !strings.Contains(body, expectedImport) {
		t.Errorf("response should contain correct go-import directive: %s\nGot: %s", expectedImport, body)
	}

	// Verify the response contains proper go-source directive
	expectedSource := `content="git.example.com/mymodule https://git.example.com/mymodule`
	if !strings.Contains(body, expectedSource) {
		t.Errorf("response should contain correct go-source directive: %s\nGot: %s", expectedSource, body)
	}

	// Verify the response contains proper body content
	expectedBody := `go get git.example.com/mymodule`
	if !strings.Contains(body, expectedBody) {
		t.Errorf("response should contain correct body content: %s\nGot: %s", expectedBody, body)
	}

	// Verify content type
	contentType := w.Header().Get("Content-Type")
	if contentType != "text/html; charset=utf-8" {
		t.Errorf("expected content type text/html; charset=utf-8, got %s", contentType)
	}

	// Test that the import path format matches Go's expectations:
	// - Should be domain/path format
	// - Should not have protocol prefix in the import path
	// - Should use HTTPS for the repository URL
	if strings.Contains(body, `content="mymodule git`) {
		t.Error("import path should include domain, not just module name")
	}

	if strings.Contains(body, `content="https://git.example.com/mymodule git`) {
		t.Error("import path should not include protocol")
	}
}

// Test error handling in go-import generation
func TestGoImportErrorHandling(t *testing.T) {
	// Test with invalid server configuration
	handler := &ModuleHandler{
		reposDir:   "/tmp/repos",
		serverHost: "", // Invalid empty host
	}

	req := httptest.NewRequest("GET", "/mymodule?go-get=1", nil)
	w := httptest.NewRecorder()

	handler.handleGoImport(w, req)

	if w.Code != http.StatusInternalServerError {
		t.Errorf("expected status 500 for invalid server config, got %d", w.Code)
	}

	// Test with invalid module path characters
	handler.serverHost = "git.example.com"

	req = httptest.NewRequest("GET", "/my%20module?go-get=1", nil)
	w = httptest.NewRecorder()

	handler.handleGoImport(w, req)

	// Should handle URL-encoded paths gracefully or return appropriate error
	if w.Code == http.StatusOK {
		body := w.Body.String()
		// Verify it doesn't contain malformed content
		if strings.Contains(body, "%20") {
			t.Error("response should not contain URL-encoded characters in meta tags")
		}
	}
}