From 232f0df03f63c6e54659ce0eda661f38b7cc849e Mon Sep 17 00:00:00 2001 From: Umputun Date: Fri, 25 May 2018 14:39:24 -0500 Subject: [PATCH] fix export file with gz close --- app/rest/api/admin.go | 4 +++- app/rest/api/admin_test.go | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/app/rest/api/admin.go b/app/rest/api/admin.go index bf93c870..6a6a2604 100644 --- a/app/rest/api/admin.go +++ b/app/rest/api/admin.go @@ -105,7 +105,9 @@ func (a *admin) exportCtrl(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/gzip") w.Header().Set("Content-Disposition", "attachment;filename="+exportFile) w.WriteHeader(http.StatusOK) - writer = gzip.NewWriter(w) + gzWriter := gzip.NewWriter(w) + defer gzWriter.Close() + writer = gzWriter } if _, err := a.exporter.Export(writer, siteID); err != nil { diff --git a/app/rest/api/admin_test.go b/app/rest/api/admin_test.go index a9c66188..c8be5690 100644 --- a/app/rest/api/admin_test.go +++ b/app/rest/api/admin_test.go @@ -1,12 +1,14 @@ package api import ( + "compress/gzip" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -175,7 +177,7 @@ func TestAdmin_BlockedList(t *testing.T) { assert.Equal(t, "user2", users[1].ID) } -func TestAdmin_Export(t *testing.T) { +func TestAdmin_ExportStream(t *testing.T) { srv, ts := prep(t) assert.NotNil(t, srv) defer cleanup(ts) @@ -194,3 +196,35 @@ func TestAdmin_Export(t *testing.T) { assert.Equal(t, 2, strings.Count(body, "\"text\"")) t.Logf("%s", body) } + +func TestAdmin_ExportFile(t *testing.T) { + srv, ts := prep(t) + assert.NotNil(t, srv) + defer cleanup(ts) + + c1 := store.Comment{Text: "test test #1", + Locator: store.Locator{SiteID: "radio-t", URL: "https://radio-t.com/blah1"}} + c2 := store.Comment{Text: "test test #2", ParentID: "p1", + Locator: store.Locator{SiteID: "radio-t", URL: "https://radio-t.com/blah2"}} + + addComment(t, c1, ts) + addComment(t, c2, ts) + + client := &http.Client{Timeout: 5 * time.Second} + req, err := http.NewRequest("GET", ts.URL+"/api/v1/admin/export?site=radio-t&mode=file", nil) + require.Nil(t, err) + withBasicAuth(req, "dev", "password") + resp, err := client.Do(req) + require.Nil(t, err) + + assert.Equal(t, 200, resp.StatusCode) + assert.Equal(t, "application/gzip", resp.Header.Get("Content-Type")) + + ungzReader, err := gzip.NewReader(resp.Body) + assert.NoError(t, err) + ungzBody, err := ioutil.ReadAll(ungzReader) + assert.NoError(t, err) + assert.Equal(t, 2, strings.Count(string(ungzBody), "\n")) + assert.Equal(t, 2, strings.Count(string(ungzBody), "\"text\"")) + t.Logf("%s", string(ungzBody)) +}