1
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseTxt(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "a.txt")
|
||||
if err := os.WriteFile(path, []byte("第一行\n\n## 标题\n第二行"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text, err := ParseFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, part := range []string{"第一行", "## 标题", "第二行"} {
|
||||
if !strings.Contains(text, part) {
|
||||
t.Errorf("missing %q in %q", part, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseHtml(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "b.html")
|
||||
html := `<html><body><h1>文档标题</h1><p>正文第一段。</p><p>正文第二段。</p></body></html>`
|
||||
if err := os.WriteFile(path, []byte(html), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text, err := ParseFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, part := range []string{"文档标题", "正文第一段", "正文第二段"} {
|
||||
if !strings.Contains(text, part) {
|
||||
t.Errorf("missing %q in %q", part, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDocx(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "c.docx")
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zw := zip.NewWriter(f)
|
||||
w, err := zw.Create("word/document.xml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xml := `<?xml version="1.0"?><w:document xmlns:w="urn:x"><w:body><w:p><w:r><w:t>第一段落</w:t></w:r></w:p><w:p><w:r><w:t>第二段落</w:t></w:r></w:p></w:body></w:document>`
|
||||
if _, err := w.Write([]byte(xml)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
text, err := ParseFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, part := range []string{"第一段落", "第二段落"} {
|
||||
if !strings.Contains(text, part) {
|
||||
t.Errorf("missing %q in %q", part, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePdf(t *testing.T) {
|
||||
path := "/Users/zhangbin/go/pkg/mod/github.com/pdfcpu/pdfcpu@v0.14.0/pkg/testdata/testRot.pdf"
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Skip("pdfcpu testdata not found")
|
||||
}
|
||||
text, err := ParseFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.TrimSpace(text) == "" {
|
||||
t.Fatal("pdf text is empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseUnsupported(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "d.xyz")
|
||||
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ParseFile(path); err == nil {
|
||||
t.Fatal("expected error for unsupported type")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user