-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli_test.go
More file actions
1916 lines (1494 loc) · 53.2 KB
/
Copy pathcli_test.go
File metadata and controls
1916 lines (1494 loc) · 53.2 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
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 Grant Carthew
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
"testing"
)
// TestMain runs before and after all tests to ensure cleanup
func TestMain(m *testing.M) {
// Set up signal handling to cleanup on Ctrl+C
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigChan
fmt.Fprintf(os.Stderr, "\nCleaning up browsers before exit...\n")
cleanupOrphanedBrowsers()
os.Exit(ExitCodeInterrupt)
}()
// Clean up any orphaned Chrome instances before running tests
cleanupOrphanedBrowsers()
// Run tests
exitCode := m.Run()
// Clean up any orphaned Chrome instances after running tests
cleanupOrphanedBrowsers()
os.Exit(exitCode)
}
// cleanupOrphanedBrowsers kills any Chrome/Chromium instances with remote debugging
func cleanupOrphanedBrowsers() {
// Find Chrome/Chromium processes with remote-debugging-port
cmd := exec.Command("sh", "-c", "ps aux | grep -iE '(chrome|chromium).*--remote-debugging-port' | grep -v grep | awk '{print $2}'")
output, err := cmd.Output()
if err != nil {
// No processes found or command failed - that's okay
return
}
pidsStr := strings.TrimSpace(string(output))
if pidsStr == "" {
return
}
pids := strings.Split(pidsStr, "\n")
fmt.Fprintf(os.Stderr, "Cleaning up %d orphaned browser instance(s)...\n", len(pids))
for _, pid := range pids {
pid = strings.TrimSpace(pid)
if pid == "" {
continue
}
// Try graceful kill first
exec.Command("kill", pid).Run()
}
// Wait longer for graceful shutdown
exec.Command("sleep", "2").Run()
// Force kill any remaining
for _, pid := range pids {
pid = strings.TrimSpace(pid)
if pid == "" {
continue
}
exec.Command("kill", "-9", pid).Run()
}
// Final wait to ensure processes are fully gone
exec.Command("sleep", "1").Run()
}
// isBrowserAvailable checks if Chrome or Chromium is available on the system
func isBrowserAvailable() bool {
browsers := []string{
"google-chrome",
"chromium",
"chromium-browser",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
}
for _, browser := range browsers {
if _, err := exec.LookPath(browser); err == nil {
return true
}
// Check if file exists (for macOS app paths)
if _, err := os.Stat(browser); err == nil {
return true
}
}
return false
}
// startTestServer launches an HTTP server serving files from testdata/
func startTestServer(t *testing.T) *httptest.Server {
t.Helper()
// Get absolute path to testdata directory
testdataPath, err := filepath.Abs("testdata")
if err != nil {
t.Fatalf("failed to get testdata path: %v", err)
}
// Create file server
fileServer := http.FileServer(http.Dir(testdataPath))
// Create test server
server := httptest.NewServer(fileServer)
// Register cleanup
t.Cleanup(func() {
server.Close()
})
return server
}
// runSnag executes the snag binary with the given arguments
// Returns stdout, stderr, and error
func runSnag(args ...string) (stdout string, stderr string, err error) {
cmd := exec.Command("./snag", args...)
// Capture stdout and stderr separately
stdoutBytes, stderrBytes, err := runCommand(cmd)
return string(stdoutBytes), string(stderrBytes), err
}
// runCommand executes a command and returns stdout, stderr separately
func runCommand(cmd *exec.Cmd) (stdout []byte, stderr []byte, err error) {
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, err
}
stderrPipe, err := cmd.StderrPipe()
if err != nil {
return nil, nil, err
}
if err := cmd.Start(); err != nil {
return nil, nil, err
}
// Read output using io.ReadAll
stdoutBytes, stdoutErr := io.ReadAll(stdoutPipe)
stderrBytes, stderrErr := io.ReadAll(stderrPipe)
// Wait for command to finish
err = cmd.Wait()
// Check for read errors
if stdoutErr != nil {
return nil, nil, stdoutErr
}
if stderrErr != nil {
return nil, nil, stderrErr
}
return stdoutBytes, stderrBytes, err
}
// assertContains checks if the output contains the expected substring
func assertContains(t *testing.T, output, expected string) {
t.Helper()
if !strings.Contains(output, expected) {
t.Errorf("expected output to contain %q, got:\n%s", expected, output)
}
}
// assertNotContains checks if the output does not contain the substring
func assertNotContains(t *testing.T, output, unexpected string) {
t.Helper()
if strings.Contains(output, unexpected) {
t.Errorf("expected output to NOT contain %q, got:\n%s", unexpected, output)
}
}
// assertExitCode checks if the command exited with the expected code
func assertExitCode(t *testing.T, err error, expectedCode int) {
t.Helper()
if expectedCode == 0 {
if err != nil {
t.Errorf("expected exit code 0, but command failed: %v", err)
}
} else {
// expectedCode != 0, so we expect an error
if exitErr, ok := err.(*exec.ExitError); ok {
if exitErr.ExitCode() != expectedCode {
t.Errorf("expected exit code %d, got %d", expectedCode, exitErr.ExitCode())
}
} else {
t.Errorf("expected exit code %d, but got non-exit error or success: %v", expectedCode, err)
}
}
}
// assertNoError checks that there was no error
func assertNoError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
// assertError checks that there was an error
func assertError(t *testing.T, err error) {
t.Helper()
if err == nil {
t.Fatal("expected error but got none")
}
}
// ============================================================================
// Phase 3: Fast CLI Tests (No Browser Required)
// ============================================================================
// TestCLI_Version tests the --version flag
func TestCLI_Version(t *testing.T) {
stdout, stderr, err := runSnag("--version")
assertNoError(t, err)
// Version should be in output (could be stdout or stderr)
output := stdout + stderr
if !strings.Contains(output, "snag version") && !strings.Contains(output, version) {
t.Errorf("expected version in output, got: %s", output)
}
}
// TestCLI_Help tests the --help flag
func TestCLI_Help(t *testing.T) {
stdout, stderr, _ := runSnag("--help")
// Help may exit with 0 or error depending on cli library
output := stdout + stderr
// Should contain usage information
assertContains(t, output, "USAGE")
assertContains(t, output, "snag")
}
// TestCLI_NoArguments tests running without URL
func TestCLI_NoArguments(t *testing.T) {
stdout, stderr, err := runSnag()
// Should fail when no URL provided
assertError(t, err)
assertExitCode(t, err, 1)
output := stdout + stderr
// Should show error or help message
if !strings.Contains(output, "No URLs provided") && !strings.Contains(output, "USAGE") {
t.Errorf("expected error or usage message, got: %s", output)
}
}
// TestCLI_InvalidURL tests invalid URL handling
func TestCLI_InvalidURL(t *testing.T) {
tests := []struct {
url string
desc string
}{
{"ftp://example.com", "unsupported scheme"},
{"javascript:alert(1)", "javascript scheme"},
{"://malformed", "malformed URL"},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
stdout, stderr, err := runSnag(tt.url)
assertError(t, err)
assertExitCode(t, err, 1)
output := stdout + stderr
// Should contain error message
if !strings.Contains(output, "Invalid") && !strings.Contains(output, "invalid") &&
!strings.Contains(output, "error") && !strings.Contains(output, "Error") {
t.Errorf("expected error message for %s, got: %s", tt.desc, output)
}
})
}
}
// TestCLI_InvalidFormat tests invalid format flag
func TestCLI_InvalidFormat(t *testing.T) {
// Use a truly invalid format (json is not supported)
stdout, stderr, err := runSnag("--format", "json", "https://example.com")
assertError(t, err)
assertExitCode(t, err, 1)
output := stdout + stderr
assertContains(t, output, "format")
}
// TestCLI_InvalidTimeout tests invalid timeout values
func TestCLI_InvalidTimeout(t *testing.T) {
tests := []struct {
timeout string
desc string
}{
{"-1", "negative timeout"},
{"0", "zero timeout"},
{"abc", "non-numeric timeout"},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
stdout, stderr, err := runSnag("--timeout", tt.timeout, "https://example.com")
// Should either fail validation or fail to parse
assertError(t, err)
output := stdout + stderr
// Should contain error about timeout or invalid value
if !strings.Contains(output, "timeout") && !strings.Contains(output, "invalid") &&
!strings.Contains(output, "error") && !strings.Contains(output, "Error") {
t.Errorf("expected error message about timeout or invalid value for %s, got: %s", tt.desc, output)
}
})
}
}
// TestCLI_InvalidPort tests invalid port values
func TestCLI_InvalidPort(t *testing.T) {
tests := []struct {
port string
desc string
}{
{"-1", "negative port"},
{"0", "zero port"},
{"99999", "port too large"},
{"abc", "non-numeric port"},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
stdout, stderr, err := runSnag("--port", tt.port, "--force-headless", "https://example.com")
// Should either fail validation or fail to parse
assertError(t, err)
output := stdout + stderr
// Should contain error about port or invalid value
if !strings.Contains(output, "port") && !strings.Contains(output, "invalid") &&
!strings.Contains(output, "error") && !strings.Contains(output, "Error") {
t.Errorf("expected error message about port or invalid value for %s, got: %s", tt.desc, output)
}
})
}
}
// TestCLI_FormatOptions tests valid format values are accepted
func TestCLI_FormatOptions(t *testing.T) {
// Note: These will fail to actually fetch without a browser,
// but should pass format validation
// Test with user-facing format names (aliases that will be normalized)
tests := []string{"markdown", "md", "html", "text", "txt", "pdf", "png"}
for _, format := range tests {
t.Run(format, func(t *testing.T) {
// We can't actually test fetching without a browser,
// but we can verify the format is accepted by checking
// the error message doesn't mention invalid format
stdout, stderr, err := runSnag("--format", format, "--force-headless", "https://example.com")
output := stdout + stderr
// If there's an error, it should NOT be about invalid format
if err != nil {
if strings.Contains(output, "Invalid format") || strings.Contains(output, "invalid format") {
t.Errorf("format %q should be valid but got format error: %s", format, output)
}
// Other errors (like browser not found) are acceptable for this test
}
})
}
}
// TestCLI_ListTabsNoBrowser tests --list-tabs without browser running
func TestCLI_ListTabsNoBrowser(t *testing.T) {
stdout, stderr, err := runSnag("--list-tabs")
// Should fail when no browser is running
assertError(t, err)
assertExitCode(t, err, 1)
output := stdout + stderr
// Should contain error message about no browser running
assertContains(t, output, "No browser")
}
// TestCLI_OutputFilePermission tests output to unwritable location
func TestCLI_OutputFilePermission(t *testing.T) {
// Create a temporary directory and make it read-only
tmpDir := t.TempDir()
readOnlyDir := filepath.Join(tmpDir, "readonly")
err := os.Mkdir(readOnlyDir, 0755)
if err != nil {
t.Fatalf("failed to create test directory: %v", err)
}
// Make directory read-only (no write permission)
err = os.Chmod(readOnlyDir, 0555)
if err != nil {
t.Fatalf("failed to make directory read-only: %v", err)
}
// Ensure cleanup restores permissions so TempDir can clean up
t.Cleanup(func() {
os.Chmod(readOnlyDir, 0755)
})
outputPath := filepath.Join(readOnlyDir, "test-output.md")
stdout, stderr, err := runSnag("-o", outputPath, "--force-headless", "https://example.com")
// Should fail due to permissions
assertError(t, err)
output := stdout + stderr
// May fail with permission error or browser error - both are acceptable
// We're just verifying it doesn't succeed
_ = output
}
// ============================================================================
// Phase 4: Browser Integration Tests (Requires Chrome/Chromium)
// ============================================================================
// TestBrowser_FetchSimpleHTML tests fetching simple.html from test server
func TestBrowser_FetchSimpleHTML(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
stdout, stderr, err := runSnag(url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Verify markdown conversion happened
assertContains(t, stdout, "# Example Heading")
assertContains(t, stdout, "## Second Level Heading")
assertContains(t, stdout, "This is a simple paragraph")
assertContains(t, stdout, "[a link](https://example.com)")
assertContains(t, stdout, "**bold text**")
assertContains(t, stdout, "*italic text*")
// Verify logs went to stderr (not stdout)
if len(stderr) > 0 {
// If there's stderr output, it should be logs, not content
assertNotContains(t, stderr, "# Example Heading")
}
}
// TestBrowser_FetchComplexHTML tests fetching complex.html with tables and lists
func TestBrowser_FetchComplexHTML(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/complex.html"
stdout, stderr, err := runSnag(url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Verify markdown conversion
assertContains(t, stdout, "# Complex Content")
assertContains(t, stdout, "## Table Example")
assertContains(t, stdout, "## List Examples")
assertContains(t, stdout, "## Code Example")
// Verify lists
assertContains(t, stdout, "- Unordered item 1")
assertContains(t, stdout, "- Unordered item 2")
assertContains(t, stdout, "1. Ordered item 1")
assertContains(t, stdout, "2. Ordered item 2")
// Verify code block (should have backticks)
assertContains(t, stdout, "```")
assertContains(t, stdout, "function hello()")
// Note: Table conversion may not produce markdown tables (known issue)
// Just verify table content is preserved
assertContains(t, stdout, "Item 1")
assertContains(t, stdout, "Item 2")
// Verify logs went to stderr
if len(stderr) > 0 {
assertNotContains(t, stderr, "# Complex Content")
}
}
// TestBrowser_FetchMinimalHTML tests fetching minimal.html edge case
func TestBrowser_FetchMinimalHTML(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/minimal.html"
stdout, stderr, err := runSnag(url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should contain the minimal content
assertContains(t, stdout, "Hello")
// Should not be empty
if len(strings.TrimSpace(stdout)) == 0 {
t.Error("expected non-empty output for minimal HTML")
}
// Verify logs went to stderr
if len(stderr) > 0 {
assertNotContains(t, stderr, "Hello")
}
}
// TestBrowser_HTMLFormat tests --format html output
func TestBrowser_HTMLFormat(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
stdout, stderr, err := runSnag("--format", "html", url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Verify HTML output (not markdown)
assertContains(t, stdout, "<h1>")
assertContains(t, stdout, "<h2>")
assertContains(t, stdout, "<p>")
assertContains(t, stdout, "<a href=")
assertContains(t, stdout, "<strong>")
assertContains(t, stdout, "<em>")
// Should NOT contain markdown syntax
assertNotContains(t, stdout, "# Example Heading")
assertNotContains(t, stdout, "**bold text**")
// Verify logs went to stderr
if len(stderr) > 0 {
assertNotContains(t, stderr, "<h1>")
}
}
// TestBrowser_OutputToFile tests -o flag for file output
func TestBrowser_OutputToFile(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
// Create temporary file for output
tmpFile, err := os.CreateTemp("", "snag-test-*.md")
if err != nil {
t.Fatalf("failed to create temp file: %v", err)
}
outputPath := tmpFile.Name()
tmpFile.Close()
// Clean up after test
t.Cleanup(func() {
os.Remove(outputPath)
})
stdout, stderr, err := runSnag("-o", outputPath, url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Stdout should be empty (content written to file)
if len(strings.TrimSpace(stdout)) > 0 {
t.Errorf("expected empty stdout when using -o flag, got: %s", stdout)
}
// Verify file was created and contains content
content, err := os.ReadFile(outputPath)
if err != nil {
t.Fatalf("failed to read output file: %v", err)
}
contentStr := string(content)
assertContains(t, contentStr, "# Example Heading")
assertContains(t, contentStr, "This is a simple paragraph")
// Verify success message in stderr
if len(stderr) > 0 {
// May contain success message about writing file
assertNotContains(t, stderr, "# Example Heading")
}
}
// TestBrowser_ForceHeadless tests --force-headless flag
func TestBrowser_ForceHeadless(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
stdout, stderr, err := runSnag("--force-headless", url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should successfully fetch content
assertContains(t, stdout, "# Example Heading")
// Verify headless mode was used (check stderr for relevant messages)
output := stderr
_ = output // May or may not contain mode indication
}
// TestBrowser_CustomPort tests --port flag with custom debugging port
func TestBrowser_CustomPort(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
// Use a non-default port
stdout, stderr, err := runSnag("--port", "9223", "--force-headless", url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should successfully fetch content
assertContains(t, stdout, "# Example Heading")
output := stderr
_ = output
}
// TestBrowser_Auth401Detection tests HTTP 401 authentication detection
func TestBrowser_Auth401Detection(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
// Create test server with 401 handler
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="Test"`)
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("<html><body>401 Unauthorized</body></html>"))
})
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
url := server.URL
stdout, stderr, err := runSnag(url)
// May fail or succeed depending on how snag handles 401
// At minimum, should not crash
output := stdout + stderr
// Should indicate authentication issue or return the 401 page
// The test verifies snag handles 401 gracefully
_ = output
_ = err
}
// TestBrowser_Auth403Detection tests HTTP 403 forbidden detection
func TestBrowser_Auth403Detection(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
// Create test server with 403 handler
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("<html><body>403 Forbidden</body></html>"))
})
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
url := server.URL
stdout, stderr, err := runSnag(url)
// May fail or succeed depending on how snag handles 403
// At minimum, should not crash
output := stdout + stderr
// Should indicate forbidden access or return the 403 page
_ = output
_ = err
}
// TestBrowser_LoginFormDetection tests detection of login forms in DOM
func TestBrowser_LoginFormDetection(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/login-form.html"
stdout, stderr, err := runSnag(url)
// Should successfully fetch the login form page
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should contain login form content in markdown
assertContains(t, stdout, "Log In")
// Form fields may be converted to markdown
// Just verify content is present
output := stdout + stderr
_ = output
}
// TestBrowser_NoAuthFalsePositives tests that regular pages don't trigger auth detection
func TestBrowser_NoAuthFalsePositives(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
stdout, stderr, err := runSnag(url)
// Regular page should fetch successfully
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should contain normal content
assertContains(t, stdout, "# Example Heading")
// Should NOT have authentication warnings
output := stderr
// If there are auth-related messages in stderr for a regular page, that's a false positive
// However, we don't have specific auth detection messages defined, so just verify success
_ = output
}
// TestBrowser_CustomTimeout tests --timeout flag with custom value
func TestBrowser_CustomTimeout(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
// Use a custom timeout (60 seconds)
stdout, stderr, err := runSnag("--timeout", "60", url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should successfully fetch content
assertContains(t, stdout, "# Example Heading")
output := stderr
_ = output
}
// TestBrowser_WaitForSelector tests --wait-for flag to wait for specific element
func TestBrowser_WaitForSelector(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/dynamic.html"
// Wait for the delayed content element
stdout, stderr, err := runSnag("--wait-for", "#delayed-content", "--timeout", "5", url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should contain both initial and delayed content
assertContains(t, stdout, "Dynamic Page")
assertContains(t, stdout, "after 1 second")
output := stderr
_ = output
}
// TestBrowser_WaitForTimeout tests --wait-for with element that doesn't appear
func TestBrowser_WaitForTimeout(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
// Wait for element that doesn't exist, with short timeout
stdout, stderr, err := runSnag("--wait-for", "#nonexistent-element", "--timeout", "2", url)
// Should timeout and fail
assertError(t, err)
output := stdout + stderr
// Should indicate timeout or element not found
if !strings.Contains(output, "timeout") && !strings.Contains(output, "not found") &&
!strings.Contains(output, "Timeout") {
t.Errorf("Expected timeout error message, got: %s", output)
}
}
// TestBrowser_DefaultTimeout tests that default timeout works
func TestBrowser_DefaultTimeout(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
// No timeout specified, should use default (30 seconds)
stdout, stderr, err := runSnag(url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should successfully fetch content with default timeout
assertContains(t, stdout, "# Example Heading")
output := stderr
_ = output
}
// TestBrowser_CustomUserAgent tests --user-agent flag
func TestBrowser_CustomUserAgent(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
customUA := "Mozilla/5.0 (Custom Bot) snag/test"
stdout, stderr, err := runSnag("--user-agent", customUA, url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should successfully fetch content with custom user agent
assertContains(t, stdout, "# Example Heading")
// User agent is set in browser, content should be fetched normally
output := stderr
_ = output
}
// TestBrowser_CloseTab tests --close-tab flag
func TestBrowser_CloseTab(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
// Use --close-tab with headless mode
stdout, stderr, err := runSnag("--close-tab", "--force-headless", url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should successfully fetch content and close the tab
assertContains(t, stdout, "# Example Heading")
output := stderr
_ = output
}
// TestBrowser_VerboseOutput tests --verbose flag
func TestBrowser_VerboseOutput(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
stdout, stderr, err := runSnag("--verbose", url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should successfully fetch content
assertContains(t, stdout, "# Example Heading")
// Verbose mode should produce more stderr output
// Stderr should have verbose logging messages
if len(stderr) == 0 {
t.Log("verbose mode produced no stderr output (may be expected)")
}
}
// TestBrowser_QuietMode tests --quiet flag
func TestBrowser_QuietMode(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
stdout, stderr, err := runSnag("--quiet", url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should successfully fetch content
assertContains(t, stdout, "# Example Heading")
// Quiet mode should minimize stderr output (only errors)
// Less stderr than normal mode
_ = stderr
}
// TestBrowser_DebugMode tests --debug flag
func TestBrowser_DebugMode(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
server := startTestServer(t)
url := server.URL + "/simple.html"
stdout, stderr, err := runSnag("--debug", url)
assertNoError(t, err)
assertExitCode(t, err, 0)
// Should successfully fetch content
assertContains(t, stdout, "# Example Heading")
// Debug mode should produce detailed stderr output
// Stderr should have debug logging messages
if len(stderr) == 0 {
t.Log("debug mode produced no stderr output (may be expected)")
}
}
// TestBrowser_RealWorld_ExampleDotCom tests fetching a real website (example.com)
func TestBrowser_RealWorld_ExampleDotCom(t *testing.T) {
if !isBrowserAvailable() {
t.Skip("Browser not available, skipping browser integration test")
}
// Skip in environments without internet access
if testing.Short() {
t.Skip("skipping real-world test in short mode")
}
stdout, stderr, err := runSnag("https://example.com")
assertNoError(t, err)
assertExitCode(t, err, 0)