testhub/server_test.go
2022-06-23 11:10:41 +02:00

90 lines
1.9 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"git.andreafazzi.eu/andrea/testhub/client"
"git.andreafazzi.eu/andrea/testhub/logger"
"git.andreafazzi.eu/andrea/testhub/models"
"github.com/remogatto/prettytest"
)
type testSuite struct {
prettytest.Suite
}
type StubTestHubCollectorStore struct {
tests []*models.Quiz
}
func (store *StubTestHubCollectorStore) CreateQuiz(test *client.CreateQuizRequest) *models.Quiz {
return nil
}
func (store *StubTestHubCollectorStore) ReadAllQuizzes() ([]*models.Quiz, error) {
return store.tests, nil
}
func TestRunner(t *testing.T) {
prettytest.Run(
t,
new(testSuite),
new(integrationTestSuite),
)
}
func (t *testSuite) BeforeAll() {
logger.SetLevel(logger.Disabled)
}
func (t *testSuite) TestGETQuestions() {
expectedResult := &client.QuizReadAllResponse{
Status: "success",
Content: []*models.Quiz{
{
Question: &models.Question{ID: "1", Text: "Question 1"},
Answers: []*models.Answer{{}, {}, {}},
},
},
}
store := &StubTestHubCollectorStore{[]*models.Quiz{
{
Question: &models.Question{ID: "1", Text: "Question 1"},
Answers: []*models.Answer{{}, {}, {}},
},
}}
server := NewQuizHubCollectorServer(store)
request, _ := http.NewRequest(http.MethodGet, "/quizzes", nil)
response := httptest.NewRecorder()
server.ServeHTTP(response, request)
result := getResponse(response.Body)
t.True(result.Status == expectedResult.Status)
t.True(testsAreEqual(result, expectedResult))
t.Equal(http.StatusOK, response.Code)
}
func getResponse(body io.Reader) (response *client.QuizReadAllResponse) {
err := json.NewDecoder(body).Decode(&response)
if err != nil {
panic(fmt.Errorf("Unable to parse response from server %q into slice of Test, '%v'", body, err))
}
return
}
func testsAreEqual(got, want *client.QuizReadAllResponse) bool {
return reflect.DeepEqual(got, want)
}