410 lines
12 KiB
Go
410 lines
12 KiB
Go
package media
|
|
|
|
import (
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
func TestManifestWriter_NewManifestWriter(t *testing.T) {
|
|
// Set up temporary environment for testing
|
|
tempDir, err := os.MkdirTemp("", "manifest_test_*")
|
|
if err != nil {
|
|
t.Fatalf("Failed to create temp dir: %v", err)
|
|
}
|
|
defer os.RemoveAll(tempDir)
|
|
|
|
// Set environment variable to use temp directory
|
|
os.Setenv("LOCAL_OUTPUT_DIR", tempDir)
|
|
defer os.Unsetenv("LOCAL_OUTPUT_DIR")
|
|
|
|
eventName := "test-event"
|
|
writer := NewManifestWriter(eventName)
|
|
|
|
if writer == nil {
|
|
t.Fatal("NewManifestWriter() returned nil")
|
|
}
|
|
|
|
if writer.Segments == nil {
|
|
t.Error("Segments should be initialized")
|
|
}
|
|
if writer.Index == nil {
|
|
t.Error("Index should be initialized")
|
|
}
|
|
if len(writer.Segments) != 0 {
|
|
t.Errorf("Segments should be empty, got %d items", len(writer.Segments))
|
|
}
|
|
}
|
|
|
|
func TestManifestWriter_AddOrUpdateSegment(t *testing.T) {
|
|
writer := &ManifestWriter{
|
|
ManifestPath: "test.json",
|
|
Segments: make([]ManifestItem, 0),
|
|
Index: make(map[string]int),
|
|
}
|
|
|
|
// Test adding new segment
|
|
writer.AddOrUpdateSegment("1001", "1080p")
|
|
|
|
if len(writer.Segments) != 1 {
|
|
t.Errorf("Expected 1 segment, got %d", len(writer.Segments))
|
|
}
|
|
if writer.Segments[0].SeqNo != "1001" {
|
|
t.Errorf("Expected SeqNo '1001', got '%s'", writer.Segments[0].SeqNo)
|
|
}
|
|
if writer.Segments[0].Resolution != "1080p" {
|
|
t.Errorf("Expected Resolution '1080p', got '%s'", writer.Segments[0].Resolution)
|
|
}
|
|
|
|
// Test updating existing segment with higher resolution
|
|
writer.AddOrUpdateSegment("1001", "1440p")
|
|
|
|
if len(writer.Segments) != 1 {
|
|
t.Errorf("Segments count should remain 1 after update, got %d", len(writer.Segments))
|
|
}
|
|
if writer.Segments[0].Resolution != "1440p" {
|
|
t.Errorf("Expected updated resolution '1440p', got '%s'", writer.Segments[0].Resolution)
|
|
}
|
|
|
|
// Test updating existing segment with lower resolution (should not change)
|
|
writer.AddOrUpdateSegment("1001", "720p")
|
|
|
|
if writer.Segments[0].Resolution != "1440p" {
|
|
t.Errorf("Resolution should remain '1440p', got '%s'", writer.Segments[0].Resolution)
|
|
}
|
|
|
|
// Test adding different segment
|
|
writer.AddOrUpdateSegment("1002", "720p")
|
|
|
|
if len(writer.Segments) != 2 {
|
|
t.Errorf("Expected 2 segments, got %d", len(writer.Segments))
|
|
}
|
|
}
|
|
|
|
func TestManifestWriter_AddOrUpdateSegment_NilFields(t *testing.T) {
|
|
writer := &ManifestWriter{
|
|
ManifestPath: "test.json",
|
|
}
|
|
|
|
// Test with nil fields (should initialize them)
|
|
writer.AddOrUpdateSegment("1001", "1080p")
|
|
|
|
if writer.Segments == nil {
|
|
t.Error("Segments should be initialized")
|
|
}
|
|
if writer.Index == nil {
|
|
t.Error("Index should be initialized")
|
|
}
|
|
if len(writer.Segments) != 1 {
|
|
t.Errorf("Expected 1 segment, got %d", len(writer.Segments))
|
|
}
|
|
}
|
|
|
|
func TestManifestWriter_WriteManifest(t *testing.T) {
|
|
tempDir, err := os.MkdirTemp("", "manifest_test_*")
|
|
if err != nil {
|
|
t.Fatalf("Failed to create temp dir: %v", err)
|
|
}
|
|
defer os.RemoveAll(tempDir)
|
|
|
|
manifestPath := filepath.Join(tempDir, "test-manifest.json")
|
|
writer := &ManifestWriter{
|
|
ManifestPath: manifestPath,
|
|
Segments: make([]ManifestItem, 0),
|
|
Index: make(map[string]int),
|
|
}
|
|
|
|
// Add some test segments out of order
|
|
writer.AddOrUpdateSegment("1003", "1080p")
|
|
writer.AddOrUpdateSegment("1001", "720p")
|
|
writer.AddOrUpdateSegment("1002", "1080p")
|
|
|
|
// Write manifest
|
|
writer.WriteManifest()
|
|
|
|
// Verify file was created
|
|
if _, err := os.Stat(manifestPath); os.IsNotExist(err) {
|
|
t.Fatalf("Manifest file was not created: %s", manifestPath)
|
|
}
|
|
|
|
// Read and verify content
|
|
content, err := os.ReadFile(manifestPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to read manifest file: %v", err)
|
|
}
|
|
|
|
var segments []ManifestItem
|
|
err = json.Unmarshal(content, &segments)
|
|
if err != nil {
|
|
t.Fatalf("Failed to unmarshal manifest JSON: %v", err)
|
|
}
|
|
|
|
// Verify segments are sorted by sequence number
|
|
if len(segments) != 3 {
|
|
t.Errorf("Expected 3 segments in manifest, got %d", len(segments))
|
|
}
|
|
|
|
expectedOrder := []string{"1001", "1002", "1003"}
|
|
for i, segment := range segments {
|
|
if segment.SeqNo != expectedOrder[i] {
|
|
t.Errorf("Segment %d: expected SeqNo '%s', got '%s'", i, expectedOrder[i], segment.SeqNo)
|
|
}
|
|
}
|
|
|
|
// Verify content structure
|
|
if segments[0].Resolution != "720p" {
|
|
t.Errorf("Expected first segment resolution '720p', got '%s'", segments[0].Resolution)
|
|
}
|
|
if segments[1].Resolution != "1080p" {
|
|
t.Errorf("Expected second segment resolution '1080p', got '%s'", segments[1].Resolution)
|
|
}
|
|
}
|
|
|
|
func TestManifestWriter_WriteManifest_EmptySegments(t *testing.T) {
|
|
tempDir, err := os.MkdirTemp("", "manifest_test_*")
|
|
if err != nil {
|
|
t.Fatalf("Failed to create temp dir: %v", err)
|
|
}
|
|
defer os.RemoveAll(tempDir)
|
|
|
|
manifestPath := filepath.Join(tempDir, "empty-manifest.json")
|
|
writer := &ManifestWriter{
|
|
ManifestPath: manifestPath,
|
|
Segments: make([]ManifestItem, 0),
|
|
Index: make(map[string]int),
|
|
}
|
|
|
|
// Write empty manifest
|
|
writer.WriteManifest()
|
|
|
|
// Verify file was created
|
|
if _, err := os.Stat(manifestPath); os.IsNotExist(err) {
|
|
t.Fatalf("Manifest file was not created: %s", manifestPath)
|
|
}
|
|
|
|
// Read and verify content is empty array
|
|
content, err := os.ReadFile(manifestPath)
|
|
if err != nil {
|
|
t.Fatalf("Failed to read manifest file: %v", err)
|
|
}
|
|
|
|
var segments []ManifestItem
|
|
err = json.Unmarshal(content, &segments)
|
|
if err != nil {
|
|
t.Fatalf("Failed to unmarshal manifest JSON: %v", err)
|
|
}
|
|
|
|
if len(segments) != 0 {
|
|
t.Errorf("Expected empty segments array, got %d items", len(segments))
|
|
}
|
|
}
|
|
|
|
func TestManifestWriter_WriteManifest_InvalidPath(t *testing.T) {
|
|
writer := &ManifestWriter{
|
|
ManifestPath: "/invalid/path/that/does/not/exist/manifest.json",
|
|
Segments: []ManifestItem{{SeqNo: "1001", Resolution: "1080p"}},
|
|
Index: make(map[string]int),
|
|
}
|
|
|
|
// This should not panic, just fail gracefully
|
|
writer.WriteManifest()
|
|
|
|
// Test passes if no panic occurs
|
|
}
|
|
|
|
func TestManifestItem_JSONSerialization(t *testing.T) {
|
|
item := ManifestItem{
|
|
SeqNo: "1001",
|
|
Resolution: "1080p",
|
|
}
|
|
|
|
// Test marshaling
|
|
data, err := json.Marshal(item)
|
|
if err != nil {
|
|
t.Fatalf("Failed to marshal ManifestItem: %v", err)
|
|
}
|
|
|
|
// Test unmarshaling
|
|
var unmarshaled ManifestItem
|
|
err = json.Unmarshal(data, &unmarshaled)
|
|
if err != nil {
|
|
t.Fatalf("Failed to unmarshal ManifestItem: %v", err)
|
|
}
|
|
|
|
if unmarshaled.SeqNo != item.SeqNo {
|
|
t.Errorf("SeqNo mismatch: expected '%s', got '%s'", item.SeqNo, unmarshaled.SeqNo)
|
|
}
|
|
if unmarshaled.Resolution != item.Resolution {
|
|
t.Errorf("Resolution mismatch: expected '%s', got '%s'", item.Resolution, unmarshaled.Resolution)
|
|
}
|
|
}
|
|
|
|
func TestResolutionHeight(t *testing.T) {
|
|
cases := map[string]int{
|
|
"1080p": 1080,
|
|
"720p": 720,
|
|
"2160p": 2160,
|
|
"1440p": 1440,
|
|
"240p": 240,
|
|
// Not a <height>p label: must rank below every real resolution rather
|
|
// than accidentally outranking them.
|
|
"unknown": 0,
|
|
"": 0,
|
|
"p": 0,
|
|
}
|
|
|
|
for label, want := range cases {
|
|
if got := ResolutionHeight(label); got != want {
|
|
t.Errorf("ResolutionHeight(%q) = %d, want %d", label, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestAddOrUpdateSegmentKeepsHighestResolution pins the comparison used to
|
|
// choose between variants. Comparing the labels as strings — as this once did —
|
|
// ranks "720p" above "1080p", quietly downgrading the manifest.
|
|
func TestAddOrUpdateSegmentKeepsHighestResolution(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
arriving []string
|
|
want string
|
|
}{
|
|
{"higher replaces lower", []string{"720p", "1080p"}, "1080p"},
|
|
{"lower does not replace higher", []string{"1080p", "720p"}, "1080p"},
|
|
{"fewer digits must not win", []string{"1080p", "480p"}, "1080p"},
|
|
{"4k beats 1080p", []string{"1080p", "2160p"}, "2160p"},
|
|
{"unknown loses to a real resolution", []string{"unknown", "480p"}, "480p"},
|
|
{"unknown does not displace a real resolution", []string{"1080p", "unknown"}, "1080p"},
|
|
{"repeated identical resolution", []string{"720p", "720p"}, "720p"},
|
|
}
|
|
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
w := &ManifestWriter{}
|
|
for _, res := range tc.arriving {
|
|
w.AddOrUpdateSegment("1001", res)
|
|
}
|
|
|
|
if len(w.Segments) != 1 {
|
|
t.Fatalf("expected a single entry, got %d", len(w.Segments))
|
|
}
|
|
if got := w.Segments[0].Resolution; got != tc.want {
|
|
t.Errorf("kept %q, want %q (arrival order %v)", got, tc.want, tc.arriving)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestAddOrUpdateSegmentUpdatesTheStoredEntry guards the aliasing bug: the
|
|
// index once held a pointer to a local copy rather than to the stored element,
|
|
// so updates were applied to an orphan and never reached the written manifest.
|
|
func TestAddOrUpdateSegmentUpdatesTheStoredEntry(t *testing.T) {
|
|
w := &ManifestWriter{}
|
|
|
|
// Enough entries to force at least one append reallocation, which would
|
|
// invalidate any pointer held into the backing array.
|
|
for i := 0; i < 64; i++ {
|
|
w.AddOrUpdateSegment(strconv.Itoa(1000+i), "480p")
|
|
}
|
|
for i := 0; i < 64; i++ {
|
|
w.AddOrUpdateSegment(strconv.Itoa(1000+i), "1080p")
|
|
}
|
|
|
|
if len(w.Segments) != 64 {
|
|
t.Fatalf("expected 64 entries, got %d", len(w.Segments))
|
|
}
|
|
for _, seg := range w.Segments {
|
|
if seg.Resolution != "1080p" {
|
|
t.Fatalf("segment %s kept %q; the upgrade never reached the stored entry", seg.SeqNo, seg.Resolution)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestAddOrUpdateSegmentIsConcurrencySafe reflects real use: every variant
|
|
// downloads in its own goroutine and reports segments as they land.
|
|
func TestAddOrUpdateSegmentIsConcurrencySafe(t *testing.T) {
|
|
w := &ManifestWriter{}
|
|
resolutions := []string{"240p", "480p", "720p", "1080p"}
|
|
|
|
var wg sync.WaitGroup
|
|
for _, res := range resolutions {
|
|
wg.Add(1)
|
|
go func(res string) {
|
|
defer wg.Done()
|
|
for seq := 0; seq < 200; seq++ {
|
|
w.AddOrUpdateSegment(strconv.Itoa(seq), res)
|
|
}
|
|
}(res)
|
|
}
|
|
wg.Wait()
|
|
|
|
if got := w.Len(); got != 200 {
|
|
t.Errorf("expected 200 distinct sequence numbers, got %d", got)
|
|
}
|
|
for _, seg := range w.Segments {
|
|
if seg.Resolution != "1080p" {
|
|
t.Errorf("segment %s = %q, want the highest variant 1080p", seg.SeqNo, seg.Resolution)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestWriteManifestSortsNumerically checks that segment 9 precedes segment 10,
|
|
// which string ordering would reverse.
|
|
func TestWriteManifestSortsNumerically(t *testing.T) {
|
|
dir := t.TempDir()
|
|
w := &ManifestWriter{ManifestPath: filepath.Join(dir, "event.json")}
|
|
|
|
for _, seq := range []string{"100", "9", "1000", "10", "1"} {
|
|
w.AddOrUpdateSegment(seq, "1080p")
|
|
}
|
|
w.WriteManifest()
|
|
|
|
data, err := os.ReadFile(w.ManifestPath)
|
|
if err != nil {
|
|
t.Fatalf("failed to read manifest: %v", err)
|
|
}
|
|
|
|
var items []ManifestItem
|
|
if err := json.Unmarshal(data, &items); err != nil {
|
|
t.Fatalf("manifest is not valid JSON: %v", err)
|
|
}
|
|
|
|
want := []string{"1", "9", "10", "100", "1000"}
|
|
if len(items) != len(want) {
|
|
t.Fatalf("expected %d entries, got %d", len(want), len(items))
|
|
}
|
|
for i, seq := range want {
|
|
if items[i].SeqNo != seq {
|
|
t.Errorf("position %d = %q, want %q (full order: %v)", i, items[i].SeqNo, seq, items)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestWriteManifestLeavesIndexUsable ensures writing mid-recording does not
|
|
// corrupt the writer: sorting in place would desynchronise Index from Segments.
|
|
func TestWriteManifestLeavesIndexUsable(t *testing.T) {
|
|
dir := t.TempDir()
|
|
w := &ManifestWriter{ManifestPath: filepath.Join(dir, "event.json")}
|
|
|
|
w.AddOrUpdateSegment("20", "480p")
|
|
w.AddOrUpdateSegment("10", "480p")
|
|
w.WriteManifest()
|
|
|
|
// After the write, an upgrade must still land on the right entry.
|
|
w.AddOrUpdateSegment("20", "1080p")
|
|
|
|
pos, ok := w.Index["20"]
|
|
if !ok {
|
|
t.Fatal("sequence 20 missing from the index after WriteManifest")
|
|
}
|
|
if got := w.Segments[pos].Resolution; got != "1080p" {
|
|
t.Errorf("sequence 20 = %q, want 1080p; the index no longer matches the slice", got)
|
|
}
|
|
if w.Segments[w.Index["10"]].SeqNo != "10" {
|
|
t.Error("index and slice disagree after WriteManifest")
|
|
}
|
|
}
|