probo/pkg/store/file/exam_test.go

105 lines
2.5 KiB
Go
Raw Permalink Normal View History

2023-11-28 16:19:49 +01:00
package file
import (
"encoding/json"
"fmt"
"io"
"os"
2024-02-06 09:03:57 +01:00
"git.andreafazzi.eu/andrea/probo/pkg/models"
"git.andreafazzi.eu/andrea/probo/pkg/store"
2023-11-28 16:19:49 +01:00
"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)
2023-12-05 22:11:08 +01:00
participants := participantStore.Storer.FilterInGroup(g, map[string]string{"class": "1 D LIN"})
quizzes := quizStore.Storer.FilterInCollection(c, map[string]string{"tags": "#tag1"})
2023-11-28 16:19:49 +01:00
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
}