sub-cli/internal/format/srt/generator_test.go
2025-04-23 19:22:41 +08:00

84 lines
2.1 KiB
Go

package srt
import (
"os"
"path/filepath"
"strings"
"testing"
"sub-cli/internal/model"
)
func TestGenerate(t *testing.T) {
// Create test entries
entries := []model.SRTEntry{
{
Number: 1,
StartTime: model.Timestamp{Hours: 0, Minutes: 0, Seconds: 1, Milliseconds: 0},
EndTime: model.Timestamp{Hours: 0, Minutes: 0, Seconds: 4, Milliseconds: 0},
Content: "This is the first line.",
},
{
Number: 2,
StartTime: model.Timestamp{Hours: 0, Minutes: 0, Seconds: 5, Milliseconds: 0},
EndTime: model.Timestamp{Hours: 0, Minutes: 0, Seconds: 8, Milliseconds: 0},
Content: "This is the second line.",
},
}
// Generate SRT file
tempDir := t.TempDir()
outputFile := filepath.Join(tempDir, "output.srt")
err := Generate(entries, outputFile)
if err != nil {
t.Fatalf("Generate failed: %v", err)
}
// Verify generated content
content, err := os.ReadFile(outputFile)
if err != nil {
t.Fatalf("Failed to read output file: %v", err)
}
// Check content
lines := strings.Split(string(content), "\n")
if len(lines) < 6 {
t.Fatalf("Expected at least 6 lines, got %d", len(lines))
}
if lines[0] != "1" {
t.Errorf("Expected first line to be '1', got '%s'", lines[0])
}
if lines[1] != "00:00:01,000 --> 00:00:04,000" {
t.Errorf("Expected second line to be time range, got '%s'", lines[1])
}
if lines[2] != "This is the first line." {
t.Errorf("Expected third line to be content, got '%s'", lines[2])
}
}
func TestGenerate_FileError(t *testing.T) {
// Test with invalid path
entries := []model.SRTEntry{
{
Number: 1,
StartTime: model.Timestamp{Hours: 0, Minutes: 0, Seconds: 0, Milliseconds: 0},
EndTime: model.Timestamp{Hours: 0, Minutes: 0, Seconds: 0, Milliseconds: 0},
Content: "Test",
},
}
err := Generate(entries, "/nonexistent/directory/file.srt")
if err == nil {
t.Error("Expected error when generating to invalid path, got nil")
}
// Test with directory as file
tempDir := t.TempDir()
err = Generate(entries, tempDir)
if err == nil {
t.Error("Expected error when generating to a directory, got nil")
}
}