package main import ( "encoding/json" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "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" ) var config *Config // 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.DebugLevel) config = new(Config) err := ReadConfig("config.yaml", config) if err != nil { panic(err) } } // 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=zGDzdps75ns") if err != nil { panic(err) } t.Equal("zGDzdps75ns", video.ID) } // Test the response of a GET /tasks/:id requests. func (t *testSuite) TestGetTask() { video, err := postTask("https://www.youtube.com/watch?v=zGDzdps75ns") if err != nil { panic(err) } timer := time.NewTimer(time.Second * 10) <-timer.C // 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("zGDzdps75ns", video.ID) t.Equal(task.StatusCompleted, ts.Status) t.Equal(100.0, ts.Percentage) } func (t *testSuite) TestPostLogin() { // Set form values form := url.Values{} form.Add("password", "secret") req, err := http.NewRequest("POST", "/login", strings.NewReader((form.Encode()))) if err != nil { panic(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 err = postLogin(c, config) t.Nil(err) } 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 }