youtube-dl-service/backend/main_test.go

101 lines
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/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),
)
}
// 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.
task := new(task.Task)
if err := json.Unmarshal(rr.Body.Bytes(), &task); err != nil {
panic(err)
}
t.Equal("AVIBLFl28vo", task.ID)
}
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
}