Files
sm-quizzes-plugin/classes/importer_test.go

58 lines
3.1 KiB
Go

package classes_test
import (
"os"
"strings"
"testing"
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
)
func TestParseImportSample(t *testing.T) {
raw, err := os.ReadFile("../testdata/quiz.json")
if err != nil {
t.Fatal(err)
}
doc, err := classes.ParseImport(raw)
if err != nil {
t.Fatalf("ParseImport: %v", err)
}
if doc.Slug != "bezpieczenstwo-pojecia" {
t.Errorf("slug = %q, want it built from the title", doc.Slug)
}
if len(doc.Questions) != 3 || *doc.RoundSize != 5 || *doc.PassingScore != 60 {
t.Errorf("doc = %+v", doc)
}
}
func TestParseImportRejects(t *testing.T) {
cases := map[string]string{
`not json`: "invalid JSON",
`{"title":"A","questions":[{"text":"Q","type":"self_check"}],"extra":1}`: "unknown field",
`{"questions":[{"text":"Q","type":"self_check"}]}`: "title is required",
`{"title":"A","questions":[]}`: "questions must not be empty",
`{"title":"A","passing_score":101,"questions":[{"text":"Q","type":"self_check"}]}`: "passing_score",
`{"title":"A","round_size":0,"questions":[{"text":"Q","type":"self_check"}]}`: "round_size",
`{"title":"A","time_limit_seconds":0,"questions":[{"text":"Q","type":"self_check"}]}`: "time_limit_seconds",
`{"title":"A","questions":[{"text":"","type":"self_check"}]}`: "questions[0].text",
`{"title":"A","questions":[{"text":"Q","type":"essay"}]}`: "questions[0].type",
`{"title":"A","questions":[{"text":"Q","type":"self_check","points":-1}]}`: "points",
`{"title":"A","questions":[{"text":"Q","type":"self_check","answers":[{"text":"x"}]}]}`: "self_check question has no answers",
`{"title":"A","questions":[{"text":"Q","type":"single","answers":[{"text":"x","is_correct":true}]}]}`: "single question",
`{"title":"A","questions":[{"text":"Q","type":"single","answers":[{"text":"x"},{"text":"y"}]}]}`: "single question",
`{"title":"A","questions":[{"text":"Q","type":"multiple","answers":[{"text":"x"},{"text":"y"}]}]}`: "multiple question",
`{"title":"A","questions":[{"text":"Q","type":"multiple","answers":[{"text":"","is_correct":true},{"text":"y"}]}]}`: "answers[0].text",
`{"title":"!!!","questions":[{"text":"Q","type":"self_check"}]}`: "slug is empty",
}
for raw, want := range cases {
_, err := classes.ParseImport([]byte(raw))
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("ParseImport(%s) = %v, want an error with %q", raw, err, want)
}
}
doc, err := classes.ParseImport([]byte(`{"title":"Ignored","slug":"Mój Slug","questions":[{"text":"Q","type":"self_check"}]}`))
if err != nil || doc.Slug != "moj-slug" {
t.Errorf("explicit slug = %v %v, want moj-slug", doc, err)
}
}