|
1 | | -// SPDX-FileCopyrightText: 2015-2024 caixw |
| 1 | +// SPDX-FileCopyrightText: 2015-2025 caixw |
2 | 2 | // |
3 | 3 | // SPDX-License-Identifier: MIT |
4 | 4 |
|
@@ -65,26 +65,57 @@ func TestUpload_Do(t *testing.T) { |
65 | 65 | f, err := os.Open(filename) |
66 | 66 | a.NotError(err).NotNil(f) |
67 | 67 |
|
68 | | - body := &bytes.Buffer{} |
69 | | - writer := multipart.NewWriter(body) |
70 | | - fw, err := writer.CreateFormFile("file", filename) |
71 | | - a.NotError(err).NotNil(fw) |
| 68 | + body,ct :=formData(a, filename) |
72 | 69 |
|
73 | | - _, err = io.Copy(fw, f) |
74 | | - a.NotError(err) |
| 70 | + r, err := http.NewRequest(http.MethodPost, "/upload", body) |
| 71 | + r.Header.Add("content-type", ct) |
| 72 | + a.NotError(err).NotNil(r) |
75 | 73 |
|
76 | | - err = writer.WriteField("filename", filename) |
77 | | - a.NotError(err) |
| 74 | + paths, err := u.Do("file", r) |
| 75 | + a.NotError(err). |
| 76 | + Length(paths, 1). |
| 77 | + Equal(paths[0], "https://example.com/"+path.Join(time.Now().Format(Day), "file.xml")) |
| 78 | +} |
78 | 79 |
|
79 | | - err = writer.Close() // close writer before POST request |
| 80 | +func TestUpload_Do_None(t *testing.T) { |
| 81 | + a := assert.New(t, false) |
| 82 | + s, err := NewLocalSaver("./testdir", "https://example.com", None, Filename) |
| 83 | + a.NotError(err).NotNil(s) |
| 84 | + |
| 85 | + u := New(s, 10*1024, "xml") |
80 | 86 | a.NotError(err) |
| 87 | + filename := "./testdir/file.xml" |
| 88 | + |
| 89 | + f, err := os.Open(filename) |
| 90 | + a.NotError(err).NotNil(f) |
| 91 | + |
| 92 | + body,ct :=formData(a, filename) |
81 | 93 |
|
82 | 94 | r, err := http.NewRequest(http.MethodPost, "/upload", body) |
83 | | - r.Header.Add("content-type", writer.FormDataContentType()) |
| 95 | + r.Header.Add("content-type", ct) |
84 | 96 | a.NotError(err).NotNil(r) |
85 | 97 |
|
86 | 98 | paths, err := u.Do("file", r) |
87 | 99 | a.NotError(err). |
88 | 100 | Length(paths, 1). |
89 | | - Equal(paths[0], "https://example.com/"+path.Join(time.Now().Format(Day), "file.xml")) |
| 101 | + Equal(paths[0], "https://example.com/"+ "file_1.xml") // 已经 file.xml |
| 102 | +} |
| 103 | + |
| 104 | +func formData(a*assert.Assertion,filename string) (*bytes.Buffer,string) { |
| 105 | + f, err := os.Open(filename) |
| 106 | + a.NotError(err).NotNil(f) |
| 107 | + |
| 108 | + body := &bytes.Buffer{} |
| 109 | + writer := multipart.NewWriter(body) |
| 110 | + fw, err := writer.CreateFormFile("file", filename) |
| 111 | + a.NotError(err).NotNil(fw) |
| 112 | + |
| 113 | + _, err = io.Copy(fw, f) |
| 114 | + a.NotError(err) |
| 115 | + |
| 116 | + ct :=writer.FormDataContentType() |
| 117 | + err = writer.Close() // close writer before POST request |
| 118 | + a.NotError(err) |
| 119 | + |
| 120 | + return body,ct |
90 | 121 | } |
0 commit comments