Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: added tests for uploading documents and images. #130

Merged
merged 3 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@ import (
"gorm.io/gorm"
)

const (
DbFolder = "db_data"
DbName = "main.db"
)

var DB *gorm.DB

func ConnectToDB() {
dbPath := fmt.Sprintf("%v/db_data", util.ExPath)
dbPath := fmt.Sprintf("%v/%s", util.ExPath, DbFolder)

_, err := os.Stat(fmt.Sprintf("%v/main.db", dbPath))
_, err := os.Stat(fmt.Sprintf("%v/%s", dbPath, DbName))
if err != nil {
os.Mkdir(dbPath, 0o755)
log.Printf("DB not found, creating at %v/main.db...", dbPath)
Expand Down
260 changes: 260 additions & 0 deletions src/handlers/docs/handleDocUpload_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
package handlers

import (
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"testing"

"github.com/gin-gonic/gin"
"github.com/kevinanielsen/go-fast-cdn/src/database"
"github.com/kevinanielsen/go-fast-cdn/src/util"
"github.com/stretchr/testify/require"
)

var testDataFile []byte = []byte(`Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.`)

func TestHandleDocUpload_NoError(t *testing.T) {
// create tmpFile
pipeRead, pipeWriter := io.Pipe()
writer := multipart.NewWriter(pipeWriter)
go func() {
defer writer.Close()
part, _ := writer.CreateFormFile("doc", "filename.txt")
part.Write(testDataFile)

//h := make(textproto.MIMEHeader)
inlag marked this conversation as resolved.
Show resolved Hide resolved
//h.Set("Content-Disposition", fmt.Sprintf(
// `form-data; name="%s"; filename="%s"`,
// EscapeQuotes("doc"),
// EscapeQuotes("file.txt"),
//))
//h.Set("Content-Type", "text/plain; charset=utf-8")
//part, _ := writer.CreatePart(h)
}()

// init request
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

c.Request = httptest.NewRequest(http.MethodPost, "/api/cdn/upload/doc", pipeRead)
c.Request.Header.Add("Content-Type", writer.FormDataContentType())

// init database
util.ExPath = os.TempDir()
database.ConnectToDB()
defer func() {
filePath := fmt.Sprintf("%s/%s/%s", util.ExPath, database.DbFolder, database.DbName)
err := os.Remove(filePath)
if err != nil {
t.Error(err)
}
}()

// handling
HandleDocUpload(c)

// assert
require.Equal(t, http.StatusOK, w.Result().StatusCode)
}

func TestHandleDocUpload_ReadFailed_NoFile(t *testing.T) {
// create tmpFile
pipeRead, pipeWriter := io.Pipe()
writer := multipart.NewWriter(pipeWriter)
go func() {
defer writer.Close()
part, _ := writer.CreateFormFile("docx", "filename.txt")
part.Write(testDataFile)
}()

// init request
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

c.Request = httptest.NewRequest(http.MethodPost, "/api/cdn/upload/doc", pipeRead)
c.Request.Header.Add("Content-Type", writer.FormDataContentType())

// init database
util.ExPath = os.TempDir()
database.ConnectToDB()
defer func() {
filePath := fmt.Sprintf("%s/%s/%s", util.ExPath, database.DbFolder, database.DbName)
err := os.Remove(filePath)
if err != nil {
t.Error(err)
}
}()

// handling
HandleDocUpload(c)

// assert
require.Equal(t, http.StatusBadRequest, w.Result().StatusCode)
require.Equal(t, w.Body.String(), "Failed to read file: http: no such file")
}

func TestHandleDocUpload_ReadFailed_EOF(t *testing.T) {
// create tmpFile
pipeRead, pipeWriter := io.Pipe()
writer := multipart.NewWriter(pipeWriter)
go func() {
defer writer.Close()
part, _ := writer.CreateFormFile("doc", "filename.txt")
part.Write([]byte(""))
}()

// init request
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

c.Request = httptest.NewRequest(http.MethodPost, "/api/cdn/upload/doc", pipeRead)
c.Request.Header.Add("Content-Type", writer.FormDataContentType())

// init database
util.ExPath = os.TempDir()
database.ConnectToDB()
defer func() {
filePath := fmt.Sprintf("%s/%s/%s", util.ExPath, database.DbFolder, database.DbName)
err := os.Remove(filePath)
if err != nil {
t.Error(err)
}
}()

// handling
HandleDocUpload(c)

// assert
fmt.Println(w.Body.String())
require.Equal(t, http.StatusInternalServerError, w.Result().StatusCode)
require.Equal(t, w.Body.String(), "Failed to read file: EOF")
}

func TestHandleDocUpload_InvalidType(t *testing.T) {
// create tmpFile
pipeRead, pipeWriter := io.Pipe()
writer := multipart.NewWriter(pipeWriter)
go func() {
defer writer.Close()
part, _ := writer.CreateFormFile("doc", "filename.txt")
part.Write([]byte("testDataFile"))
}()

// init request
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

c.Request = httptest.NewRequest(http.MethodPost, "/api/cdn/upload/doc", pipeRead)
c.Request.Header.Add("Content-Type", writer.FormDataContentType())

// init database
util.ExPath = os.TempDir()
database.ConnectToDB()
defer func() {
filePath := fmt.Sprintf("%s/%s/%s", util.ExPath, database.DbFolder, database.DbName)
err := os.Remove(filePath)
if err != nil {
t.Error(err)
}
}()

// handling
HandleDocUpload(c)

// assert
require.Equal(t, http.StatusBadRequest, w.Result().StatusCode)
require.Equal(t, w.Body.String(), "Invalid file type: application/octet-stream")
}

func TestHandleDocUpload_InvalidFilename(t *testing.T) {
// create tmpFile
pipeRead, pipeWriter := io.Pipe()
writer := multipart.NewWriter(pipeWriter)
go func() {
defer writer.Close()
part, _ := writer.CreateFormFile("doc", "file.name.txt")
part.Write(testDataFile)
}()

// init request
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

c.Request = httptest.NewRequest(http.MethodPost, "/api/cdn/upload/doc", pipeRead)
c.Request.Header.Add("Content-Type", writer.FormDataContentType())

// init database
util.ExPath = os.TempDir()
database.ConnectToDB()
defer func() {
filePath := fmt.Sprintf("%s/%s/%s", util.ExPath, database.DbFolder, database.DbName)
err := os.Remove(filePath)
if err != nil {
t.Error(err)
}
}()

// handling
HandleDocUpload(c)

// assert
require.Equal(t, http.StatusBadRequest, w.Result().StatusCode)
require.Equal(t, w.Body.String(), "filename cannot contain more than one period character")
}

func TestHandleDocUpload_FileExist(t *testing.T) {
// create tmpFile
pipeRead, pipeWriter := io.Pipe()
writer := multipart.NewWriter(pipeWriter)
go func() {
defer writer.Close()
part, _ := writer.CreateFormFile("doc", "filename.txt")
part.Write(testDataFile)
}()

// init database
util.ExPath = os.TempDir()
database.ConnectToDB()
defer func() {
filePath := fmt.Sprintf("%s/%s/%s", util.ExPath, database.DbFolder, database.DbName)
err := os.Remove(filePath)
if err != nil {
t.Error(err)
}
}()

// init request
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

c.Request = httptest.NewRequest(http.MethodPost, "/api/cdn/upload/doc", pipeRead)
c.Request.Header.Add("Content-Type", writer.FormDataContentType())

// first handling
HandleDocUpload(c)

// first statement
require.Equal(t, http.StatusOK, w.Result().StatusCode)

// init request
ww := httptest.NewRecorder()
cc, _ := gin.CreateTestContext(ww)
go func() {
defer writer.Close()
part, _ := writer.CreateFormFile("doc", "filename.txt")
part.Write(testDataFile)
}()
cc.Request = httptest.NewRequest(http.MethodPost, "/api/cdn/upload/doc", pipeRead)
cc.Request.Header.Add("Content-Type", writer.FormDataContentType())

// second handling
HandleDocUpload(cc)

//// first statement
require.Equal(t, http.StatusConflict, ww.Result().StatusCode)
require.Equal(t, ww.Body.String(), "\"File already exists\"")
}
Loading
Loading