testhub/server_integration_test.go

69 lines
1.8 KiB
Go
Raw Normal View History

2022-05-26 13:58:17 +02:00
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
2022-06-16 17:21:04 +02:00
"strings"
2022-05-26 13:58:17 +02:00
"git.andreafazzi.eu/andrea/testhub/models"
"git.andreafazzi.eu/andrea/testhub/store"
"github.com/remogatto/prettytest"
)
type integrationTestSuite struct {
prettytest.Suite
}
2022-06-16 17:21:04 +02:00
func (t *integrationTestSuite) TestCreateAndGetTest() {
2022-05-26 13:58:17 +02:00
server := NewTestHubCollectorServer(store.NewMemoryTestHubCollectorStore())
// POST a new question using a JSON payload
2022-06-16 17:21:04 +02:00
payload := `
{
"question": {"text": "Question 1"},
"answers": [
{"text": "Text of the answer 1", "correct": true},
{"text": "Text of the answer 2"},
{"text": "Text of the answer 3"},
{"text": "Text of the answer 4"}
]
}
`
request, _ := http.NewRequest(http.MethodPost, "/tests", strings.NewReader(payload))
response := httptest.NewRecorder()
2022-05-26 13:58:17 +02:00
2022-06-16 17:21:04 +02:00
server.ServeHTTP(response, request)
2022-05-26 13:58:17 +02:00
2022-06-16 17:21:04 +02:00
returnedTest := new(models.Test)
2022-05-26 13:58:17 +02:00
2022-06-16 17:21:04 +02:00
err := json.Unmarshal(response.Body.Bytes(), returnedTest)
2022-05-26 14:01:59 +02:00
if err != nil {
2022-06-16 17:21:04 +02:00
t.True(err == nil, err.Error())
2022-05-26 14:01:59 +02:00
}
2022-05-26 13:58:17 +02:00
2022-06-16 17:21:04 +02:00
t.Equal("Question 1", returnedTest.Question.Text)
t.Equal("Text of the answer 1", returnedTest.Answers[0].Text)
t.Equal("Text of the answer 1", returnedTest.Correct.Text)
t.True(returnedTest.ID != 0, "Test ID should not be 0")
t.True(returnedTest.Question.ID != "", "Question ID should not be empty")
t.True(returnedTest.Answers[0].ID != "", "Answer ID should not be empty")
request, _ = http.NewRequest(http.MethodGet, "/tests", nil)
response = httptest.NewRecorder()
2022-05-26 13:58:17 +02:00
server.ServeHTTP(response, request)
2022-06-16 17:21:04 +02:00
returnedTests := make([]*models.Test, 0)
err = json.Unmarshal(response.Body.Bytes(), &returnedTests)
if err != nil {
t.True(err == nil, err.Error())
}
t.True(len(returnedTests) == 1, "Length of returned tests should be 1")
t.Equal("Question 1", returnedTests[0].Question.Text)
2022-05-26 13:58:17 +02:00
}