Skip to content

Commit

Permalink
bugfix Controller SaveToFile remove all temp file
Browse files Browse the repository at this point in the history
  • Loading branch information
Stone-afk authored and flycash committed Jan 16, 2023
1 parent df32e9e commit 8d139b8
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- [add singleflight cache for cache module](https://github.com/beego/beego/pull/5119)
- [Fix 5129: must set formatter after init the logger](https://github.com/beego/beego/pull/5130)
- [Fix 5079: only log msg when the channel is not closed](https://github.com/beego/beego/pull/5132)
- [Fix 4435: Controller SaveToFile remove all temp file](https://github.com/beego/beego/pull/5138)

# v2.0.7
- [Upgrade github.com/go-kit/kit, CVE-2022-24450](https://github.com/beego/beego/pull/5121)
Expand Down
2 changes: 1 addition & 1 deletion server/web/context/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func TestSetCookie(t *testing.T) {
output.Context.Reset(httptest.NewRecorder(), r)
for _, item := range c.valueGp {
params := item.item
var others = []interface{}{params.MaxAge, params.Path, params.Domain, params.Secure, params.HttpOnly, params.SameSite}
others := []interface{}{params.MaxAge, params.Path, params.Domain, params.Secure, params.HttpOnly, params.SameSite}
output.Context.SetCookie(params.Name, params.Value, others...)
got := output.Context.ResponseWriter.Header().Get("Set-Cookie")
if got != item.want {
Expand Down
6 changes: 4 additions & 2 deletions server/web/context/input_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,13 @@ func TestBind(t *testing.T) {

{"/?human.Nick=astaxie", []testItem{{"human", Human{}, Human{Nick: "astaxie"}}}},
{"/?human.ID=888&human.Nick=astaxie&human.Ms=true&human[Pwd]=pass", []testItem{{"human", Human{}, Human{ID: 888, Nick: "astaxie", Ms: true, Pwd: "pass"}}}},
{"/?human[0].ID=888&human[0].Nick=astaxie&human[0].Ms=true&human[0][Pwd]=pass01&human[1].ID=999&human[1].Nick=ysqi&human[1].Ms=On&human[1].Pwd=pass02",
{
"/?human[0].ID=888&human[0].Nick=astaxie&human[0].Ms=true&human[0][Pwd]=pass01&human[1].ID=999&human[1].Nick=ysqi&human[1].Ms=On&human[1].Pwd=pass02",
[]testItem{{"human", []Human{}, []Human{
{ID: 888, Nick: "astaxie", Ms: true, Pwd: "pass01"},
{ID: 999, Nick: "ysqi", Ms: true, Pwd: "pass02"},
}}}},
}}},
},

{
"/?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&human.Nick=astaxie",
Expand Down
90 changes: 90 additions & 0 deletions server/web/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@
package web

import (
"bytes"
"io"
"io/ioutil"
"math"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
Expand All @@ -30,6 +33,12 @@ import (
"github.com/beego/beego/v2/server/web/context"
)

var (
fileKey = "file1"
testFile = filepath.Join(currentWorkDir, "test/static/file.txt")
toFile = filepath.Join(currentWorkDir, "test/static/file2.txt")
)

func TestGetInt(t *testing.T) {
i := context.NewInput()
i.SetParam("age", "40")
Expand Down Expand Up @@ -260,6 +269,18 @@ func (t *TestRespController) TestResponse() {
_ = t.Resp(bar)
}

func (t *TestRespController) TestSaveToFile() {
err := t.SaveToFile(fileKey, toFile)
if err != nil {
t.Ctx.WriteString("save file fail")
}
err = os.Remove(toFile)
if err != nil {
t.Ctx.WriteString("save file fail")
}
t.Ctx.WriteString("save file success")
}

type respTestCase struct {
Accept string
ExpectedContentLength int64
Expand Down Expand Up @@ -309,3 +330,72 @@ func testControllerRespTestCases(t *testing.T, tc respTestCase) {
t.Errorf("TestResponse() failed to validate response body '%s' for %s", bodyString, tc.Accept)
}
}

func createReqBody(filePath string) (string, io.Reader, error) {
var err error

buf := new(bytes.Buffer)
bw := multipart.NewWriter(buf) // body writer

f, err := os.Open(filePath)
if err != nil {
return "", nil, err
}
defer func() {
_ = f.Close()
}()

// text part1
p1w, _ := bw.CreateFormField("name")
_, err = p1w.Write([]byte("Tony Bai"))
if err != nil {
return "", nil, err
}

// text part2
p2w, _ := bw.CreateFormField("age")
_, err = p2w.Write([]byte("15"))
if err != nil {
return "", nil, err
}

// file part1
_, fileName := filepath.Split(filePath)
fw1, _ := bw.CreateFormFile(fileKey, fileName)
_, err = io.Copy(fw1, f)
if err != nil {
return "", nil, err
}

_ = bw.Close() // write the tail boundry
return bw.FormDataContentType(), buf, nil
}

func TestControllerSaveFile(t *testing.T) {
// create body
contType, bodyReader, err := createReqBody(testFile)
assert.NoError(t, err)

// create fake POST request
r, _ := http.NewRequest("POST", "/upload_file", bodyReader)
r.Header.Set("Accept", context.ApplicationForm)
r.Header.Set("Content-Type", contType)
w := httptest.NewRecorder()

// setup the handler
handler := NewControllerRegister()
handler.Add("/upload_file", &TestRespController{},
WithRouterMethods(&TestRespController{}, "post:TestSaveToFile"))
handler.ServeHTTP(w, r)

response := w.Result()
bs := make([]byte, 100)
n, err := response.Body.Read(bs)
assert.NoError(t, err)
if string(bs[:n]) == "save file fail" {
t.Errorf("TestSaveToFile() failed to validate response")
}
if response.StatusCode != http.StatusOK {
t.Errorf("TestSaveToFile() failed to validate response code for %s", context.ApplicationJSON)
}
}
45 changes: 45 additions & 0 deletions server/web/test/static/file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<template>
<Container>
<div class="content">
<h1>
Upload files
</h1>
<div class="forms">
<FileForm v-bind:files="files['Model']" name="Model" v-on:upload="upload_model" v-on:submit="submit_model">
</FileForm>
</div>
</div>
</Container>
</template>

<script>
import axios from 'axios'
import Container from '@/components/Container.vue'
import FileForm from '@/components/FileForm.vue'

export default {
name: 'App',
data: function() {
return {
files: {},
}
},
components: {
Container,
FileForm
},
methods: {
upload_model: function(file) {
this.files['Model'] = file
},
submit_model: function() {
let formData = new FormData();
formData.append('Model', this.files['Model']);
axios.put('http://' + document.location.host + '/api/upload_model', formData)
}
},
mounted () {

}
}
</script>
4 changes: 2 additions & 2 deletions server/web/unregroute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,8 @@ func TestUnregisterFixedRouteLevel2(t *testing.T) {
}

func testHelperFnContentCheck(t *testing.T, handler *ControllerRegister,
testName, method, path, expectedBodyContent string) {

testName, method, path, expectedBodyContent string,
) {
r, err := http.NewRequest(method, path, nil)
if err != nil {
t.Errorf("httpRecorderBodyTest NewRequest error: %v", err)
Expand Down

0 comments on commit 8d139b8

Please sign in to comment.