PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/third_party/gofrontend/libgo/go/mime/multipart/multipart_test.go

http://github.com/axw/llgo
Go | 686 lines | 591 code | 60 blank | 35 comment | 130 complexity | 51ae13d25bf7ea37d28ab624eb8c47a2 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT
  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package multipart
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net/textproto"
  12. "os"
  13. "reflect"
  14. "strings"
  15. "testing"
  16. )
  17. func TestBoundaryLine(t *testing.T) {
  18. mr := NewReader(strings.NewReader(""), "myBoundary")
  19. if !mr.isBoundaryDelimiterLine([]byte("--myBoundary\r\n")) {
  20. t.Error("expected")
  21. }
  22. if !mr.isBoundaryDelimiterLine([]byte("--myBoundary \r\n")) {
  23. t.Error("expected")
  24. }
  25. if !mr.isBoundaryDelimiterLine([]byte("--myBoundary \n")) {
  26. t.Error("expected")
  27. }
  28. if mr.isBoundaryDelimiterLine([]byte("--myBoundary bogus \n")) {
  29. t.Error("expected fail")
  30. }
  31. if mr.isBoundaryDelimiterLine([]byte("--myBoundary bogus--")) {
  32. t.Error("expected fail")
  33. }
  34. }
  35. func escapeString(v string) string {
  36. bytes, _ := json.Marshal(v)
  37. return string(bytes)
  38. }
  39. func expectEq(t *testing.T, expected, actual, what string) {
  40. if expected == actual {
  41. return
  42. }
  43. t.Errorf("Unexpected value for %s; got %s (len %d) but expected: %s (len %d)",
  44. what, escapeString(actual), len(actual), escapeString(expected), len(expected))
  45. }
  46. func TestNameAccessors(t *testing.T) {
  47. tests := [...][3]string{
  48. {`form-data; name="foo"`, "foo", ""},
  49. {` form-data ; name=foo`, "foo", ""},
  50. {`FORM-DATA;name="foo"`, "foo", ""},
  51. {` FORM-DATA ; name="foo"`, "foo", ""},
  52. {` FORM-DATA ; name="foo"`, "foo", ""},
  53. {` FORM-DATA ; name=foo`, "foo", ""},
  54. {` FORM-DATA ; filename="foo.txt"; name=foo; baz=quux`, "foo", "foo.txt"},
  55. {` not-form-data ; filename="bar.txt"; name=foo; baz=quux`, "", "bar.txt"},
  56. }
  57. for i, test := range tests {
  58. p := &Part{Header: make(map[string][]string)}
  59. p.Header.Set("Content-Disposition", test[0])
  60. if g, e := p.FormName(), test[1]; g != e {
  61. t.Errorf("test %d: FormName() = %q; want %q", i, g, e)
  62. }
  63. if g, e := p.FileName(), test[2]; g != e {
  64. t.Errorf("test %d: FileName() = %q; want %q", i, g, e)
  65. }
  66. }
  67. }
  68. var longLine = strings.Repeat("\n\n\r\r\r\n\r\000", (1<<20)/8)
  69. func testMultipartBody(sep string) string {
  70. testBody := `
  71. This is a multi-part message. This line is ignored.
  72. --MyBoundary
  73. Header1: value1
  74. HEADER2: value2
  75. foo-bar: baz
  76. My value
  77. The end.
  78. --MyBoundary
  79. name: bigsection
  80. [longline]
  81. --MyBoundary
  82. Header1: value1b
  83. HEADER2: value2b
  84. foo-bar: bazb
  85. Line 1
  86. Line 2
  87. Line 3 ends in a newline, but just one.
  88. --MyBoundary
  89. never read data
  90. --MyBoundary--
  91. useless trailer
  92. `
  93. testBody = strings.Replace(testBody, "\n", sep, -1)
  94. return strings.Replace(testBody, "[longline]", longLine, 1)
  95. }
  96. func TestMultipart(t *testing.T) {
  97. bodyReader := strings.NewReader(testMultipartBody("\r\n"))
  98. testMultipart(t, bodyReader, false)
  99. }
  100. func TestMultipartOnlyNewlines(t *testing.T) {
  101. bodyReader := strings.NewReader(testMultipartBody("\n"))
  102. testMultipart(t, bodyReader, true)
  103. }
  104. func TestMultipartSlowInput(t *testing.T) {
  105. bodyReader := strings.NewReader(testMultipartBody("\r\n"))
  106. testMultipart(t, &slowReader{bodyReader}, false)
  107. }
  108. func testMultipart(t *testing.T, r io.Reader, onlyNewlines bool) {
  109. reader := NewReader(r, "MyBoundary")
  110. buf := new(bytes.Buffer)
  111. // Part1
  112. part, err := reader.NextPart()
  113. if part == nil || err != nil {
  114. t.Error("Expected part1")
  115. return
  116. }
  117. if x := part.Header.Get("Header1"); x != "value1" {
  118. t.Errorf("part.Header.Get(%q) = %q, want %q", "Header1", x, "value1")
  119. }
  120. if x := part.Header.Get("foo-bar"); x != "baz" {
  121. t.Errorf("part.Header.Get(%q) = %q, want %q", "foo-bar", x, "baz")
  122. }
  123. if x := part.Header.Get("Foo-Bar"); x != "baz" {
  124. t.Errorf("part.Header.Get(%q) = %q, want %q", "Foo-Bar", x, "baz")
  125. }
  126. buf.Reset()
  127. if _, err := io.Copy(buf, part); err != nil {
  128. t.Errorf("part 1 copy: %v", err)
  129. }
  130. adjustNewlines := func(s string) string {
  131. if onlyNewlines {
  132. return strings.Replace(s, "\r\n", "\n", -1)
  133. }
  134. return s
  135. }
  136. expectEq(t, adjustNewlines("My value\r\nThe end."), buf.String(), "Value of first part")
  137. // Part2
  138. part, err = reader.NextPart()
  139. if err != nil {
  140. t.Fatalf("Expected part2; got: %v", err)
  141. return
  142. }
  143. if e, g := "bigsection", part.Header.Get("name"); e != g {
  144. t.Errorf("part2's name header: expected %q, got %q", e, g)
  145. }
  146. buf.Reset()
  147. if _, err := io.Copy(buf, part); err != nil {
  148. t.Errorf("part 2 copy: %v", err)
  149. }
  150. s := buf.String()
  151. if len(s) != len(longLine) {
  152. t.Errorf("part2 body expected long line of length %d; got length %d",
  153. len(longLine), len(s))
  154. }
  155. if s != longLine {
  156. t.Errorf("part2 long body didn't match")
  157. }
  158. // Part3
  159. part, err = reader.NextPart()
  160. if part == nil || err != nil {
  161. t.Error("Expected part3")
  162. return
  163. }
  164. if part.Header.Get("foo-bar") != "bazb" {
  165. t.Error("Expected foo-bar: bazb")
  166. }
  167. buf.Reset()
  168. if _, err := io.Copy(buf, part); err != nil {
  169. t.Errorf("part 3 copy: %v", err)
  170. }
  171. expectEq(t, adjustNewlines("Line 1\r\nLine 2\r\nLine 3 ends in a newline, but just one.\r\n"),
  172. buf.String(), "body of part 3")
  173. // Part4
  174. part, err = reader.NextPart()
  175. if part == nil || err != nil {
  176. t.Error("Expected part 4 without errors")
  177. return
  178. }
  179. // Non-existent part5
  180. part, err = reader.NextPart()
  181. if part != nil {
  182. t.Error("Didn't expect a fifth part.")
  183. }
  184. if err != io.EOF {
  185. t.Errorf("On fifth part expected io.EOF; got %v", err)
  186. }
  187. }
  188. func TestVariousTextLineEndings(t *testing.T) {
  189. tests := [...]string{
  190. "Foo\nBar",
  191. "Foo\nBar\n",
  192. "Foo\r\nBar",
  193. "Foo\r\nBar\r\n",
  194. "Foo\rBar",
  195. "Foo\rBar\r",
  196. "\x00\x01\x02\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10",
  197. }
  198. for testNum, expectedBody := range tests {
  199. body := "--BOUNDARY\r\n" +
  200. "Content-Disposition: form-data; name=\"value\"\r\n" +
  201. "\r\n" +
  202. expectedBody +
  203. "\r\n--BOUNDARY--\r\n"
  204. bodyReader := strings.NewReader(body)
  205. reader := NewReader(bodyReader, "BOUNDARY")
  206. buf := new(bytes.Buffer)
  207. part, err := reader.NextPart()
  208. if part == nil {
  209. t.Errorf("Expected a body part on text %d", testNum)
  210. continue
  211. }
  212. if err != nil {
  213. t.Errorf("Unexpected error on text %d: %v", testNum, err)
  214. continue
  215. }
  216. written, err := io.Copy(buf, part)
  217. expectEq(t, expectedBody, buf.String(), fmt.Sprintf("test %d", testNum))
  218. if err != nil {
  219. t.Errorf("Error copying multipart; bytes=%v, error=%v", written, err)
  220. }
  221. part, err = reader.NextPart()
  222. if part != nil {
  223. t.Errorf("Unexpected part in test %d", testNum)
  224. }
  225. if err != io.EOF {
  226. t.Errorf("On test %d expected io.EOF; got %v", testNum, err)
  227. }
  228. }
  229. }
  230. type maliciousReader struct {
  231. t *testing.T
  232. n int
  233. }
  234. const maxReadThreshold = 1 << 20
  235. func (mr *maliciousReader) Read(b []byte) (n int, err error) {
  236. mr.n += len(b)
  237. if mr.n >= maxReadThreshold {
  238. mr.t.Fatal("too much was read")
  239. return 0, io.EOF
  240. }
  241. return len(b), nil
  242. }
  243. func TestLineLimit(t *testing.T) {
  244. mr := &maliciousReader{t: t}
  245. r := NewReader(mr, "fooBoundary")
  246. part, err := r.NextPart()
  247. if part != nil {
  248. t.Errorf("unexpected part read")
  249. }
  250. if err == nil {
  251. t.Errorf("expected an error")
  252. }
  253. if mr.n >= maxReadThreshold {
  254. t.Errorf("expected to read < %d bytes; read %d", maxReadThreshold, mr.n)
  255. }
  256. }
  257. func TestMultipartTruncated(t *testing.T) {
  258. testBody := `
  259. This is a multi-part message. This line is ignored.
  260. --MyBoundary
  261. foo-bar: baz
  262. Oh no, premature EOF!
  263. `
  264. body := strings.Replace(testBody, "\n", "\r\n", -1)
  265. bodyReader := strings.NewReader(body)
  266. r := NewReader(bodyReader, "MyBoundary")
  267. part, err := r.NextPart()
  268. if err != nil {
  269. t.Fatalf("didn't get a part")
  270. }
  271. _, err = io.Copy(ioutil.Discard, part)
  272. if err != io.ErrUnexpectedEOF {
  273. t.Fatalf("expected error io.ErrUnexpectedEOF; got %v", err)
  274. }
  275. }
  276. type slowReader struct {
  277. r io.Reader
  278. }
  279. func (s *slowReader) Read(p []byte) (int, error) {
  280. if len(p) == 0 {
  281. return s.r.Read(p)
  282. }
  283. return s.r.Read(p[:1])
  284. }
  285. func TestLineContinuation(t *testing.T) {
  286. // This body, extracted from an email, contains headers that span multiple
  287. // lines.
  288. // TODO: The original mail ended with a double-newline before the
  289. // final delimiter; this was manually edited to use a CRLF.
  290. testBody :=
  291. "\n--Apple-Mail-2-292336769\nContent-Transfer-Encoding: 7bit\nContent-Type: text/plain;\n\tcharset=US-ASCII;\n\tdelsp=yes;\n\tformat=flowed\n\nI'm finding the same thing happening on my system (10.4.1).\n\n\n--Apple-Mail-2-292336769\nContent-Transfer-Encoding: quoted-printable\nContent-Type: text/html;\n\tcharset=ISO-8859-1\n\n<HTML><BODY>I'm finding the same thing =\nhappening on my system (10.4.1).=A0 But I built it with XCode =\n2.0.</BODY></=\nHTML>=\n\r\n--Apple-Mail-2-292336769--\n"
  292. r := NewReader(strings.NewReader(testBody), "Apple-Mail-2-292336769")
  293. for i := 0; i < 2; i++ {
  294. part, err := r.NextPart()
  295. if err != nil {
  296. t.Fatalf("didn't get a part")
  297. }
  298. var buf bytes.Buffer
  299. n, err := io.Copy(&buf, part)
  300. if err != nil {
  301. t.Errorf("error reading part: %v\nread so far: %q", err, buf.String())
  302. }
  303. if n <= 0 {
  304. t.Errorf("read %d bytes; expected >0", n)
  305. }
  306. }
  307. }
  308. func TestQuotedPrintableEncoding(t *testing.T) {
  309. // From https://golang.org/issue/4411
  310. body := "--0016e68ee29c5d515f04cedf6733\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=text\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nwords words words words words words words words words words words words wor=\r\nds words words words words words words words words words words words words =\r\nwords words words words words words words words words words words words wor=\r\nds words words words words words words words words words words words words =\r\nwords words words words words words words words words\r\n--0016e68ee29c5d515f04cedf6733\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=submit\r\n\r\nSubmit\r\n--0016e68ee29c5d515f04cedf6733--"
  311. r := NewReader(strings.NewReader(body), "0016e68ee29c5d515f04cedf6733")
  312. part, err := r.NextPart()
  313. if err != nil {
  314. t.Fatal(err)
  315. }
  316. if te, ok := part.Header["Content-Transfer-Encoding"]; ok {
  317. t.Errorf("unexpected Content-Transfer-Encoding of %q", te)
  318. }
  319. var buf bytes.Buffer
  320. _, err = io.Copy(&buf, part)
  321. if err != nil {
  322. t.Error(err)
  323. }
  324. got := buf.String()
  325. want := "words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words"
  326. if got != want {
  327. t.Errorf("wrong part value:\n got: %q\nwant: %q", got, want)
  328. }
  329. }
  330. // Test parsing an image attachment from gmail, which previously failed.
  331. func TestNested(t *testing.T) {
  332. // nested-mime is the body part of a multipart/mixed email
  333. // with boundary e89a8ff1c1e83553e304be640612
  334. f, err := os.Open("testdata/nested-mime")
  335. if err != nil {
  336. t.Fatal(err)
  337. }
  338. defer f.Close()
  339. mr := NewReader(f, "e89a8ff1c1e83553e304be640612")
  340. p, err := mr.NextPart()
  341. if err != nil {
  342. t.Fatalf("error reading first section (alternative): %v", err)
  343. }
  344. // Read the inner text/plain and text/html sections of the multipart/alternative.
  345. mr2 := NewReader(p, "e89a8ff1c1e83553e004be640610")
  346. p, err = mr2.NextPart()
  347. if err != nil {
  348. t.Fatalf("reading text/plain part: %v", err)
  349. }
  350. if b, err := ioutil.ReadAll(p); string(b) != "*body*\r\n" || err != nil {
  351. t.Fatalf("reading text/plain part: got %q, %v", b, err)
  352. }
  353. p, err = mr2.NextPart()
  354. if err != nil {
  355. t.Fatalf("reading text/html part: %v", err)
  356. }
  357. if b, err := ioutil.ReadAll(p); string(b) != "<b>body</b>\r\n" || err != nil {
  358. t.Fatalf("reading text/html part: got %q, %v", b, err)
  359. }
  360. p, err = mr2.NextPart()
  361. if err != io.EOF {
  362. t.Fatalf("final inner NextPart = %v; want io.EOF", err)
  363. }
  364. // Back to the outer multipart/mixed, reading the image attachment.
  365. _, err = mr.NextPart()
  366. if err != nil {
  367. t.Fatalf("error reading the image attachment at the end: %v", err)
  368. }
  369. _, err = mr.NextPart()
  370. if err != io.EOF {
  371. t.Fatalf("final outer NextPart = %v; want io.EOF", err)
  372. }
  373. }
  374. type headerBody struct {
  375. header textproto.MIMEHeader
  376. body string
  377. }
  378. func formData(key, value string) headerBody {
  379. return headerBody{
  380. textproto.MIMEHeader{
  381. "Content-Type": {"text/plain; charset=ISO-8859-1"},
  382. "Content-Disposition": {"form-data; name=" + key},
  383. },
  384. value,
  385. }
  386. }
  387. type parseTest struct {
  388. name string
  389. in, sep string
  390. want []headerBody
  391. }
  392. var parseTests = []parseTest{
  393. // Actual body from App Engine on a blob upload. The final part (the
  394. // Content-Type: message/external-body) is what App Engine replaces
  395. // the uploaded file with. The other form fields (prefixed with
  396. // "other" in their form-data name) are unchanged. A bug was
  397. // reported with blob uploads failing when the other fields were
  398. // empty. This was the MIME POST body that previously failed.
  399. {
  400. name: "App Engine post",
  401. sep: "00151757727e9583fd04bfbca4c6",
  402. in: "--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherEmpty1\r\n\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherFoo1\r\n\r\nfoo\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherFoo2\r\n\r\nfoo\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherEmpty2\r\n\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherRepeatFoo\r\n\r\nfoo\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherRepeatFoo\r\n\r\nfoo\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherRepeatEmpty\r\n\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherRepeatEmpty\r\n\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=submit\r\n\r\nSubmit\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: message/external-body; charset=ISO-8859-1; blob-key=AHAZQqG84qllx7HUqO_oou5EvdYQNS3Mbbkb0RjjBoM_Kc1UqEN2ygDxWiyCPulIhpHRPx-VbpB6RX4MrsqhWAi_ZxJ48O9P2cTIACbvATHvg7IgbvZytyGMpL7xO1tlIvgwcM47JNfv_tGhy1XwyEUO8oldjPqg5Q\r\nContent-Disposition: form-data; name=file; filename=\"fall.png\"\r\n\r\nContent-Type: image/png\r\nContent-Length: 232303\r\nX-AppEngine-Upload-Creation: 2012-05-10 23:14:02.715173\r\nContent-MD5: MzRjODU1ZDZhZGU1NmRlOWEwZmMwMDdlODBmZTA0NzA=\r\nContent-Disposition: form-data; name=file; filename=\"fall.png\"\r\n\r\n\r\n--00151757727e9583fd04bfbca4c6--",
  403. want: []headerBody{
  404. formData("otherEmpty1", ""),
  405. formData("otherFoo1", "foo"),
  406. formData("otherFoo2", "foo"),
  407. formData("otherEmpty2", ""),
  408. formData("otherRepeatFoo", "foo"),
  409. formData("otherRepeatFoo", "foo"),
  410. formData("otherRepeatEmpty", ""),
  411. formData("otherRepeatEmpty", ""),
  412. formData("submit", "Submit"),
  413. {textproto.MIMEHeader{
  414. "Content-Type": {"message/external-body; charset=ISO-8859-1; blob-key=AHAZQqG84qllx7HUqO_oou5EvdYQNS3Mbbkb0RjjBoM_Kc1UqEN2ygDxWiyCPulIhpHRPx-VbpB6RX4MrsqhWAi_ZxJ48O9P2cTIACbvATHvg7IgbvZytyGMpL7xO1tlIvgwcM47JNfv_tGhy1XwyEUO8oldjPqg5Q"},
  415. "Content-Disposition": {"form-data; name=file; filename=\"fall.png\""},
  416. }, "Content-Type: image/png\r\nContent-Length: 232303\r\nX-AppEngine-Upload-Creation: 2012-05-10 23:14:02.715173\r\nContent-MD5: MzRjODU1ZDZhZGU1NmRlOWEwZmMwMDdlODBmZTA0NzA=\r\nContent-Disposition: form-data; name=file; filename=\"fall.png\"\r\n\r\n"},
  417. },
  418. },
  419. // Single empty part, ended with --boundary immediately after headers.
  420. {
  421. name: "single empty part, --boundary",
  422. sep: "abc",
  423. in: "--abc\r\nFoo: bar\r\n\r\n--abc--",
  424. want: []headerBody{
  425. {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
  426. },
  427. },
  428. // Single empty part, ended with \r\n--boundary immediately after headers.
  429. {
  430. name: "single empty part, \r\n--boundary",
  431. sep: "abc",
  432. in: "--abc\r\nFoo: bar\r\n\r\n\r\n--abc--",
  433. want: []headerBody{
  434. {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
  435. },
  436. },
  437. // Final part empty.
  438. {
  439. name: "final part empty",
  440. sep: "abc",
  441. in: "--abc\r\nFoo: bar\r\n\r\n--abc\r\nFoo2: bar2\r\n\r\n--abc--",
  442. want: []headerBody{
  443. {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
  444. {textproto.MIMEHeader{"Foo2": {"bar2"}}, ""},
  445. },
  446. },
  447. // Final part empty with newlines after final separator.
  448. {
  449. name: "final part empty then crlf",
  450. sep: "abc",
  451. in: "--abc\r\nFoo: bar\r\n\r\n--abc--\r\n",
  452. want: []headerBody{
  453. {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
  454. },
  455. },
  456. // Final part empty with lwsp-chars after final separator.
  457. {
  458. name: "final part empty then lwsp",
  459. sep: "abc",
  460. in: "--abc\r\nFoo: bar\r\n\r\n--abc-- \t",
  461. want: []headerBody{
  462. {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
  463. },
  464. },
  465. // No parts (empty form as submitted by Chrome)
  466. {
  467. name: "no parts",
  468. sep: "----WebKitFormBoundaryQfEAfzFOiSemeHfA",
  469. in: "------WebKitFormBoundaryQfEAfzFOiSemeHfA--\r\n",
  470. want: []headerBody{},
  471. },
  472. // Part containing data starting with the boundary, but with additional suffix.
  473. {
  474. name: "fake separator as data",
  475. sep: "sep",
  476. in: "--sep\r\nFoo: bar\r\n\r\n--sepFAKE\r\n--sep--",
  477. want: []headerBody{
  478. {textproto.MIMEHeader{"Foo": {"bar"}}, "--sepFAKE"},
  479. },
  480. },
  481. // Part containing a boundary with whitespace following it.
  482. {
  483. name: "boundary with whitespace",
  484. sep: "sep",
  485. in: "--sep \r\nFoo: bar\r\n\r\ntext\r\n--sep--",
  486. want: []headerBody{
  487. {textproto.MIMEHeader{"Foo": {"bar"}}, "text"},
  488. },
  489. },
  490. // With ignored leading line.
  491. {
  492. name: "leading line",
  493. sep: "MyBoundary",
  494. in: strings.Replace(`This is a multi-part message. This line is ignored.
  495. --MyBoundary
  496. foo: bar
  497. --MyBoundary--`, "\n", "\r\n", -1),
  498. want: []headerBody{
  499. {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
  500. },
  501. },
  502. // Issue 10616; minimal
  503. {
  504. name: "issue 10616 minimal",
  505. sep: "sep",
  506. in: "--sep \r\nFoo: bar\r\n\r\n" +
  507. "a\r\n" +
  508. "--sep_alt\r\n" +
  509. "b\r\n" +
  510. "\r\n--sep--",
  511. want: []headerBody{
  512. {textproto.MIMEHeader{"Foo": {"bar"}}, "a\r\n--sep_alt\r\nb\r\n"},
  513. },
  514. },
  515. // Issue 10616; full example from bug.
  516. {
  517. name: "nested separator prefix is outer separator",
  518. sep: "----=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9",
  519. in: strings.Replace(`------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9
  520. Content-Type: multipart/alternative; boundary="----=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt"
  521. ------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt
  522. Content-Type: text/plain; charset="utf-8"
  523. Content-Transfer-Encoding: 8bit
  524. This is a multi-part message in MIME format.
  525. ------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt
  526. Content-Type: text/html; charset="utf-8"
  527. Content-Transfer-Encoding: 8bit
  528. html things
  529. ------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt--
  530. ------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9--`, "\n", "\r\n", -1),
  531. want: []headerBody{
  532. {textproto.MIMEHeader{"Content-Type": {`multipart/alternative; boundary="----=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt"`}},
  533. strings.Replace(`------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt
  534. Content-Type: text/plain; charset="utf-8"
  535. Content-Transfer-Encoding: 8bit
  536. This is a multi-part message in MIME format.
  537. ------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt
  538. Content-Type: text/html; charset="utf-8"
  539. Content-Transfer-Encoding: 8bit
  540. html things
  541. ------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt--`, "\n", "\r\n", -1),
  542. },
  543. },
  544. },
  545. roundTripParseTest(),
  546. }
  547. func TestParse(t *testing.T) {
  548. Cases:
  549. for _, tt := range parseTests {
  550. r := NewReader(strings.NewReader(tt.in), tt.sep)
  551. got := []headerBody{}
  552. for {
  553. p, err := r.NextPart()
  554. if err == io.EOF {
  555. break
  556. }
  557. if err != nil {
  558. t.Errorf("in test %q, NextPart: %v", tt.name, err)
  559. continue Cases
  560. }
  561. pbody, err := ioutil.ReadAll(p)
  562. if err != nil {
  563. t.Errorf("in test %q, error reading part: %v", tt.name, err)
  564. continue Cases
  565. }
  566. got = append(got, headerBody{p.Header, string(pbody)})
  567. }
  568. if !reflect.DeepEqual(tt.want, got) {
  569. t.Errorf("test %q:\n got: %v\nwant: %v", tt.name, got, tt.want)
  570. if len(tt.want) != len(got) {
  571. t.Errorf("test %q: got %d parts, want %d", tt.name, len(got), len(tt.want))
  572. } else if len(got) > 1 {
  573. for pi, wantPart := range tt.want {
  574. if !reflect.DeepEqual(wantPart, got[pi]) {
  575. t.Errorf("test %q, part %d:\n got: %v\nwant: %v", tt.name, pi, got[pi], wantPart)
  576. }
  577. }
  578. }
  579. }
  580. }
  581. }
  582. func roundTripParseTest() parseTest {
  583. t := parseTest{
  584. name: "round trip",
  585. want: []headerBody{
  586. formData("empty", ""),
  587. formData("lf", "\n"),
  588. formData("cr", "\r"),
  589. formData("crlf", "\r\n"),
  590. formData("foo", "bar"),
  591. },
  592. }
  593. var buf bytes.Buffer
  594. w := NewWriter(&buf)
  595. for _, p := range t.want {
  596. pw, err := w.CreatePart(p.header)
  597. if err != nil {
  598. panic(err)
  599. }
  600. _, err = pw.Write([]byte(p.body))
  601. if err != nil {
  602. panic(err)
  603. }
  604. }
  605. w.Close()
  606. t.in = buf.String()
  607. t.sep = w.Boundary()
  608. return t
  609. }