probo/store/file/exam_test.go

111 lines
2.5 KiB
Go

package file
import (
"encoding/json"
"fmt"
"io"
"os"
"git.andreafazzi.eu/andrea/probo/models"
"git.andreafazzi.eu/andrea/probo/store"
"github.com/remogatto/prettytest"
)
type examTestSuite struct {
prettytest.Suite
}
func (t *examTestSuite) TestCreate() {
participantStore, err := NewParticipantFileStore(
&FileStoreConfig[*models.Participant, *store.ParticipantStore]{
FilePathConfig: FilePathConfig{"testdata/exams/participants", "participant", ".json"},
IndexDirFunc: DefaultIndexDirFunc[*models.Participant, *store.ParticipantStore],
CreateEntityFunc: func() *models.Participant {
return &models.Participant{
Attributes: make(map[string]string),
}
},
},
)
t.Nil(err)
quizStore, err := NewQuizFileStore(
&FileStoreConfig[*models.Quiz, *store.QuizStore]{
FilePathConfig: FilePathConfig{"testdata/exams/quizzes", "quiz", ".md"},
IndexDirFunc: DefaultQuizIndexDirFunc,
},
)
t.Nil(err)
if !t.Failed() {
t.Equal(3, len(participantStore.ReadAll()))
examStore, err := NewDefaultExamFileStore()
t.Nil(err)
if !t.Failed() {
g := new(models.Group)
c := new(models.Collection)
participants := participantStore.Storer.FilterInGroup(g, &models.ParticipantFilter{
Attributes: map[string]string{"class": "1 D LIN"},
})
quizzes := quizStore.Storer.FilterInCollection(c, &models.Filter{
Tags: []*models.Tag{
{Name: "#tag1"},
},
})
for _, p := range participants {
e := new(models.Exam)
e.Participant = p
e.Quizzes = quizzes
_, err = examStore.Create(e)
t.Nil(err)
defer os.Remove(examStore.GetPath(e))
examFromDisk, err := readExamFromJSON(e.GetID())
t.Nil(err)
if !t.Failed() {
t.Not(t.Nil(examFromDisk.Participant))
if !t.Failed() {
t.Equal("Smith", examFromDisk.Participant.Lastname)
t.Equal(2, len(examFromDisk.Quizzes))
}
}
}
}
}
}
func readExamFromJSON(examID string) (*models.Exam, error) {
// Build the path to the JSON file
jsonPath := fmt.Sprintf("testdata/exams/exam_%s.json", examID)
// Open the JSON file
file, err := os.Open(jsonPath)
if err != nil {
return nil, fmt.Errorf("failed to open JSON file: %w", err)
}
defer file.Close()
// Read the JSON data from the file
jsonData, err := io.ReadAll(file)
if err != nil {
return nil, fmt.Errorf("failed to read JSON data: %w", err)
}
// Unmarshal the JSON data into an Exam object
var exam models.Exam
if err := json.Unmarshal(jsonData, &exam); err != nil {
return nil, fmt.Errorf("failed to parse JSON data: %w", err)
}
return &exam, nil
}