-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptspkg_test.go
99 lines (89 loc) · 2.13 KB
/
optspkg_test.go
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
package parser_test // this is a package test
import (
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/rorycl/letters/email"
"github.com/rorycl/letters/parser"
)
func TestPkgOptVerbose(t *testing.T) {
opt := parser.WithVerbose()
_ = parser.NewParser(opt)
}
// TestPkgNoAttachments tests to ensure that no attachments are
// processed with the WithoutAttachments option.
func TestPkgNoAttachments(t *testing.T) {
p := parser.NewParser(parser.WithoutAttachments())
c, err := os.Open("testdata/cats.eml")
if err != nil {
t.Fatal(err)
}
defer c.Close()
e, err := p.Parse(c)
if err != nil {
t.Fatal(err)
}
if len(e.Files) > 0 {
t.Error("expected no files for parser.WithoutAttachments")
}
}
// TestPkgOptFileFilter shows an example of a file filter to only save
// jpeg images from an email.
func TestPkgOptFileFilter(t *testing.T) {
expectedNames := []string{"cat1.jpg", "cat3.jpg"}
tempDir, err := os.MkdirTemp("", "letters-pkg-tmpdir-*")
if err != nil {
t.Fatal(err)
}
// customJPGFileFunc selects only attached or inline files with the
// ContentType of image/jpeg
customJPGFileFunc := func(ef *email.File) error {
fcc := strings.ToLower(ef.ContentInfo.Type)
if fcc != "image/jpeg" {
return nil
}
f, err := os.Create(filepath.Join(tempDir, ef.Name))
if err != nil {
return fmt.Errorf("file creation error %w", err)
}
defer f.Close()
_, err = io.Copy(f, ef.Reader)
if err != nil {
return fmt.Errorf("file saving error %w", err)
}
return nil
}
// make option, add to parser constructor, parse email
dirOpt := parser.WithCustomFileFunc(customJPGFileFunc)
p := parser.NewParser(dirOpt)
c, err := os.Open("testdata/cats.eml")
if err != nil {
t.Fatal(err)
}
_, err = p.Parse(c)
if err != nil {
t.Fatal(err)
}
// check the output
dir, err := os.ReadDir(tempDir)
if err != nil {
t.Fatal(err)
}
files := []string{}
for _, f := range dir {
files = append(files, f.Name())
}
slices.Sort(files)
if diff := cmp.Diff(expectedNames, files); diff != "" {
t.Error(diff)
}
err = os.RemoveAll(tempDir)
if err != nil {
t.Fatal(err)
}
}