testhub/server_test.go

87 lines
1.7 KiB
Go
Raw Normal View History

2022-05-25 12:04:53 +02:00
package main
import (
2022-05-25 18:09:54 +02:00
"encoding/json"
"fmt"
"io"
2022-05-25 12:04:53 +02:00
"net/http"
"net/http/httptest"
2022-05-25 18:09:54 +02:00
"reflect"
2022-05-25 12:04:53 +02:00
"testing"
2022-05-26 12:30:53 +02:00
"git.andreafazzi.eu/andrea/testhub/logger"
2022-05-25 19:24:12 +02:00
"git.andreafazzi.eu/andrea/testhub/models"
2022-05-26 12:30:53 +02:00
"github.com/google/uuid"
2022-05-25 12:04:53 +02:00
"github.com/remogatto/prettytest"
)
type testSuite struct {
prettytest.Suite
}
2022-05-26 13:58:17 +02:00
type StubTestHubCollectorStore struct {
questions []*models.Question
}
2022-05-25 12:04:53 +02:00
2022-05-26 09:53:08 +02:00
func (store *StubTestHubCollectorStore) CreateQuestion(question *models.Question) *models.Question {
return nil
2022-05-25 12:04:53 +02:00
}
2022-05-26 09:53:08 +02:00
func (store *StubTestHubCollectorStore) GetQuestions() []*models.Question {
2022-05-26 13:58:17 +02:00
return store.questions
2022-05-25 18:09:54 +02:00
}
2022-05-25 12:04:53 +02:00
func TestRunner(t *testing.T) {
prettytest.Run(
t,
new(testSuite),
2022-05-26 13:58:17 +02:00
new(integrationTestSuite),
2022-05-25 12:04:53 +02:00
)
}
2022-05-26 12:30:53 +02:00
func (t *testSuite) BeforeAll() {
logger.SetLevel(logger.Disabled)
}
2022-05-26 07:59:55 +02:00
func (t *testSuite) TestGETQuestions() {
2022-05-26 12:30:53 +02:00
expectedResult := []*models.Question{
{
Text: "Domanda 1",
AnswerIDs: []uuid.UUID{{}},
},
}
2022-05-25 18:09:54 +02:00
2022-05-26 13:58:17 +02:00
store := &StubTestHubCollectorStore{[]*models.Question{
{
Text: "Domanda 1",
AnswerIDs: []uuid.UUID{{}},
},
}}
2022-05-25 18:09:54 +02:00
2022-05-26 09:53:08 +02:00
server := NewTestHubCollectorServer(store)
2022-05-25 18:09:54 +02:00
2022-05-26 09:53:08 +02:00
request, _ := http.NewRequest(http.MethodGet, "/questions", nil)
2022-05-25 18:09:54 +02:00
response := httptest.NewRecorder()
server.ServeHTTP(response, request)
2022-05-26 09:53:08 +02:00
result := getQuestionsFromResponse(response.Body)
2022-05-25 18:09:54 +02:00
2022-05-26 09:53:08 +02:00
t.True(questionsAreEqual(expectedResult, result))
2022-05-25 18:09:54 +02:00
t.Equal(http.StatusOK, response.Code)
}
2022-05-26 09:53:08 +02:00
func getQuestionsFromResponse(body io.Reader) (questions []*models.Question) {
err := json.NewDecoder(body).Decode(&questions)
2022-05-25 18:09:54 +02:00
if err != nil {
2022-05-26 09:53:08 +02:00
panic(fmt.Errorf("Unable to parse response from server %q into slice of Question, '%v'", body, err))
2022-05-25 18:09:54 +02:00
}
return
}
2022-05-26 09:53:08 +02:00
func questionsAreEqual(got, want []*models.Question) bool {
2022-05-25 18:09:54 +02:00
return reflect.DeepEqual(got, want)
}