testhub/main_test.go
2022-05-26 09:53:08 +02:00

68 lines
1.4 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"git.andreafazzi.eu/andrea/testhub/models"
"github.com/remogatto/prettytest"
)
// Start of setup
type testSuite struct {
prettytest.Suite
}
type StubTestHubCollectorStore struct{}
func (store *StubTestHubCollectorStore) CreateQuestion(question *models.Question) *models.Question {
return nil
}
func (store *StubTestHubCollectorStore) GetQuestions() []*models.Question {
return []*models.Question{{Text: "Domanda 1"}}
}
func TestRunner(t *testing.T) {
prettytest.Run(
t,
new(testSuite),
)
}
func (t *testSuite) TestGETQuestions() {
expectedResult := []*models.Question{{Text: "Domanda 1"}}
store := &StubTestHubCollectorStore{}
server := NewTestHubCollectorServer(store)
request, _ := http.NewRequest(http.MethodGet, "/questions", nil)
response := httptest.NewRecorder()
server.ServeHTTP(response, request)
result := getQuestionsFromResponse(response.Body)
t.True(questionsAreEqual(expectedResult, result))
t.Equal(http.StatusOK, response.Code)
}
func getQuestionsFromResponse(body io.Reader) (questions []*models.Question) {
err := json.NewDecoder(body).Decode(&questions)
if err != nil {
panic(fmt.Errorf("Unable to parse response from server %q into slice of Question, '%v'", body, err))
}
return
}
func questionsAreEqual(got, want []*models.Question) bool {
return reflect.DeepEqual(got, want)
}