youtube-dl-service/backend/main_test.go

108 lines
2.2 KiB
Go
Raw Normal View History

2021-11-12 08:54:02 +01:00
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
2021-12-07 13:49:08 +01:00
"git.andreafazzi.eu/andrea/youtube-dl-service/downloader"
2021-12-07 14:11:10 +01:00
"git.andreafazzi.eu/andrea/youtube-dl-service/logger"
2021-12-02 13:56:39 +01:00
"git.andreafazzi.eu/andrea/youtube-dl-service/task"
2021-11-12 08:54:02 +01:00
"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),
)
}
2021-12-10 12:06:04 +01:00
func (t *testSuite) BeforeAll() {
gin.SetMode(gin.ReleaseMode)
logger.SetLevel(logger.Disabled)
}
2021-11-12 08:54:02 +01:00
// Test the creation of a new task. A new task is created with a POST
// request to the endpoint.
func (t *testSuite) TestCreateTask() {
2021-12-02 13:56:39 +01:00
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)
}
2021-12-07 13:49:08 +01:00
func postTask(ytUrl string) (*downloader.Video, error) {
2021-11-12 08:54:02 +01:00
// Set form values
form := url.Values{}
2021-12-02 13:56:39 +01:00
form.Add("url", ytUrl)
2021-11-12 08:54:02 +01:00
// Create a new request
req, err := http.NewRequest("POST", "/task", strings.NewReader(form.Encode()))
if err != nil {
2021-12-02 13:56:39 +01:00
return nil, err
2021-11-12 08:54:02 +01:00
}
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.
2021-12-07 13:49:08 +01:00
video := new(downloader.Video)
2021-11-12 08:54:02 +01:00
2021-12-02 13:56:39 +01:00
if err := json.Unmarshal(rr.Body.Bytes(), &video); err != nil {
return nil, err
2021-11-12 08:54:02 +01:00
}
2021-12-02 13:56:39 +01:00
return video, nil
2021-11-12 08:54:02 +01:00
}