package parser import ( "os" "os/exec" "path/filepath" "testing" ) // fakePdftotext stands in for the real executable: what matters here is how it // is put on disk, not what it does once there. var fakePdftotext = []byte("#!/bin/sh\necho bundled\n") // The bundled copy has to land somewhere it can be exec'd, and run. func TestInstallBundledRuns(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) path, err := installBundled(fakePdftotext) if err != nil { t.Fatal(err) } out, err := exec.Command(path).Output() if err != nil { t.Fatalf("run %s: %v", path, err) } if string(out) != "bundled\n" { t.Errorf("output %q", out) } } // A copy already in place is reused, but only once its contents check out: a // write cut short by a killed process must not become what every later run // trusts. func TestInstallBundledReplacesADamagedCopy(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) path, err := installBundled(fakePdftotext) if err != nil { t.Fatal(err) } if err := os.WriteFile(path, fakePdftotext[:5], 0o755); err != nil { t.Fatal(err) } again, err := installBundled(fakePdftotext) if err != nil { t.Fatal(err) } if again != path { t.Errorf("reinstalled to %s, want %s", again, path) } if got, _ := os.ReadFile(path); string(got) != string(fakePdftotext) { t.Errorf("damaged copy kept: %q", got) } } // Each build's copy has its own name, so a newer binary never runs an older // one's pdftotext left in the same cache. func TestInstallBundledNamesByContent(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) a, err := installBundled(fakePdftotext) if err != nil { t.Fatal(err) } b, err := installBundled(append([]byte(nil), "#!/bin/sh\necho newer\n"...)) if err != nil { t.Fatal(err) } if a == b || filepath.Dir(a) != filepath.Dir(b) { t.Errorf("paths %s and %s, want two names in one directory", a, b) } } // Without -tags bundled, nothing is embedded and PATH decides, as before. func TestUnbundledUsesPath(t *testing.T) { if len(bundledPdftotext) != 0 { t.Skip("built with -tags bundled") } if cmd, err := pdftotextCommand(); err != nil || cmd != "pdftotext" { t.Errorf("command = %q, %v; want pdftotext from PATH", cmd, err) } }