github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/mime/multipart/formdata_test.go (about)

     1  // Copyright 2011 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  
     5  package multipart
     6  
     7  import (
     8  	"bytes"
     9  	"io"
    10  	"os"
    11  	"regexp"
    12  	"testing"
    13  )
    14  
    15  func TestReadForm(t *testing.T) {
    16  	testBody := regexp.MustCompile("\n").ReplaceAllString(message, "\r\n")
    17  	b := bytes.NewBufferString(testBody)
    18  	r := NewReader(b, boundary)
    19  	f, err := r.ReadForm(25)
    20  	if err != nil {
    21  		t.Fatal("ReadForm:", err)
    22  	}
    23  	defer f.RemoveAll()
    24  	if g, e := f.Value["texta"][0], textaValue; g != e {
    25  		t.Errorf("texta value = %q, want %q", g, e)
    26  	}
    27  	if g, e := f.Value["textb"][0], textbValue; g != e {
    28  		t.Errorf("texta value = %q, want %q", g, e)
    29  	}
    30  	fd := testFile(t, f.File["filea"][0], "filea.txt", fileaContents)
    31  	if _, ok := fd.(*os.File); ok {
    32  		t.Error("file is *os.File, should not be")
    33  	}
    34  	fd.Close()
    35  	fd = testFile(t, f.File["fileb"][0], "fileb.txt", filebContents)
    36  	if _, ok := fd.(*os.File); !ok {
    37  		t.Errorf("file has unexpected underlying type %T", fd)
    38  	}
    39  	fd.Close()
    40  }
    41  
    42  func testFile(t *testing.T, fh *FileHeader, efn, econtent string) File {
    43  	if fh.Filename != efn {
    44  		t.Errorf("filename = %q, want %q", fh.Filename, efn)
    45  	}
    46  	f, err := fh.Open()
    47  	if err != nil {
    48  		t.Fatal("opening file:", err)
    49  	}
    50  	b := new(bytes.Buffer)
    51  	_, err = io.Copy(b, f)
    52  	if err != nil {
    53  		t.Fatal("copying contents:", err)
    54  	}
    55  	if g := b.String(); g != econtent {
    56  		t.Errorf("contents = %q, want %q", g, econtent)
    57  	}
    58  	return f
    59  }
    60  
    61  const (
    62  	fileaContents = "This is a test file."
    63  	filebContents = "Another test file."
    64  	textaValue    = "foo"
    65  	textbValue    = "bar"
    66  	boundary      = `MyBoundary`
    67  )
    68  
    69  const message = `
    70  --MyBoundary
    71  Content-Disposition: form-data; name="filea"; filename="filea.txt"
    72  Content-Type: text/plain
    73  
    74  ` + fileaContents + `
    75  --MyBoundary
    76  Content-Disposition: form-data; name="fileb"; filename="fileb.txt"
    77  Content-Type: text/plain
    78  
    79  ` + filebContents + `
    80  --MyBoundary
    81  Content-Disposition: form-data; name="texta"
    82  
    83  ` + textaValue + `
    84  --MyBoundary
    85  Content-Disposition: form-data; name="textb"
    86  
    87  ` + textbValue + `
    88  --MyBoundary--
    89  `