culto

Repositório culto
git clone git://git.sivaldodavi.com/culto.git
Log | Files | Refs | README

app_test.go (15163B)


      1 package app
      2 
      3 import (
      4 	"encoding/json"
      5 	"fmt"
      6 	"os"
      7 	"path/filepath"
      8 	"strings"
      9 	"testing"
     10 	"time"
     11 
     12 	"culto/internal/culto"
     13 	tea "github.com/charmbracelet/bubbletea"
     14 )
     15 
     16 func TestMainMenuAndLiturgiaNavigation(t *testing.T) {
     17 	m := New(culto.Config{}).(*model)
     18 	if got := m.View(); !strings.Contains(got, "CULTO") || !strings.Contains(got, "Liturgia") {
     19 		t.Fatalf("menu inicial inesperado: %s", got)
     20 	}
     21 
     22 	m.activate("liturgia")
     23 	if m.screen != menuScreen || len(m.stack) != 1 {
     24 		t.Fatal("liturgia não abriu como submenu")
     25 	}
     26 	m.activate("text:ORAÇÃO INICIAL")
     27 	if m.screen != previewScreen || !strings.Contains(m.content, "ORAÇÃO INICIAL") {
     28 		t.Fatal("item litúrgico não abriu a visualização")
     29 	}
     30 	m.Update(tea.KeyMsg{Type: tea.KeyEsc})
     31 	if m.screen != menuScreen || m.menu.Title != "Liturgia · Esc volta" {
     32 		t.Fatal("Esc não voltou ao submenu de liturgia")
     33 	}
     34 	m.Update(tea.KeyMsg{Type: tea.KeyEsc})
     35 	if m.menu.Title != "" || len(m.stack) != 0 {
     36 		t.Fatal("Esc não voltou ao menu principal")
     37 	}
     38 }
     39 
     40 func TestMainMenuOmitsDuplicateActionsAndLiturgiaAgenda(t *testing.T) {
     41 	agendaCount := 0
     42 	for _, item := range mainItems() {
     43 		entry := item.(menuItem)
     44 		if entry.action == "clear" || entry.action == "quit" {
     45 			t.Fatalf("ação redundante na lista inicial: %#v", entry)
     46 		}
     47 		if entry.action == "agenda" {
     48 			agendaCount++
     49 		}
     50 	}
     51 	if agendaCount != 1 {
     52 		t.Fatalf("agenda deve aparecer uma vez no menu inicial; apareceu %d vezes", agendaCount)
     53 	}
     54 	m := New(culto.Config{}).(*model)
     55 	m.activate("liturgia")
     56 	for _, item := range m.menu.Items() {
     57 		if entry := item.(menuItem); entry.action == "agenda" {
     58 			t.Fatal("agenda aparece duplicada dentro de Liturgia")
     59 		}
     60 	}
     61 }
     62 
     63 func TestSongEditorContentKeepsLyricsAndRemovesOnlyItsTitle(t *testing.T) {
     64 	title := "Cântico de teste"
     65 	original := songEditorText(title, []string{"Primeira estrofe", "Segunda estrofe"})
     66 	want := "Primeira estrofe\n\nSegunda estrofe"
     67 	if got := songEditorLyrics(original, title); got != want {
     68 		t.Fatalf("letra extraída = %q, esperado %q", got, want)
     69 	}
     70 
     71 	content := "# Cântico de teste\n\n# Cabeçalho da estrofe\nletra"
     72 	if got := songEditorLyrics(content, title); got != "# Cabeçalho da estrofe\nletra" {
     73 		t.Fatalf("cabeçalho Markdown da letra foi removido: %q", got)
     74 	}
     75 }
     76 
     77 func TestSongEditorStartsWithTitleAndEmptyLyrics(t *testing.T) {
     78 	if got, want := songEditorText("Nova música", nil), "# Nova música\n\n"; got != want {
     79 		t.Fatalf("conteúdo inicial = %q, esperado %q", got, want)
     80 	}
     81 }
     82 
     83 func TestFinishEditorSavesLyricsAndReturnsToSongList(t *testing.T) {
     84 	title := "Cântico existente"
     85 	musicFile := filepath.Join(t.TempDir(), "musicas.json")
     86 	if err := culto.SaveSong(musicFile, title, "Letra antiga"); err != nil {
     87 		t.Fatal(err)
     88 	}
     89 
     90 	m := New(culto.Config{MusicFile: musicFile}).(*model)
     91 	m.openSongs()
     92 	m.openSong(title)
     93 
     94 	original := songEditorText(title, []string{"Letra antiga"})
     95 	edited := songEditorText(title, []string{"Primeira estrofe", "Segunda estrofe"})
     96 	editFile := filepath.Join(t.TempDir(), "culto.md")
     97 	if err := os.WriteFile(editFile, []byte(edited), 0o600); err != nil {
     98 		t.Fatal(err)
     99 	}
    100 	m.finishEditor(editorFinishedMsg{
    101 		title: title, path: editFile, original: original,
    102 	})
    103 
    104 	if m.screen != menuScreen || m.menu.Title != "Músicas · Esc volta" {
    105 		t.Fatal("após editar, a aplicação não voltou à lista de músicas")
    106 	}
    107 	songs, err := culto.LoadSongs(musicFile)
    108 	if err != nil {
    109 		t.Fatal(err)
    110 	}
    111 	if got := songs["Cânticos Espirituais"][title]; len(got) != 2 ||
    112 		got[0] != "Primeira estrofe" || got[1] != "Segunda estrofe" {
    113 		t.Fatalf("letra editada não foi salva: %#v", got)
    114 	}
    115 	if _, err := os.Stat(editFile); !os.IsNotExist(err) {
    116 		t.Fatal("arquivo temporário do editor não foi removido")
    117 	}
    118 }
    119 
    120 func TestSongEditorChangesReachProjectionBeforeEditorCloses(t *testing.T) {
    121 	dir := t.TempDir()
    122 	xdotool := filepath.Join(dir, "xdotool")
    123 	script := "#!/bin/sh\n" +
    124 		"if [ \"$1\" = search ]; then printf '4242\\n'; fi\n"
    125 	if err := os.WriteFile(xdotool, []byte(script), 0o755); err != nil {
    126 		t.Fatal(err)
    127 	}
    128 	t.Setenv("PATH", dir)
    129 
    130 	title := "Cântico ao vivo"
    131 	original := songEditorText(title, []string{"Letra antiga"})
    132 	liveFile := filepath.Join(dir, "live.md")
    133 	sentFile := filepath.Join(dir, "slides")
    134 	if err := os.WriteFile(liveFile, []byte(original), 0o600); err != nil {
    135 		t.Fatal(err)
    136 	}
    137 	stop := watchSongProjection(culto.Config{SentFile: sentFile}, liveFile, title, original)
    138 	defer stop()
    139 
    140 	edited := songEditorText(title, []string{"Primeira estrofe", "Segunda estrofe"})
    141 	if err := os.WriteFile(liveFile, []byte(edited), 0o600); err != nil {
    142 		t.Fatal(err)
    143 	}
    144 
    145 	deadline := time.Now().Add(3 * time.Second)
    146 	for time.Now().Before(deadline) {
    147 		projected, err := os.ReadFile(sentFile)
    148 		if err == nil && strings.Contains(string(projected), "SEGUNDA ESTROFE") {
    149 			if got, want := string(projected), "PRIMEIRA ESTROFE\n\nSEGUNDA ESTROFE\n"; got != want {
    150 				t.Fatalf("letra projetada = %q, esperado %q", got, want)
    151 			}
    152 			return
    153 		}
    154 		time.Sleep(20 * time.Millisecond)
    155 	}
    156 	t.Fatal("a letra editada não chegou à projeção antes de fechar o editor")
    157 }
    158 
    159 func TestDiscardedSongEditRestoresProjection(t *testing.T) {
    160 	dir := t.TempDir()
    161 	xdotool := filepath.Join(dir, "xdotool")
    162 	if err := os.WriteFile(xdotool, []byte("#!/bin/sh\nif [ \"$1\" = search ]; then printf '4242\\n'; fi\n"), 0o755); err != nil {
    163 		t.Fatal(err)
    164 	}
    165 	t.Setenv("PATH", dir)
    166 
    167 	title := "Cântico descartado"
    168 	original := songEditorText(title, []string{"Letra original"})
    169 	editorFile := filepath.Join(dir, "editor.md")
    170 	liveFile := filepath.Join(dir, "live.md")
    171 	sentFile := filepath.Join(dir, "slides")
    172 	if err := os.WriteFile(editorFile, []byte(original), 0o600); err != nil {
    173 		t.Fatal(err)
    174 	}
    175 	if err := os.WriteFile(liveFile, []byte(songEditorText(title, []string{"Letra temporária"})), 0o600); err != nil {
    176 		t.Fatal(err)
    177 	}
    178 
    179 	m := New(culto.Config{SentFile: sentFile}).(*model)
    180 	m.finishEditor(editorFinishedMsg{
    181 		title: title, path: editorFile, livePath: liveFile, original: original,
    182 	})
    183 
    184 	projected, err := os.ReadFile(sentFile)
    185 	if err != nil {
    186 		t.Fatal(err)
    187 	}
    188 	if got, want := string(projected), "LETRA ORIGINAL\n"; got != want {
    189 		t.Fatalf("projeção após descartar = %q, esperado %q", got, want)
    190 	}
    191 	if m.status != "Edição descartada; projeção restaurada." {
    192 		t.Fatalf("status após descartar: %q", m.status)
    193 	}
    194 }
    195 
    196 func TestSongListHasAddAndBackActions(t *testing.T) {
    197 	m := New(culto.Config{MusicFile: t.TempDir() + "/missing.json"}).(*model)
    198 	m.openSongs()
    199 	items := m.menu.Items()
    200 	if len(items) < 2 {
    201 		t.Fatal("lista de músicas sem ações básicas")
    202 	}
    203 	add, ok := items[0].(menuItem)
    204 	if !ok || add.action != "song:add" {
    205 		t.Fatalf("primeiro item não é adicionar: %#v", items[0])
    206 	}
    207 	back, ok := items[1].(menuItem)
    208 	if !ok || back.action != "back" {
    209 		t.Fatalf("segundo item não é voltar: %#v", items[1])
    210 	}
    211 }
    212 
    213 func TestSongCanBeRenamedFromPreview(t *testing.T) {
    214 	musicFile := filepath.Join(t.TempDir(), "musicas.json")
    215 	if err := culto.SaveSong(musicFile, "Título antigo", "Letra preservada"); err != nil {
    216 		t.Fatal(err)
    217 	}
    218 	m := New(culto.Config{MusicFile: musicFile}).(*model)
    219 	m.openSongs()
    220 	m.openSong("Título antigo")
    221 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'t'}})
    222 	m.input.SetValue("Título novo")
    223 	m.Update(tea.KeyMsg{Type: tea.KeyEnter})
    224 
    225 	songs, err := culto.LoadSongs(musicFile)
    226 	if err != nil {
    227 		t.Fatal(err)
    228 	}
    229 	if got := songs["Cânticos Espirituais"]["Título novo"]; len(got) != 1 || got[0] != "Letra preservada" {
    230 		t.Fatalf("música renomeada incorretamente: %#v", got)
    231 	}
    232 	if m.screen != menuScreen || m.menu.Index() < 2 {
    233 		t.Fatal("após renomear, a lista não selecionou a música atualizada")
    234 	}
    235 }
    236 
    237 func TestSongDeletionRequiresExplicitConfirmation(t *testing.T) {
    238 	musicFile := filepath.Join(t.TempDir(), "musicas.json")
    239 	if err := culto.SaveSong(musicFile, "Título a remover", "Letra"); err != nil {
    240 		t.Fatal(err)
    241 	}
    242 	m := New(culto.Config{MusicFile: musicFile}).(*model)
    243 	m.openSongs()
    244 	m.openSong("Título a remover")
    245 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'d'}})
    246 	m.input.SetValue("não")
    247 	m.Update(tea.KeyMsg{Type: tea.KeyEnter})
    248 	if m.screen != previewScreen || m.status != "Remoção cancelada." {
    249 		t.Fatal("confirmação incorreta não cancelou a remoção")
    250 	}
    251 	songs, err := culto.LoadSongs(musicFile)
    252 	if err != nil {
    253 		t.Fatal(err)
    254 	}
    255 	if len(culto.SongTitles(songs)) != 1 {
    256 		t.Fatal("música foi removida sem confirmação correta")
    257 	}
    258 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'d'}})
    259 	m.input.SetValue("REMOVER")
    260 	m.Update(tea.KeyMsg{Type: tea.KeyEnter})
    261 	songs, err = culto.LoadSongs(musicFile)
    262 	if err != nil {
    263 		t.Fatal(err)
    264 	}
    265 	if len(culto.SongTitles(songs)) != 0 {
    266 		t.Fatalf("música ainda existe depois de confirmada a remoção: %#v", songs)
    267 	}
    268 	if m.screen != menuScreen {
    269 		t.Fatal("após remover, a aplicação não voltou à lista de músicas")
    270 	}
    271 }
    272 
    273 func TestSlideJumpStaysOnPreviewAndSendsNumberToSent(t *testing.T) {
    274 	dir := t.TempDir()
    275 	argsFile := filepath.Join(dir, "xdotool-args")
    276 	xdotool := filepath.Join(dir, "xdotool")
    277 	script := "#!/bin/sh\n" +
    278 		"if [ \"$1\" = search ]; then printf '4242\\n'; exit 0; fi\n" +
    279 		"printf '%s\\n' \"$@\" > \"$CULTO_TEST_XDOTOOL_ARGS\"\n"
    280 	if err := os.WriteFile(xdotool, []byte(script), 0o755); err != nil {
    281 		t.Fatal(err)
    282 	}
    283 	t.Setenv("PATH", dir)
    284 	t.Setenv("CULTO_TEST_XDOTOOL_ARGS", argsFile)
    285 
    286 	m := New(culto.Config{}).(*model)
    287 	m.showPreview("HINO\n\nESTROFE")
    288 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'g'}})
    289 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'1'}})
    290 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'2'}})
    291 	if m.screen != previewScreen || !m.jumpActive || m.jumpDigits != "12" {
    292 		t.Fatal("entrada do número trocou a tela de projeção")
    293 	}
    294 	m.Update(tea.KeyMsg{Type: tea.KeyEnter})
    295 	if m.screen != previewScreen || m.jumpActive {
    296 		t.Fatal("após o salto, a tela de projeção não foi mantida")
    297 	}
    298 	got, err := os.ReadFile(argsFile)
    299 	if err != nil {
    300 		t.Fatal(err)
    301 	}
    302 	want := "key\n--window\n4242\n--clearmodifiers\ng\n1\n2\nReturn\n"
    303 	if string(got) != want {
    304 		t.Fatalf("sequência enviada ao sent:\n%s\nesperado:\n%s", got, want)
    305 	}
    306 }
    307 
    308 func TestBibleReferenceCanReuseLastBookAndChapter(t *testing.T) {
    309 	bibleFile := filepath.Join(t.TempDir(), "biblia.json")
    310 	data, err := json.Marshal([]culto.BibleBook{{
    311 		Name:     "Romanos",
    312 		Abbrev:   "Rm",
    313 		Chapters: [][]string{{"Versículo um.", "Versículo dois.", "Versículo três."}},
    314 	}})
    315 	if err != nil {
    316 		t.Fatal(err)
    317 	}
    318 	if err := os.WriteFile(bibleFile, data, 0o600); err != nil {
    319 		t.Fatal(err)
    320 	}
    321 	m := New(culto.Config{BibleFile: bibleFile}).(*model)
    322 	m.readBible("Romanos 1", false)
    323 	if m.lastBibleBase != "Romanos 1" || !m.previewBible {
    324 		t.Fatalf("contexto bíblico não foi armazenado: base=%q preview=%v", m.lastBibleBase, m.previewBible)
    325 	}
    326 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'v'}})
    327 	if !strings.Contains(m.inputPrompt, "Romanos 1") {
    328 		t.Fatalf("prompt não informa o capítulo atual: %q", m.inputPrompt)
    329 	}
    330 	m.input.SetValue("2")
    331 	m.Update(tea.KeyMsg{Type: tea.KeyEnter})
    332 	if m.screen != previewScreen || !strings.Contains(m.content, "Romanos 1:2") ||
    333 		!strings.Contains(m.content, "2. Versículo dois.") {
    334 		t.Fatalf("referência relativa não selecionou o versículo correto: %q", m.content)
    335 	}
    336 	if got := resolveBibleReference("10-12", "Romanos 1"); got != "Romanos 1:10-12" {
    337 		t.Fatalf("intervalo relativo resolvido como %q", got)
    338 	}
    339 }
    340 
    341 func TestPreviewErrorsCannotBeProjected(t *testing.T) {
    342 	m := New(culto.Config{}).(*model)
    343 	m.showError(fmt.Errorf("erro de teste"))
    344 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'p'}})
    345 	if m.previewProjectable || m.status != "Esta mensagem não pode ser projetada." {
    346 		t.Fatalf("erro ficou projetável: projectable=%v status=%q", m.previewProjectable, m.status)
    347 	}
    348 }
    349 
    350 func TestSlideJumpCanBeCancelledWithoutLeavingPreview(t *testing.T) {
    351 	m := New(culto.Config{}).(*model)
    352 	m.showPreview("SLIDE")
    353 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'g'}})
    354 	m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'3'}})
    355 	m.Update(tea.KeyMsg{Type: tea.KeyEsc})
    356 	if m.screen != previewScreen || m.jumpActive || m.jumpDigits != "" {
    357 		t.Fatal("cancelar o salto alterou a tela ou manteve o número digitado")
    358 	}
    359 }
    360 
    361 func TestPreviewArrowKeysMoveSentSlideWithoutLeavingPreview(t *testing.T) {
    362 	dir := t.TempDir()
    363 	argsFile := filepath.Join(dir, "xdotool-args")
    364 	xdotool := filepath.Join(dir, "xdotool")
    365 	script := "#!/bin/sh\n" +
    366 		"if [ \"$1\" = search ]; then printf '4242\\n'; exit 0; fi\n" +
    367 		"printf '%s\\n' \"$@\" >> \"$CULTO_TEST_XDOTOOL_ARGS\"\n"
    368 	if err := os.WriteFile(xdotool, []byte(script), 0o755); err != nil {
    369 		t.Fatal(err)
    370 	}
    371 	t.Setenv("PATH", dir)
    372 	t.Setenv("CULTO_TEST_XDOTOOL_ARGS", argsFile)
    373 
    374 	m := New(culto.Config{}).(*model)
    375 	m.showPreview("HINO\n\nESTROFE")
    376 	m.Update(tea.KeyMsg{Type: tea.KeyLeft})
    377 	if m.screen != previewScreen || m.status != "Slide anterior enviado ao sent." {
    378 		t.Fatalf("atalho de slide anterior inesperado: tela=%v status=%q", m.screen, m.status)
    379 	}
    380 	m.Update(tea.KeyMsg{Type: tea.KeyRight})
    381 	if m.screen != previewScreen || m.status != "Slide seguinte enviado ao sent." {
    382 		t.Fatalf("atalho de slide seguinte inesperado: tela=%v status=%q", m.screen, m.status)
    383 	}
    384 
    385 	got, err := os.ReadFile(argsFile)
    386 	if err != nil {
    387 		t.Fatal(err)
    388 	}
    389 	want := "key\n--window\n4242\n--clearmodifiers\nLeft\n" +
    390 		"key\n--window\n4242\n--clearmodifiers\nRight\n"
    391 	if string(got) != want {
    392 		t.Fatalf("teclas enviadas ao sent:\n%s\nesperado:\n%s", got, want)
    393 	}
    394 }
    395 
    396 func TestCtrlLClearsProjectionWithoutLeavingCurrentScreen(t *testing.T) {
    397 	for _, screenName := range []string{"menu", "input", "preview"} {
    398 		t.Run(screenName, func(t *testing.T) {
    399 			dir := t.TempDir()
    400 			xdotool := filepath.Join(dir, "xdotool")
    401 			script := "#!/bin/sh\n" +
    402 				"if [ \"$1\" = search ]; then printf '4242\\n'; exit 0; fi\n" +
    403 				"exit 0\n"
    404 			if err := os.WriteFile(xdotool, []byte(script), 0o755); err != nil {
    405 				t.Fatal(err)
    406 			}
    407 			t.Setenv("PATH", dir)
    408 
    409 			sentFile := filepath.Join(dir, "sent-slides")
    410 			if err := os.WriteFile(sentFile, []byte("SLIDE 1\n"), 0o600); err != nil {
    411 				t.Fatal(err)
    412 			}
    413 			m := New(culto.Config{SentFile: sentFile}).(*model)
    414 			switch screenName {
    415 			case "input":
    416 				m.ask("Buscar", "search")
    417 				m.input.SetValue("termo")
    418 			case "preview":
    419 				m.showPreview("Conteúdo atual")
    420 			}
    421 			beforeScreen := m.screen
    422 
    423 			m.Update(tea.KeyMsg{Type: tea.KeyCtrlL})
    424 
    425 			if m.screen != beforeScreen {
    426 				t.Fatalf("atalho mudou de tela: %v -> %v", beforeScreen, m.screen)
    427 			}
    428 			if m.status != "Projeção limpa." {
    429 				t.Fatalf("status inesperado: %q", m.status)
    430 			}
    431 			got, err := os.ReadFile(sentFile)
    432 			if err != nil {
    433 				t.Fatal(err)
    434 			}
    435 			if string(got) != " \n" {
    436 				t.Fatalf("arquivo da projeção não foi limpo: %q", got)
    437 			}
    438 			if screenName == "input" && m.input.Value() != "termo" {
    439 				t.Fatalf("texto do campo foi perdido: %q", m.input.Value())
    440 			}
    441 			if screenName == "preview" && m.content != "Conteúdo atual" {
    442 				t.Fatalf("conteúdo da tela foi perdido: %q", m.content)
    443 			}
    444 		})
    445 	}
    446 }