youtube-dl-service/backend/main_test.go
2021-12-10 13:43:33 +01:00

108 lines
2.2 KiB
Go

package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"git.andreafazzi.eu/andrea/youtube-dl-service/downloader"
"git.andreafazzi.eu/andrea/youtube-dl-service/logger"
"git.andreafazzi.eu/andrea/youtube-dl-service/task"
"github.com/gin-gonic/gin"
"github.com/remogatto/prettytest"
)
// Start of setup
type testSuite struct {
prettytest.Suite
}
func TestRunner(t *testing.T) {
prettytest.Run(
t,
new(testSuite),
)
}
func (t *testSuite) BeforeAll() {
gin.SetMode(gin.ReleaseMode)
logger.SetLevel(logger.Disabled)
}
// Test the creation of a new task. A new task is created with a POST
// request to the endpoint.
func (t *testSuite) TestCreateTask() {
video, err := postTask("https://www.youtube.com/watch?v=AVIBLFl28vo")
if err != nil {
panic(err)
}
t.Equal("AVIBLFl28vo", video.ID)
}
// Test the response of a GET /tasks/:id requests.
func (t *testSuite) TestGetTask() {
video, err := postTask("https://www.youtube.com/watch?v=AVIBLFl28vo")
if err != nil {
panic(err)
}
// Create a new request
req, err := http.NewRequest("GET", "/task/"+video.ID, nil)
if err != nil {
panic(err)
}
// Create an http recorder
rr := httptest.NewRecorder()
// Set the context and call the handler
c, _ := gin.CreateTestContext(rr)
c.Request = req
getTask(c, video.ID)
// Read the response and assert it.
ts := new(task.Task)
if err := json.Unmarshal(rr.Body.Bytes(), &ts); err != nil {
panic(err)
}
t.Equal("AVIBLFl28vo", ts.ID)
t.Equal(task.StatusCompleted, ts.Status)
}
func postTask(ytUrl string) (*downloader.Video, error) {
// Set form values
form := url.Values{}
form.Add("url", ytUrl)
// Create a new request
req, err := http.NewRequest("POST", "/task", strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// Create an http recorder
rr := httptest.NewRecorder()
// Set the context and call the handler
c, _ := gin.CreateTestContext(rr)
c.Request = req
createTask(c)
// Read the response and assert it.
video := new(downloader.Video)
if err := json.Unmarshal(rr.Body.Bytes(), &video); err != nil {
return nil, err
}
return video, nil
}