formats_test.go
⎇
Raw
1package service
2
3import (
4 "testing"
5)
6
7func TestParseFormatJSON(t *testing.T) {
8 data := []byte(`{
9 "id": "vid",
10 "formats": [
11 {"format_id": "18", "ext": "mp4", "resolution": "640x360", "fps": 30, "vcodec": "avc1", "acodec": "mp4a", "format_note": "360p"},
12 {"format_id": "137", "ext": "mp4", "width": 1920, "height": 1080, "fps": 60, "vcodec": "avc1", "acodec": "none", "filesize": 1048576, "format_note": "1080p"},
13 {"format_id": "233", "ext": "m4a", "resolution": "audio only", "vcodec": "none", "acodec": "mp4a", "audio_channels": 2, "format_note": "audio"}
14 ]
15 }`)
16 formats, entry, err := parseFormatJSON(data)
17 if err != nil {
18 t.Fatalf("parseFormatJSON: %v", err)
19 }
20 if entry != "" {
21 t.Errorf("single video reported playlist entry %q, want none", entry)
22 }
23 if len(formats) != 3 {
24 t.Fatalf("expected 3 formats, got %d: %+v", len(formats), formats)
25 }
26 if formats[0].ID != "18" || formats[0].Ext != "mp4" || formats[0].Resolution != "640x360" {
27 t.Errorf("format[0] = %+v", formats[0])
28 }
29 if formats[0].FPS != "30" {
30 t.Errorf("format[0] fps = %q, want 30", formats[0].FPS)
31 }
32 // Resolution is derived from width/height when no resolution string is present.
33 if formats[1].Resolution != "1920x1080" {
34 t.Errorf("format[1] resolution = %q, want 1920x1080", formats[1].Resolution)
35 }
36 if formats[1].FileSize != "1.0 MiB" {
37 t.Errorf("format[1] filesize = %q, want 1.0 MiB", formats[1].FileSize)
38 }
39 // Audio-only format: codec falls back to acodec and channels are populated.
40 if formats[2].Codec != "mp4a" {
41 t.Errorf("format[2] codec = %q, want mp4a", formats[2].Codec)
42 }
43 if formats[2].Channels != "2" {
44 t.Errorf("format[2] channels = %q, want 2", formats[2].Channels)
45 }
46}
47
48func TestParseFormatJSONPlaylistFallback(t *testing.T) {
49 // A playlist dump exposes formats under the first entry, not at the top level.
50 data := []byte(`{"_type":"playlist","entries":[{"id":"a","title":"First Clip","formats":[{"format_id":"18","ext":"mp4"}]}]}`)
51 formats, entry, err := parseFormatJSON(data)
52 if err != nil {
53 t.Fatalf("parseFormatJSON: %v", err)
54 }
55 if len(formats) != 1 || formats[0].ID != "18" {
56 t.Fatalf("expected 1 format from entry fallback, got %+v", formats)
57 }
58 if entry != "First Clip" {
59 t.Errorf("playlist entry = %q, want First Clip", entry)
60 }
61
62 // An entry without a title still has to be reported as a playlist entry.
63 _, entry, err = parseFormatJSON([]byte(`{"_type":"playlist","entries":[{"id":"a","formats":[{"format_id":"18"}]}]}`))
64 if err != nil {
65 t.Fatalf("parseFormatJSON: %v", err)
66 }
67 if entry == "" {
68 t.Error("untitled playlist entry reported as a single video")
69 }
70}
71