| 1 | package docx_test |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "bytes" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "unicode" |
| 13 | |
| 14 | "github.com/carlosframework/docs/internal/docx" |
| 15 | "github.com/carlosframework/docs/internal/export" |
| 16 | ) |
| 17 | |
| 18 | // The fixtures in this file are SYNTHESIZED: OOXML written by hand in the |
| 19 | // shapes Google Docs' DOCX export uses (its namespaces, its styles, a link |
| 20 | // as w:hyperlink, a suggestion as w:ins/w:del, a table, a list paragraph). |
| 21 | // None of them is a real Google export. A real export, with permission to |
| 22 | // commit its contents, has not been supplied; until one is, this reader's |
| 23 | // agreement with Google's actual output is unproven beyond these shapes, |
| 24 | // and the gap is recorded in the branch discussion. |
| 25 | |
| 26 | const docNS = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ` + |
| 27 | `xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ` + |
| 28 | `xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ` + |
| 29 | `xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ` + |
| 30 | `xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" mc:Ignorable="w14"` |
| 31 | |
| 32 | // googleStyles is a styles part shaped like Google's: Arial 11pt as the |
| 33 | // document default and on Normal, and the named heading, title and |
| 34 | // subtitle styles. |
| 35 | const googleStyles = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + |
| 36 | `<w:styles ` + docNS + `>` + |
| 37 | `<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Arial" w:cs="Arial" w:eastAsia="Arial" w:hAnsi="Arial"/>` + |
| 38 | `<w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en"/></w:rPr></w:rPrDefault>` + |
| 39 | `<w:pPrDefault><w:pPr><w:spacing w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>` + |
| 40 | `<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="normal"/></w:style>` + |
| 41 | `<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/>` + |
| 42 | `<w:pPr><w:keepNext w:val="1"/></w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:style>` + |
| 43 | `<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/>` + |
| 44 | `<w:rPr><w:sz w:val="32"/></w:rPr></w:style>` + |
| 45 | `<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/>` + |
| 46 | `<w:rPr><w:sz w:val="52"/></w:rPr></w:style>` + |
| 47 | `<w:style w:type="paragraph" w:styleId="Subtitle"><w:name w:val="Subtitle"/><w:basedOn w:val="Normal"/>` + |
| 48 | `<w:rPr><w:color w:val="666666"/><w:sz w:val="30"/></w:rPr></w:style>` + |
| 49 | `</w:styles>` |
| 50 | |
| 51 | // The link targets are hostile on purpose. Import never reads the |
| 52 | // relationships part, so none of them may appear anywhere in its output. |
| 53 | const hostileRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + |
| 54 | `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` + |
| 55 | `<Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="javascript:alert(document.cookie)" TargetMode="External"/>` + |
| 56 | `<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="file:///etc/passwd" TargetMode="External"/>` + |
| 57 | `<Relationship Id="rId11" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="http://169.254.169.254/latest/meta-data/" TargetMode="External"/>` + |
| 58 | `</Relationships>` |
| 59 | |
| 60 | func run(props, text string) string { |
| 61 | if props != "" { |
| 62 | props = "<w:rPr>" + props + "</w:rPr>" |
| 63 | } |
| 64 | return `<w:r>` + props + `<w:t xml:space="preserve">` + text + `</w:t></w:r>` |
| 65 | } |
| 66 | |
| 67 | func para(style, content string) string { |
| 68 | ppr := "" |
| 69 | if style != "" { |
| 70 | ppr = `<w:pPr><w:pStyle w:val="` + style + `"/></w:pPr>` |
| 71 | } |
| 72 | return `<w:p>` + ppr + content + `</w:p>` |
| 73 | } |
| 74 | |
| 75 | // googleShaped is the synthesized fixture: every container whose text the |
| 76 | // old reader lost, plus the omissions the report must name. |
| 77 | func googleShaped(t *testing.T) []byte { |
| 78 | t.Helper() |
| 79 | body := para("Title", run("", "Quarterly plan")) + |
| 80 | para("Heading1", run("", "Summary")) + |
| 81 | // A link, inside a paragraph, with hostile targets in the rels. |
| 82 | para("", run("", "Visit ")+`<w:hyperlink r:id="rId9"><w:r><w:rPr><w:color w:val="1155CC"/><w:u w:val="single"/></w:rPr><w:t>our site</w:t></w:r></w:hyperlink>`+run("", ".")) + |
| 83 | // Explicit bold off, the true spellings of on, and italic. |
| 84 | para("", run(`<w:b w:val="0"/>`, "not bold, ")+run(`<w:b/>`, "bold, ")+run(`<w:b w:val="false"/>`, "off again, ")+run(`<w:b w:val="1"/><w:i w:val="true"/>`, "both")) + |
| 85 | // A list item. |
| 86 | `<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr>` + run("", "First item") + `</w:p>` + |
| 87 | // A table, with a nested table in one cell. |
| 88 | `<w:tbl><w:tblPr/><w:tr><w:tc><w:tcPr/>` + para("", run("", "A1")) + `</w:tc><w:tc>` + para("", run("", "B1")) + `</w:tc></w:tr>` + |
| 89 | `<w:tr><w:tc>` + para("", run("", "A2")) + `<w:tbl><w:tr><w:tc>` + para("", run("", "inner")) + `</w:tc></w:tr></w:tbl></w:tc><w:tc>` + para("", run("", "B2")) + `</w:tc></w:tr></w:tbl>` + |
| 90 | // A suggestion: an insertion is kept, a deletion is not. |
| 91 | para("", run("", "Kept ")+`<w:ins w:id="1" w:author="Someone" w:date="2026-10-01T00:00:00Z">`+run("", "added")+`</w:ins>`+ |
| 92 | `<w:del w:id="2" w:author="Someone" w:date="2026-10-01T00:00:00Z"><w:r><w:delText>removed</w:delText></w:r></w:del>`+run("", " text")) + |
| 93 | // A block content control and a smart tag. |
| 94 | `<w:sdt><w:sdtPr><w:alias w:val="x"/></w:sdtPr><w:sdtContent>` + para("", run("", "in a control")) + `</w:sdtContent></w:sdt>` + |
| 95 | para("", `<w:smartTag w:uri="urn:x" w:element="place">`+run("", "Smart")+`</w:smartTag>`+` <w:sdt><w:sdtContent>`+run("", " inline")+`</w:sdtContent></w:sdt>`) + |
| 96 | // A tab, a line break and a page break. |
| 97 | para("", `<w:r><w:t>before</w:t><w:tab/><w:t>after</w:t><w:br/><w:t>next line</w:t><w:br w:type="page"/><w:t>next page</w:t></w:r>`) + |
| 98 | // An image, a footnote, a comment, a size off the ladder, an |
| 99 | // unknown face, a centred paragraph, a heading level. |
| 100 | para("", `<w:r><w:drawing><wp:inline/></w:drawing></w:r>`+run("", "Caption")+`<w:r><w:footnoteReference w:id="1"/></w:r>`+ |
| 101 | `<w:commentRangeStart w:id="0"/>`+run(`<w:sz w:val="30"/>`, "fifteen")+`<w:commentRangeEnd w:id="0"/><w:r><w:commentReference w:id="0"/></w:r>`+ |
| 102 | run(`<w:rFonts w:ascii="Comic Sans MS" w:hAnsi="Comic Sans MS"/>`, " comic")+run(`<w:sz w:val="28"/>`, " fourteen")) + |
| 103 | `<w:p><w:pPr><w:jc w:val="center"/></w:pPr>` + run("", "Centred") + `</w:p>` + |
| 104 | para("Subtitle", run("", "A subtitle")) + |
| 105 | para("Heading2", run(`<w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman"/>`, "Serif heading")) + |
| 106 | para("", "") + |
| 107 | `<w:sectPr><w:headerReference w:type="default" r:id="rId12"/><w:pgSz w:w="12240" w:h="15840"/></w:sectPr>` |
| 108 | return zipOf(t, map[string]string{ |
| 109 | "[Content_Types].xml": `<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>`, |
| 110 | "word/document.xml": `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document ` + docNS + `><w:body>` + body + `</w:body></w:document>`, |
| 111 | "word/styles.xml": googleStyles, |
| 112 | "word/_rels/document.xml.rels": hostileRels, |
| 113 | "word/comments.xml": `<w:comments ` + docNS + `/>`, |
| 114 | }) |
| 115 | } |
| 116 | |
| 117 | func zipOf(t *testing.T, parts map[string]string) []byte { |
| 118 | t.Helper() |
| 119 | var buf bytes.Buffer |
| 120 | z := zip.NewWriter(&buf) |
| 121 | for name, body := range parts { |
| 122 | w, err := z.Create(name) |
| 123 | if err != nil { |
| 124 | t.Fatal(err) |
| 125 | } |
| 126 | io.WriteString(w, body) |
| 127 | } |
| 128 | if err := z.Close(); err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | return buf.Bytes() |
| 132 | } |
| 133 | |
| 134 | // shape renders a document as one line per block: its type, then each |
| 135 | // run as text{marks}. |
| 136 | func shape(d export.Document) []string { |
| 137 | var out []string |
| 138 | for _, b := range d.Root.Content { |
| 139 | line := b.Type |
| 140 | if b.Type == "heading" { |
| 141 | line += fmt.Sprint(b.Attrs.Level) |
| 142 | } |
| 143 | line += ":" |
| 144 | for _, r := range b.Content { |
| 145 | var marks []string |
| 146 | for _, m := range r.Marks { |
| 147 | marks = append(marks, m.Type) |
| 148 | } |
| 149 | line += r.Text |
| 150 | if len(marks) > 0 { |
| 151 | line += "{" + strings.Join(marks, ",") + "}" |
| 152 | } |
| 153 | line += "|" |
| 154 | } |
| 155 | out = append(out, line) |
| 156 | } |
| 157 | return out |
| 158 | } |
| 159 | |
| 160 | func TestImportReadsEveryContainerGoogleExportsTextIn(t *testing.T) { |
| 161 | res, err := docx.Import(googleShaped(t)) |
| 162 | if err != nil { |
| 163 | t.Fatal(err) |
| 164 | } |
| 165 | // Arial is Liberation Sans (font_sans) and 11pt is size_11, Google's |
| 166 | // default, so ordinary runs carry both; headings carry no inherited |
| 167 | // size, because a heading's size is its level's here. |
| 168 | const body = "font_sans,size_11" |
| 169 | want := []string{ |
| 170 | "heading1:Quarterly plan{font_sans}|", |
| 171 | "heading1:Summary{font_sans}|", |
| 172 | "paragraph:Visit {" + body + "}|our site{" + body + "}|.{" + body + "}|", |
| 173 | "paragraph:not bold, {" + body + "}|bold, {" + body + ",strong}|off again, {" + body + "}|both{" + body + ",strong,em}|", |
| 174 | "paragraph:First item{" + body + "}|", |
| 175 | "paragraph:A1{" + body + "}|", |
| 176 | "paragraph:B1{" + body + "}|", |
| 177 | "paragraph:A2{" + body + "}|", |
| 178 | "paragraph:inner{" + body + "}|", |
| 179 | "paragraph:B2{" + body + "}|", |
| 180 | "paragraph:Kept {" + body + "}|added{" + body + "}| text{" + body + "}|", |
| 181 | "paragraph:in a control{" + body + "}|", |
| 182 | "paragraph:Smart{" + body + "}| inline{" + body + "}|", |
| 183 | "paragraph:before{" + body + "}| {" + body + "}|after{" + body + "}|", |
| 184 | "paragraph:next line{" + body + "}|", |
| 185 | "paragraph:next page{" + body + "}|", |
| 186 | "paragraph:Caption{" + body + "}|fifteen{font_sans}| comic{size_11}| fourteen{font_sans,size_14}|", |
| 187 | "paragraph:Centred{" + body + "}|", |
| 188 | "paragraph:A subtitle{font_sans}|", |
| 189 | "heading2:Serif heading{font_serif}|", |
| 190 | "paragraph:", |
| 191 | } |
| 192 | got := shape(res.Document) |
| 193 | if strings.Join(got, "\n") != strings.Join(want, "\n") { |
| 194 | t.Errorf("document\n got:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) |
| 195 | } |
| 196 | |
| 197 | type line struct { |
| 198 | count int |
| 199 | where string |
| 200 | names string |
| 201 | } |
| 202 | wantReport := map[docx.Code]line{ |
| 203 | docx.CodeTableFlattened: {2, "6,9", ""}, |
| 204 | docx.CodeListFlattened: {1, "5", ""}, |
| 205 | docx.CodeLinkTextKept: {1, "3", ""}, |
| 206 | docx.CodeInsertionKept: {1, "11", ""}, |
| 207 | docx.CodeDeletionOmitted: {1, "11", ""}, |
| 208 | docx.CodeObjectOmitted: {1, "17", ""}, |
| 209 | docx.CodeNotesOmitted: {1, "17", ""}, |
| 210 | docx.CodeCommentsOmitted: {1, "17", ""}, |
| 211 | docx.CodeHeadersOmitted: {1, "", ""}, |
| 212 | docx.CodeTitleAsHeading: {1, "1", ""}, |
| 213 | docx.CodeSubtitleAsParagraph: {1, "19", ""}, |
| 214 | docx.CodeFontSubstituted: {1, "17", ""}, |
| 215 | docx.CodeSizeDropped: {2, "17,19", ""}, |
| 216 | docx.CodeFormattingLost: {2, "3,19", ""}, |
| 217 | docx.CodeAlignmentLost: {1, "18", ""}, |
| 218 | docx.CodeTabAsSpace: {1, "14", ""}, |
| 219 | docx.CodeLineBreakSplit: {1, "15", ""}, |
| 220 | docx.CodePageBreakSplit: {1, "16", ""}, |
| 221 | } |
| 222 | gotReport := map[docx.Code]line{} |
| 223 | for _, it := range res.Report.Items { |
| 224 | var where []string |
| 225 | for _, p := range it.Paragraphs { |
| 226 | where = append(where, fmt.Sprint(p)) |
| 227 | } |
| 228 | gotReport[it.Code] = line{it.Count, strings.Join(where, ","), ""} |
| 229 | } |
| 230 | for code, w := range wantReport { |
| 231 | if g, ok := gotReport[code]; !ok { |
| 232 | t.Errorf("report has no %s", code) |
| 233 | } else if g != w { |
| 234 | t.Errorf("report %s: got %+v, want %+v", code, g, w) |
| 235 | } |
| 236 | } |
| 237 | for code := range gotReport { |
| 238 | if _, ok := wantReport[code]; !ok { |
| 239 | t.Errorf("report has an unexpected %s: %+v", code, gotReport[code]) |
| 240 | } |
| 241 | } |
| 242 | // The report lists in Codes order. |
| 243 | at := map[docx.Code]int{} |
| 244 | for i, c := range docx.Codes { |
| 245 | at[c] = i |
| 246 | } |
| 247 | for i := 1; i < len(res.Report.Items); i++ { |
| 248 | if at[res.Report.Items[i-1].Code] > at[res.Report.Items[i].Code] { |
| 249 | t.Errorf("report out of order at %d", i) |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | // The reader this replaced bound w:body>w:p>w:r>w:t alone and read w:b |
| 255 | // by presence, with no error and no report. Run against it (its Read at |
| 256 | // 056b94d), the first eleven cases below failed: link, table, insertion, |
| 257 | // both content controls, smart tag and field text came back missing, |
| 258 | // bold-off and italic-off came back on, and a tab or break joined its |
| 259 | // neighbours. The last two passed there too; they are here because a |
| 260 | // walk that descends into everything could get them wrong where an |
| 261 | // unmarshal into fixed paths could not. |
| 262 | func TestImportKeepsWhatTheOldReaderLost(t *testing.T) { |
| 263 | for _, c := range []struct { |
| 264 | name, body, want string |
| 265 | }{ |
| 266 | {"link", para("", `<w:hyperlink r:id="rId9">`+run("", "linked")+`</w:hyperlink>`), "paragraph:linked|"}, |
| 267 | {"table", `<w:tbl><w:tr><w:tc>` + para("", run("", "cell")) + `</w:tc></w:tr></w:tbl>`, "paragraph:cell|"}, |
| 268 | {"insertion", para("", `<w:ins w:id="1" w:author="a">`+run("", "inserted")+`</w:ins>`), "paragraph:inserted|"}, |
| 269 | {"block content control", `<w:sdt><w:sdtContent>` + para("", run("", "controlled")) + `</w:sdtContent></w:sdt>`, "paragraph:controlled|"}, |
| 270 | {"inline content control", para("", `<w:sdt><w:sdtContent>`+run("", "inline")+`</w:sdtContent></w:sdt>`), "paragraph:inline|"}, |
| 271 | {"smart tag", para("", `<w:smartTag w:element="x">`+run("", "tagged")+`</w:smartTag>`), "paragraph:tagged|"}, |
| 272 | {"simple field", para("", `<w:fldSimple w:instr="PAGE">`+run("", "7")+`</w:fldSimple>`), "paragraph:7|"}, |
| 273 | {"bold off", para("", run(`<w:b w:val="0"/>`, "plain")), "paragraph:plain|"}, |
| 274 | {"italic off", para("", run(`<w:i w:val="false"/>`, "plain")), "paragraph:plain|"}, |
| 275 | {"tab", para("", `<w:r><w:t>a</w:t><w:tab/><w:t>b</w:t></w:r>`), "paragraph:a| |b|"}, |
| 276 | {"break", para("", `<w:r><w:t>a</w:t><w:br/><w:t>b</w:t></w:r>`), "paragraph:a|\nparagraph:b|"}, |
| 277 | {"deletion is not text", para("", run("", "kept")+`<w:del w:id="1" w:author="a"><w:r><w:delText>gone</w:delText></w:r></w:del>`), "paragraph:kept|"}, |
| 278 | {"paragraph mark properties are not the run's", `<w:p><w:pPr><w:rPr><w:b/></w:rPr></w:pPr>` + run("", "plain") + `</w:p>`, "paragraph:plain|"}, |
| 279 | } { |
| 280 | data := zipOf(t, map[string]string{ |
| 281 | "word/document.xml": `<w:document ` + docNS + `><w:body>` + c.body + `</w:body></w:document>`, |
| 282 | }) |
| 283 | res, err := docx.Import(data) |
| 284 | if err != nil { |
| 285 | t.Errorf("%s: %v", c.name, err) |
| 286 | continue |
| 287 | } |
| 288 | if got := strings.Join(shape(res.Document), "\n"); got != c.want { |
| 289 | t.Errorf("%s: got %q, want %q", c.name, got, c.want) |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | // Bold and italic come through the whole cascade: document default, |
| 295 | // paragraph style chain, character style, run, with an explicit off at |
| 296 | // any nearer level winning. What a style carries that Docs cannot hold is |
| 297 | // reported for the paragraphs it reaches, not dropped in silence. |
| 298 | func TestImportFollowsTheStyleCascade(t *testing.T) { |
| 299 | styles := `<w:styles ` + docNS + `>` + |
| 300 | `<w:docDefaults><w:rPrDefault><w:rPr><w:i/></w:rPr></w:rPrDefault></w:docDefaults>` + |
| 301 | `<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>` + |
| 302 | `<w:style w:type="paragraph" w:styleId="Strong"><w:name w:val="Strong body"/><w:basedOn w:val="Normal"/><w:rPr><w:b/></w:rPr></w:style>` + |
| 303 | `<w:style w:type="paragraph" w:styleId="StrongChild"><w:name w:val="Strong child"/><w:basedOn w:val="Strong"/><w:rPr><w:i w:val="0"/></w:rPr></w:style>` + |
| 304 | `<w:style w:type="paragraph" w:styleId="Red"><w:name w:val="Red"/><w:rPr><w:color w:val="FF0000"/></w:rPr></w:style>` + |
| 305 | `<w:style w:type="paragraph" w:styleId="Centred"><w:name w:val="Centred"/><w:pPr><w:jc w:val="center"/></w:pPr></w:style>` + |
| 306 | `<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:rPr><w:b/><w:color w:val="FF0000"/><w:sz w:val="40"/></w:rPr></w:style>` + |
| 307 | `<w:style w:type="character" w:styleId="Emph"><w:name w:val="Emph"/><w:rPr><w:i/><w:u w:val="single"/></w:rPr></w:style>` + |
| 308 | `</w:styles>` |
| 309 | body := para("", run("", "default italic")) + |
| 310 | para("Strong", run("", "style bold")+run(`<w:b w:val="0"/>`, "run says not bold")) + |
| 311 | para("StrongChild", run("", "inherited bold, italic off")) + |
| 312 | para("", run(`<w:rStyle w:val="Emph"/><w:i w:val="0"/>`, "character style, italic off")+run(`<w:rStyle w:val="Emph"/>`, "character style")) + |
| 313 | para("Red", run("", "red")) + |
| 314 | para("Centred", run("", "centred")) + |
| 315 | `<w:p><w:pPr><w:pStyle w:val="Centred"/><w:jc w:val="left"/></w:pPr>` + run("", "left after all") + `</w:p>` + |
| 316 | para("Heading1", run("", "heading")) |
| 317 | res, err := docx.Import(zipOf(t, map[string]string{ |
| 318 | "word/styles.xml": styles, |
| 319 | "word/document.xml": `<w:document ` + docNS + `><w:body>` + body + `</w:body></w:document>`, |
| 320 | })) |
| 321 | if err != nil { |
| 322 | t.Fatal(err) |
| 323 | } |
| 324 | want := []string{ |
| 325 | "paragraph:default italic{em}|", |
| 326 | "paragraph:style bold{strong,em}|run says not bold{em}|", |
| 327 | "paragraph:inherited bold, italic off{strong}|", |
| 328 | "paragraph:character style, italic off|character style{em}|", |
| 329 | "paragraph:red{em}|", |
| 330 | "paragraph:centred{em}|", |
| 331 | "paragraph:left after all{em}|", |
| 332 | "heading1:heading|", |
| 333 | } |
| 334 | if got := strings.Join(shape(res.Document), "\n"); got != strings.Join(want, "\n") { |
| 335 | t.Errorf("document\n got:\n%s\nwant:\n%s", got, strings.Join(want, "\n")) |
| 336 | } |
| 337 | where := map[docx.Code]string{} |
| 338 | for _, it := range res.Report.Items { |
| 339 | var ps []string |
| 340 | for _, p := range it.Paragraphs { |
| 341 | ps = append(ps, fmt.Sprint(p)) |
| 342 | } |
| 343 | where[it.Code] = strings.Join(ps, ",") |
| 344 | } |
| 345 | if where[docx.CodeFormattingLost] != "4,5" { |
| 346 | t.Errorf("formatting lost at %q, want the underlined character style (4) and the red paragraph style (5)", where[docx.CodeFormattingLost]) |
| 347 | } |
| 348 | if where[docx.CodeAlignmentLost] != "6" { |
| 349 | t.Errorf("alignment lost at %q, want the centred style's paragraph only (6)", where[docx.CodeAlignmentLost]) |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | func TestImportNeverReadsALinkTarget(t *testing.T) { |
| 354 | res, err := docx.Import(googleShaped(t)) |
| 355 | if err != nil { |
| 356 | t.Fatal(err) |
| 357 | } |
| 358 | out, _ := json.Marshal(res) |
| 359 | for _, s := range []string{"javascript", "alert", "/etc/passwd", "169.254", "rId9", "Someone"} { |
| 360 | if strings.Contains(string(out), s) { |
| 361 | t.Errorf("the result carries %q from the file's metadata", s) |
| 362 | } |
| 363 | } |
| 364 | // The report is closed metadata: codes, counts and paragraph |
| 365 | // numbers. No text from the file, and no face name either. |
| 366 | rep, _ := json.Marshal(res.Report) |
| 367 | for _, s := range []string{"Comic", "Arial", "Quarterly", "Summary", "our site", "removed"} { |
| 368 | if strings.Contains(string(rep), s) { |
| 369 | t.Errorf("the report quotes %q from the file", s) |
| 370 | } |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | func TestImportDropsControlCharacters(t *testing.T) { |
| 375 | data := zipOf(t, map[string]string{ |
| 376 | "word/document.xml": `<w:document ` + docNS + `><w:body>` + para("", run("", "a\u0085b	c\nd")) + `</w:body></w:document>`, |
| 377 | }) |
| 378 | res, err := docx.Import(data) |
| 379 | if err != nil { |
| 380 | t.Fatal(err) |
| 381 | } |
| 382 | if got := strings.Join(shape(res.Document), ""); got != "paragraph:ab c d|" { |
| 383 | t.Errorf("got %q", got) |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | func TestImportRefusals(t *testing.T) { |
| 388 | doc := func(body string) map[string]string { |
| 389 | return map[string]string{"word/document.xml": `<w:document ` + docNS + `><w:body>` + body + `</w:body></w:document>`} |
| 390 | } |
| 391 | deep := strings.Repeat(`<w:sdt><w:sdtContent>`, 300) + para("", run("", "x")) + strings.Repeat(`</w:sdtContent></w:sdt>`, 300) |
| 392 | many := map[string]string{"word/document.xml": doc(para("", run("", "x")))["word/document.xml"]} |
| 393 | for i := 0; i < 1001; i++ { |
| 394 | many[fmt.Sprintf("word/media/%d.bin", i)] = "" |
| 395 | } |
| 396 | cases := []struct { |
| 397 | name string |
| 398 | data []byte |
| 399 | want error |
| 400 | }{ |
| 401 | {"not a zip", []byte("%PDF-1.7 not a word file"), docx.ErrNotWord}, |
| 402 | {"no document part", zipOf(t, map[string]string{"word/styles.xml": googleStyles}), docx.ErrNotWord}, |
| 403 | {"a spreadsheet", zipOf(t, map[string]string{"xl/workbook.xml": "<workbook/>"}), docx.ErrNotWord}, |
| 404 | {"wrong root", zipOf(t, map[string]string{"word/document.xml": `<html/>`}), docx.ErrNotWord}, |
| 405 | {"not well formed", zipOf(t, doc(`<w:p><w:r>`)), docx.ErrMalformed}, |
| 406 | {"a DTD", zipOf(t, map[string]string{"word/document.xml": `<!DOCTYPE w:document [<!ENTITY a "aaaa">]><w:document ` + docNS + `/>`}), docx.ErrMalformed}, |
| 407 | {"too deep", zipOf(t, doc(deep)), docx.ErrMalformed}, |
| 408 | {"too many entries", zipOf(t, many), docx.ErrTooLarge}, |
| 409 | {"nothing but empty paragraphs", zipOf(t, doc(para("", "")+para("", `<w:r><w:drawing/></w:r>`))), docx.ErrEmpty}, |
| 410 | {"only deleted text", zipOf(t, doc(para("", `<w:del><w:r><w:delText>x</w:delText></w:r></w:del>`))), docx.ErrEmpty}, |
| 411 | {"too many blocks", zipOf(t, doc(strings.Repeat(para("", run("", "x")), 5_001))), docx.ErrTooLarge}, |
| 412 | {"too much text", zipOf(t, doc(para("", run("", strings.Repeat("x", 512<<10+1))))), docx.ErrTooLarge}, |
| 413 | {"too many runs", zipOf(t, doc(para("", strings.Repeat(run("", "x"), 10_001)))), docx.ErrTooLarge}, |
| 414 | } |
| 415 | for _, c := range cases { |
| 416 | if _, err := docx.Import(c.data); !errors.Is(err, c.want) { |
| 417 | t.Errorf("%s: got %v, want %v", c.name, err, c.want) |
| 418 | } |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | // A part whose decompressed size is far past its compressed one is |
| 423 | // refused from the bytes actually read, not from the header's claim. |
| 424 | func TestImportCountsDecompressedBytes(t *testing.T) { |
| 425 | var buf bytes.Buffer |
| 426 | z := zip.NewWriter(&buf) |
| 427 | w, _ := z.Create("word/document.xml") |
| 428 | io.WriteString(w, `<w:document `+docNS+`><w:body>`) |
| 429 | pad := bytes.Repeat([]byte(" "), 1<<20) |
| 430 | for i := 0; i < 33; i++ { |
| 431 | w.Write(pad) |
| 432 | } |
| 433 | io.WriteString(w, `</w:body></w:document>`) |
| 434 | z.Close() |
| 435 | if buf.Len() > 1<<20 { |
| 436 | t.Fatalf("the bomb is %d bytes compressed; the test means a small file", buf.Len()) |
| 437 | } |
| 438 | if _, err := docx.Import(buf.Bytes()); !errors.Is(err, docx.ErrTooLarge) { |
| 439 | t.Errorf("got %v, want ErrTooLarge", err) |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | func TestImportRefusesADuplicatedPart(t *testing.T) { |
| 444 | var buf bytes.Buffer |
| 445 | z := zip.NewWriter(&buf) |
| 446 | for _, body := range []string{para("", run("", "one")), para("", run("", "two"))} { |
| 447 | w, _ := z.Create("word/document.xml") |
| 448 | io.WriteString(w, `<w:document `+docNS+`><w:body>`+body+`</w:body></w:document>`) |
| 449 | } |
| 450 | z.Close() |
| 451 | if _, err := docx.Import(buf.Bytes()); !errors.Is(err, docx.ErrMalformed) { |
| 452 | t.Errorf("got %v, want ErrMalformed", err) |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | // Whatever the bytes, Import either refuses with one of its own errors |
| 457 | // or returns runs the builder accepts: non-empty, no control character. |
| 458 | func FuzzImport(f *testing.F) { |
| 459 | var tb testing.T |
| 460 | f.Add(googleShaped(&tb)) |
| 461 | f.Add([]byte("PK\x03\x04")) |
| 462 | f.Fuzz(func(t *testing.T, data []byte) { |
| 463 | res, err := docx.Import(data) |
| 464 | if err != nil { |
| 465 | for _, known := range []error{docx.ErrNotWord, docx.ErrMalformed, docx.ErrTooLarge, docx.ErrEmpty} { |
| 466 | if errors.Is(err, known) { |
| 467 | return |
| 468 | } |
| 469 | } |
| 470 | t.Fatalf("unexpected error %v", err) |
| 471 | } |
| 472 | for _, b := range res.Document.Root.Content { |
| 473 | for _, r := range b.Content { |
| 474 | if r.Text == "" || strings.IndexFunc(r.Text, unicode.IsControl) >= 0 { |
| 475 | t.Fatalf("a run the builder would refuse: %q", r.Text) |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | }) |
| 480 | } |
| 481 | |