-
Notifications
You must be signed in to change notification settings - Fork 3
/
stream_writer_test.go
121 lines (104 loc) · 2.61 KB
/
stream_writer_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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Copyright (c) 2017 Andrey Gayvoronsky <plandem@gmail.com>
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package ooxml_test
import (
"archive/zip"
"bytes"
"encoding/xml"
"github.com/plandem/ooxml"
"github.com/stretchr/testify/require"
"testing"
)
func TestStreamFileWriter(t *testing.T) {
type Email struct {
Where string `xml:"where,attr"`
Addr string
}
type Address struct {
City, State string
}
type Person struct {
Name string `xml:"FullName"`
Phone string
Email []Email
Groups []string `xml:"Group>Value"`
Address
}
fileName := `xl/worksheets/sheet1.xml`
tests := []struct {
name string
memory bool
}{
{"tempFile", false},
{"memory", true},
}
streamClosed := false
for _, info := range tests {
t.Run(info.name, func(tt *testing.T) {
sheetStream, err := ooxml.NewStreamFileWriter(fileName, info.memory, func() error {
streamClosed = true
return nil
})
require.IsType(tt, &ooxml.StreamFileWriter{}, sheetStream)
require.Nil(tt, err)
persons := []*Person{
{
Name: "John Doe",
Email: []Email{
{Where: "home", Addr: "john@example.com"},
{Where: "work", Addr: "john@work.com"},
},
Groups: []string{"husband", "father"},
Address: Address{
City: "Denver",
State: "Colorado",
},
},
{
Name: "Jane Dow",
Email: []Email{
{Where: "home", Addr: "jane@example.com"},
{Where: "work", Addr: "jane@work.com"},
},
Groups: []string{"wife", "mother"},
Address: Address{
City: "Washington",
State: "Washington",
},
},
}
err = sheetStream.Encode(persons[0])
require.Nil(tt, err)
err = sheetStream.Encode(persons[1])
require.Nil(tt, err)
//prepare target zip
buf := bytes.NewBuffer(nil)
zipper := zip.NewWriter(buf)
//add stream file into the target
err = sheetStream.Save(zipper)
require.Equal(tt, true, streamClosed)
require.Nil(tt, err)
err = zipper.Close()
require.Nil(tt, err)
//open file
readerAt := bytes.NewReader(buf.Bytes())
reader, err := zip.NewReader(readerAt, int64(readerAt.Len()))
require.Nil(tt, err)
//file has same name
require.Equal(tt, fileName, reader.File[0].Name)
zipFile, err := reader.File[0].Open()
require.Nil(tt, err)
//content is same
decoder := xml.NewDecoder(zipFile)
result := make([]*Person, 0)
err = decoder.Decode(&result)
require.Nil(tt, err)
err = decoder.Decode(&result)
require.Nil(tt, err)
require.Equal(tt, persons, result)
err = zipFile.Close()
require.Nil(tt, err)
})
}
}