Debian Codegraph @

mimetype_test.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package mimetype
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "math/rand"
8 "mime"
9 "os"
10 "strings"
11 "sync"
12 "testing"
13 "testing/iotest"
14 )
15
16 // testcases are used for correctness and benchmarks.
17 // testcase data is provided as a string for convenience,
18 // but that makes benchmarks allocate more. It can be observed
19 // for testcases that call fromDisk. Those allocate more because
20 // they read a lot from disk.
21 type testcase struct {
22 name string
23 data string
24 expectedMIME string
25 bench string
26 }
27
28 var testcases = []testcase{
29 {"3gpp2", "\x00\x00\x00\x18ftyp3g24", "video/3gpp2", one},
30 {"3gpp2 without ftyp", "\x00\x00\x00\x18mtyp3g24", "application/octet-stream", none},
31 {"3gp", "\x00\x00\x00\x18ftyp3gp1", "video/3gpp", one},
32 {
33 "3mf",
34 `<?xml version="1.0"?><model xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">`,
35 "application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
36 one,
37 },
38 {"7z", "\x37\x7A\xBC\xAF\x27\x1C", "application/x-7z-compressed", all},
39 {"a", "\x21\x3C\x61\x72\x63\x68\x3E", "application/x-archive", one},
40 {"aac 1", "\xFF\xF1", "audio/aac", one},
41 {"aac 2", "\xFF\xF9", "audio/aac", none},
42 {"accdb", offset(4, "Standard ACE DB"), "application/x-msaccess", none}, // none because accdb and mdb share the same MIME
43 {"aiff", "\x46\x4F\x52\x4D\x00\x00\x00\x00\x41\x49\x46\x46\x00", "audio/aiff", one},
44 {"amf", `<?xml version="1.0"?><amf>`, "application/x-amf", one},
45 {"amr", "\x23\x21\x41\x4D\x52", "audio/amr", one},
46 {"ape", "\x4D\x41\x43\x20\x96\x0F\x00\x00\x34\x00\x00\x00\x18\x00\x00\x00\x90\xE3", "audio/ape", one},
47 {"apk app-metadata.properties", fromDisk("app-metadata.apk"), "application/vnd.android.package-archive", one},
48 {"apk zipflinger", fromDisk("zipflinger.apk"), "application/vnd.android.package-archive", one},
49 {"apng", "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\xe0\x00\x00\x01\x90\b\x06\x00\x00\x00v\xf6\xb3T\x00\x00\x00\bacTL", "image/apng", all},
50 {"asf", "\x30\x26\xB2\x75\x8E\x66\xCF\x11\xA6\xD9\x00\xAA\x00\x62\xCE\x6C", "video/x-ms-asf", one},
51 {"atom", `<?xml version="1.0"?><feed xmlns="http://www.w3.org/2005/Atom">`, "application/atom+xml", one},
52 {"au", "\x2E\x73\x6E\x64", "audio/basic", one},
53 {"avi", "RIFF\x00\x00\x00\x00AVI LIST\x00", "video/x-msvideo", all},
54 {"avif", "\x00\x00\x00\x18ftypavif", "image/avif", all},
55 {"avis", "\x00\x00\x00\x18ftypavis", "image/avif", all},
56 {"bmp\x30", "BM \x30\x00\x00\x00", "image/bmp", all},
57 {"bmp\x18", "BM \x18\x00\x00\x00", "image/bmp", none},
58 {"bmp\x10", "BM \x10\x00\x00\x00", "image/bmp", none},
59 {"bmp\x40", "BM \x40\x00\x00\x00", "image/bmp", none},
60 {"bmp\x34", "BM \x34\x00\x00\x00", "image/bmp", none},
61 {"bmp\x38", "BM \x38\x00\x00\x00", "image/bmp", none},
62 {"bmp\x28", "BM \x28\x00\x00\x00", "image/bmp", none},
63 {"bmp\x7C", "BM \x7C\x00\x00\x00", "image/bmp", none},
64 {"bmp\x6C", "BM \x6C\x00\x00\x00", "image/bmp", none},
65 {"bpg", "\x42\x50\x47\xFB", "image/bpg", one},
66 {"bufr", "BUFR \x03", "application/bufr", one},
67 {"bz2", "\x42\x5A\x68", "application/x-bzip2", one},
68 {"cab", "MSCF\x00\x00\x00\x00", "application/vnd.ms-cab-compressed", one},
69 {"cab.is", "ISc(\x00\x00\x00\x01", "application/x-installshield", one},
70 {"cdf-doc", fromDisk("doc.doc"), "application/msword", all},
71 {"cdf-xls", fromDisk("xls.xls"), "application/vnd.ms-excel", one},
72 {"cdf-msg", fromDisk("msg.msg"), "application/vnd.ms-outlook", one},
73 {"cdf-msi", fromDisk("msi.msi"), "application/x-ms-installer", all},
74 {"cdf-ppt", fromDisk("ppt.ppt"), "application/vnd.ms-powerpoint", all},
75 {"cdf-pub", fromDisk("pub.pub"), "application/vnd.ms-publisher", one},
76 {"chm", "ITSF\003\000\000\000\x60\000\000\000", "application/vnd.ms-htmlhelp", one},
77 {"class", "\xCA\xFE\xBA\xBE\x00\x00\x00\xFF", "application/x-java-applet", one},
78 {
79 "crx",
80 "Cr24\x00\x00\x00\x00\x01\x00\x00\x00\x0F\x00\x00\x00" + offset(16, "") + "\x50\x4B\x03\x04",
81 "application/x-chrome-extension",
82 one,
83 },
84 {
85 "csv",
86 `1,2
87 "abc","def"
88 a,"b`,
89 "text/csv",
90 all,
91 },
92 {
93 `csv with \r\n`,
94 "1,2\r\n3,4\r\na,b",
95 "text/csv",
96 none,
97 },
98 {"cpio 7", "070707", "application/x-cpio", one},
99 {"cpio 1", "070701", "application/x-cpio", none},
100 {"cpio 2", "070702", "application/x-cpio", none},
101 {"cpio bin", "\xC7\x71____", "application/x-cpio", none},
102 {"cyclonedx json", `{"bomFormat": "CycloneDX", "specVersion": "1.2"}`, "application/vnd.cyclonedx+json", one},
103 {"cyclonedx xml", `<?xml version="1.0"?> <bom xmlns="http://cyclonedx.org/schema/bom/1.1">`, "application/vnd.cyclonedx+xml", one},
104 {"dae", `<?xml version="1.0"?><COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema">`, "model/vnd.collada+xml", one},
105 {"dbf", "\x03\x5f\x07\x1a\x96\x0f\x00\x00\xc1\x00\xa3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x6f\x73\x6d\x5f\x69\x64\x00\x00\x00\x00\x00\x43\x00\x00\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x63\x6f\x64\x65", "application/x-dbf", one},
106 {"dcm", offset(128, "\x44\x49\x43\x4D"), "application/dicom", one},
107 {"deb", "\x21\x3c\x61\x72\x63\x68\x3e\x0a\x64\x65\x62\x69\x61\x6e\x2d\x62\x69\x6e\x61\x72\x79", "application/vnd.debian.binary-package", all},
108 {"djvu", "\x41\x54\x26\x54\x46\x4F\x52\x4D\x00\x00\x00\x00DJVU", "image/vnd.djvu", one},
109 {"djvuM", "\x41\x54\x26\x54\x46\x4F\x52\x4D\x00\x00\x00\x00DJVM", "image/vnd.djvu", none},
110 {"djvuI", "\x41\x54\x26\x54\x46\x4F\x52\x4D\x00\x00\x00\x00DJVI", "image/vnd.djvu", none},
111 {"djvuTHUM", "\x41\x54\x26\x54\x46\x4F\x52\x4D\x00\x00\x00\x00THUM", "image/vnd.djvu", none},
112 {"docx", fromDisk("docx.docx"), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", all},
113 {"rpm 1", "\xed\xab\xee\xdb", "application/x-rpm", one},
114 {"rpm 2", "drpm", "application/x-rpm", none},
115 {"dwg", "\x41\x43\x31\x30\x32\x34", "image/vnd.dwg", none},
116 {"dxf1", " 0\x0ASECTION\x0A", "image/vnd.dxf", one},
117 {"dxf2", " 0\x0D\x0ASECTION\x0D\x0A", "image/vnd.dxf", none},
118 {"dxf3", "0\x0ASECTION\x0A", "image/vnd.dxf", none},
119 {"dxf4", "0\x0D\x0ASECTION\x0D\x0A", "image/vnd.dxf", none},
120 {"eot", "\xbe\x45\x00\x00\xfa\x44\x00\x00\x02\x00\x02\x00\x04\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x90\x01\x00\x00\x00\x00\x4c\x50", "application/vnd.ms-fontobject", one},
121 {"epub", "\x50\x4B\x03\x04" + offset(26, "mimetypeapplication/epub+zip"), "application/epub+zip", all},
122 {"exe", "\x4D\x5A", "application/vnd.microsoft.portable-executable", all},
123 {"fdf", "%FDF", "application/vnd.fdf", one},
124 {"fits", "\x53\x49\x4d\x50\x4c\x45\x20\x20\x3d\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x54", "application/fits", one},
125 {"flac", "\x66\x4C\x61\x43\x00\x00\x00\x22", "audio/flac", one},
126 {"flv", "\x46\x4C\x56\x01", "video/x-flv", one},
127 {"fm", "<MakerFile \x00", "application/vnd.framemaker", one},
128 {"fmdict", "<MakerDictionary \x00", "application/vnd.framemaker", one},
129 {"fmbook", "<BooKFilE \x00", "application/vnd.framemaker", one},
130 {"gbr", offset(20, "GIMP"), "image/x-gimp-gbr", one},
131 {"geojson", `{"type":"Feature"}`, "application/geo+json", one},
132 {"geojson with space", `{ "type" : "Feature" }`, "application/geo+json", none},
133 {"gltf1", `{"asset":{"version":"1.0"}}`, "model/gltf+json", none},
134 {"gltf2", `{"asset":{"version":"2.0"}}`, "model/gltf+json", none},
135 {"gif 87", "GIF87a", "image/gif", all},
136 {"gif 89", "GIF89a", "image/gif", none},
137 {"glb 1", "\x67\x6C\x54\x46\x02\x00\x00\x00", "model/gltf-binary", one},
138 {"glb 2", "\x67\x6C\x54\x46\x01\x00\x00\x00", "model/gltf-binary", none},
139 {"gml", `<?xml version="1.0"?><any xmlns:gml="http://www.opengis.net/gml">`, "application/gml+xml", one},
140 {"gml3.2", `<?xml version="1.0"?><any xmlns:gml="http://www.opengis.net/gml/3.2">`, "application/gml+xml", none},
141 {"gml3.3", `<?xml version="1.0"?><any xmlns:gml="http://www.opengis.net/gml/3.3/exr">`, "application/gml+xml", none},
142 {"gpx", `<?xml version="1.0"?><gpx xmlns="http://www.topografix.com/GPX/1/1">`, "application/gpx+xml", one},
143 {"grib1", "GRIB\x00\x00\x00\x01", "application/grib", one},
144 {"grib2", "GRIB\x00\x00\x00\x02", "application/grib", none},
145 {"gz", "\x1F\x8B", "application/gzip", all},
146 {"har", `{"log":{ "version": "1.2"}}`, "application/json", one},
147 {"hdr", "#?RADIANCE\n", "image/vnd.radiance", one},
148 {"heic", "\x00\x00\x00\x18ftypheic", "image/heic", one},
149 {"heix", "\x00\x00\x00\x18ftypheix", "image/heic", none},
150 {"heif mif1", "\x00\x00\x00\x18ftypmif1", "image/heif", one},
151 {"heif heim", "\x00\x00\x00\x18ftypheim", "image/heif", none},
152 {"heif heis", "\x00\x00\x00\x18ftypheis", "image/heif", none},
153 {"heif avic", "\x00\x00\x00\x18ftypavic", "image/heif", none},
154 {"html", `<HtMl><bOdY>blah blah blah</body></html>`, "text/html; charset=utf-8", all},
155 {"html empty", `<HTML></HTML>`, "text/html; charset=utf-8", none},
156 {"html just header", ` <!DOCTYPE HTML>...`, "text/html; charset=utf-8", none},
157 {"line ending before html", "\r\n<html>...", "text/html; charset=utf-8", none},
158 {
159 "html with encoding",
160 `<Html><Head><metA Http-EquiV="Content-Type" Content="text/html; charset=iso-8859-1">`,
161 "text/html; charset=iso-8859-1",
162 none,
163 },
164 {
165 "html with comment prefix",
166 `<!-- this comment should not affect --><html><head>`,
167 "text/html; charset=utf-8",
168 none,
169 },
170 {"ico 01", "\x00\x00\x01\x00", "image/x-icon", one},
171 {"ico 02", "\x00\x00\x02\x00", "image/x-icon", none},
172 {"ics", "BEGIN:VCALENDAR\n00", "text/calendar", one},
173 {"ics dos", "BEGIN:VCALENDAR\r\n00", "text/calendar", none},
174 {"inf os2", "HSP\x01\x9b\x00", "application/x-os2-inf", none},
175 {"hlp os2", "HSP\x10\x9b\x00", "application/x-os2-hlp", none},
176 {"txt iso88591", "\x0a\xe6\xf8\xe6\xf8\xe5\xe6\xf8\xe5\xe5\x0a", "text/plain; charset=iso-8859-1", none},
177 {"jar", fromDisk("jar.jar"), "application/java-archive", all},
178 {"jar executable", "PK\x03\x04\x00\x00\x00\x00\x01" + offset(0x15, "\xFE\xCA"), "application/java-archive", none},
179 {"jar in zip #639", fromDisk("jar_in_zip.zip"), "application/zip", none},
180 {"jp2", "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a\x00\x00\x00\x14\x66\x74\x79\x70\x6a\x70\x32\x20", "image/jp2", one},
181 {"jpf", "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a\x00\x00\x00\x1c\x66\x74\x79\x70\x6a\x70\x78\x20", "image/jpx", one},
182 {"jpg", "\xFF\xD8\xFF", "image/jpeg", one},
183 {"jpm", "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a\x00\x00\x00\x14\x66\x74\x79\x70\x6a\x70\x6d\x20", "image/jpm", one},
184 {"jxl 1", "\xFF\x0A", "image/jxl", one},
185 {"jxl 2", "\x00\x00\x00\x0cJXL\x20\x0d\x0a\x87\x0a", "image/jxl", none},
186 {"jxr", "\x49\x49\xBC\x01", "image/jxr", one},
187 {"xpm", "\x2F\x2A\x20\x58\x50\x4D\x20\x2A\x2F", "image/x-xpixmap", one},
188 {"js", "#!/bin/node ", "text/javascript", one},
189 {"json", `{"a":"b", "c":[{"a":"b"},1,true,false,"abc"]}`, "application/json", all},
190 {"json multiple lines", `{"a":"b",
191 "c":[{"a":"b"},
192 1,true,false,
193 "abc"]}`, "application/json", none},
194 {"json issue#239", "{\x0A\x09\x09\"key\":\"val\"}\x0A", "application/json", none},
195 // json.{int,float,string}.txt contain a single JSON value. They are valid JSON
196 // documents but they should not be detected as application/json. This mimics
197 // the behaviour of libmagic and seems the correct thing to do.
198 {"json.int.txt", "1", "text/plain; charset=utf-8", none},
199 {"json.float.txt", "1.5", "text/plain; charset=utf-8", none},
200 {"json.string.txt", `"some string"`, "text/plain; charset=utf-8", none},
201 {"kml 2.2", `<?xml version="1.0"?><kml xmlns="http://www.opengis.net/kml/2.2">`, "application/vnd.google-earth.kml+xml", one},
202 {"kml 2.0", `<?xml version="1.0"?><kml xmlns="http://earth.google.com/kml/2.0">`, "application/vnd.google-earth.kml+xml", none},
203 {"kml 2.1", `<?xml version="1.0"?><kml xmlns="http://earth.google.com/kml/2.1">`, "application/vnd.google-earth.kml+xml", none},
204 {"kml 2.2", `<?xml version="1.0"?><kml xmlns="http://earth.google.com/kml/2.2">`, "application/vnd.google-earth.kml+xml", none},
205 {"kmz", "\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00\xe6\x6c\x04\x5b\xfd\xf4\xf2\x45\x41\x00\x00\x00\x43\x00\x00\x00\x07\x00\x1c\x00doc.kml", "application/vnd.google-earth.kmz", none},
206 {"lit", "ITOLITLS", "application/x-ms-reader", one},
207 {"lotus1", "\x00\x00\x02\x00456\x00" + offset(13, ""), "application/vnd.lotus-1-2-3", one},
208 {"lotus2", "\x00\x00\x1a\x00" + offset(16, "\x01"), "application/vnd.lotus-1-2-3", one},
209 {"lua", "#!/usr/bin/lua", "text/x-lua", one},
210 {"lua space", "#! /usr/bin/lua", "text/x-lua", none},
211 {"lz", "\x4c\x5a\x49\x50", "application/lzip", one},
212 {"m3u", "#EXTM3U\n", "application/vnd.apple.mpegurl", one},
213 {"m4a", "\x00\x00\x00\x18ftypM4A ", "audio/x-m4a", one},
214 {"audio mp4 F4A", "\x00\x00\x00\x18ftypF4A ", "audio/mp4", one},
215 {"audio mp4 F4B", "\x00\x00\x00\x18ftypF4B ", "audio/mp4", none},
216 {"audio mp4 M4B", "\x00\x00\x00\x18ftypM4B ", "audio/mp4", none},
217 {"audio mp4 M4P", "\x00\x00\x00\x18ftypM4P ", "audio/mp4", none},
218 {"audio mp4 MSNV", "\x00\x00\x00\x18ftypMSNV", "audio/mp4", none},
219 {"audio mp4 NDAS", "\x00\x00\x00\x18ftypNDAS", "audio/mp4", none},
220 {"lnk", "\x4C\x00\x00\x00\x01\x14\x02\x00", "application/x-ms-shortcut", one},
221 {"mdb", offset(4, "Standard Jet DB"), "application/x-msaccess", one},
222 {"midi", "\x4D\x54\x68\x64", "audio/midi", one},
223 {"mkv", "\x1a\x45\xdf\xa3\x01\x00\x00\x00\x00\x00\x00\x23\x42\x86\x81\x01\x42\xf7\x81\x01\x42\xf2\x81\x04\x42\xf3\x81\x08\x42\x82\x88\x6d\x61\x74\x72\x6f\x73\x6b\x61", "video/matroska", one},
224 {"mobi", offset(60, "BOOKMOBI"), "application/x-mobipocket-ebook", one},
225 {"mov", "\x00\x00\x00\x14\x66\x74\x79\x70\x71\x74\x20\x20", "video/quicktime", one},
226 {"mp3", "ID3\x04\x00\x00\x00\x00\x00\x01", "audio/mpeg", all},
227 {"mp3 v1 notag", "\xff\xfb\xc8\x00", "audio/mpeg", none},
228 {"mp3 v2.5 notag", "\xff\xe3\x18\xc4", "audio/mpeg", none},
229 {"mp3 v2 notag", "\xff\xf3\x82\xc4", "audio/mpeg", none},
230 {"mp4 1", "\x00\x00\x00\x18ftyp0000", "video/mp4", all},
231 {"mpc", "MPCK", "audio/musepack", one},
232 {"mpeg", "\x00\x00\x01\xba", "video/mpeg", one},
233 {"mqv", "\x00\x00\x00\x18ftypmqt ", "video/quicktime", none},
234 {"mrc", "00057 2200037 4500245001900000\x1e", "application/marc", one},
235 {"ndjson", `{"key":"val"}` + "\n" + `{"key":"val"}`, "application/x-ndjson", one},
236 {"ndjson spaces", `{ "key" : "val" }` + "\n" + ` { "key" : "val" }`, "application/x-ndjson", one},
237 {
238 "ndjson with before&after lines",
239 `
240 {"key":"val"}
241 {"key":"val"}
242 `,
243 "application/x-ndjson",
244 none,
245 },
246 {
247 "empty lines should not be counted for ndjson",
248 `
249 {"key":"val"}
250 `,
251 "application/json",
252 none,
253 },
254 {
255 "a json spread on multiple lines is not ndjson",
256 `{"key"
257 :"val"}`,
258 "application/json",
259 none,
260 },
261 {
262 "a json object spread on multiple lines second line valid json", // #803
263 `{"key":
264 "val"`, // Notice how this line is a valid json value (a string)
265 "text/plain; charset=utf-8",
266 none,
267 },
268 {
269 "a json array spread on multiple lines second line valid json", // #803
270 `{"key":
271 "val"`,
272 "text/plain; charset=utf-8",
273 none,
274 },
275 {"nes", "NES\x1a", "application/vnd.nintendo.snes.rom", one},
276 {"elfobject", "\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00", "application/x-object", one},
277 {"odf", "PK\x03\x04\x14\x00\x00\x08\x00\x00\xb1Z\xa8N\x07\x8a\xa8[*\x00\x00\x00*\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.formula", "application/vnd.oasis.opendocument.formula", one},
278 {"sxc", "PK\x03\x04\x14\x00\x00\x08\x00\x00\xbb\x03\x5eGE\xbc\x13\x94\x1c\x00\x00\x00\x1c\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.sun.xml.calc", "application/vnd.sun.xml.calc", one},
279 {"odg", "PK\x03\x04\x14\x00\x00\x08\x00\x00\xcbY\xa8N\x9f\x03.\xc4\x2b\x00\x00\x00\x2b\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.graphics", "application/vnd.oasis.opendocument.graphics", one},
280 {"odp", "PK\x03\x04\x14\x00\x00\x08\x00\x00\xbdX\xa8N3&\xac\xa8/\x00\x00\x00/\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.presentation", "application/vnd.oasis.opendocument.presentation", one},
281 {"ods", "PK\x03\x04\x14\x00\x00\x08\x00\x00\x14V\xa8N\x85l9\x8a.\x00\x00\x00.\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.spreadsheet", one},
282 {"odt", "PK\x03\x04\x14\x00\x00\x08\x00\x00\xbbP\xa8N\x5e\xc62\n'\x00\x00\x00'\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.text", "application/vnd.oasis.opendocument.text", one},
283 {"ogg", "OggS\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\xce\xc6AI\x00\x00\x00\x00py\xf3\x3d\x01\x1e\x01vorbis\x00\x00", "audio/ogg", one},
284 {"ogg", "OggS\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x80\xbc\x81_\x00\x00\x00\x00\xd0\xfbP\x84\x01@fishead\x00\x03", "video/ogg", one},
285 {"ogg spx oga", "OggS\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\xc7w\xaa\x15\x00\x00\x00\x00V&\x88\x89\x01PSpeex 1", "audio/ogg", one},
286 {"one", "\xe4\x52\x5c\x7b\x8c\xd8\xa7\x4d\xae\xb1\x53\x78\xd0\x29\x96\xd3", "application/onenote", one},
287 {"otf", "OTTO\x00\x0c\x00\x80\x00\x03\x00\x40\x43\x46\x46 " + offset(36, ""), "font/otf", one},
288 {"otg", "PK\x03\x04\x14\x00\x00\x08\x00\x00\xd1Y\xa8N\xdf%\xad\xe94\x00\x00\x004\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.graphics-template", "application/vnd.oasis.opendocument.graphics-template", one},
289 {"otp", "PK\x03\x04\x14\x00\x00\x08\x00\x00\xc4X\xa8N\xef\n\x14:8\x00\x00\x008\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.presentation-template", "application/vnd.oasis.opendocument.presentation-template", one},
290 {"ots", "PK\x03\x04\x14\x00\x00\x08\x00\x00\x1bV\xa8N{\x96\xa3N7\x00\x00\x007\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.spreadsheet-template", "application/vnd.oasis.opendocument.spreadsheet-template", one},
291 {"ott", "PK\x03\x04\x14\x00\x00\x08\x00\x00\xcfP\xa8N\xe4\x11\x92)0\x00\x00\x000\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.text-template", "application/vnd.oasis.opendocument.text-template", one},
292 {"odc", "PK\x03\x04\x14\x00\x00\x08\x00\x00zp2R\xab\xb8\xb2l(\x00\x00\x00(\x00\x00\x00\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.chart", "application/vnd.oasis.opendocument.chart", one},
293 {"owl", `<?xml version="1.0"?><Ontology xmlns="http://www.w3.org/2002/07/owl#">`, "application/owl+xml", one},
294 {"pat", "\x00\x00\x00\x1c\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x03GPAT", "image/x-gimp-pat", one},
295 {"pcap", "\xd4\xc3\xb2\xa1", "application/vnd.tcpdump.pcap", none},
296 {"pdf", "%PDF-", "application/pdf", all},
297 {"php", "#!/usr/bin/env php", "text/x-php", one},
298 {"pl", "#!/usr/bin/perl", "text/x-perl", one},
299 {"png", "\x89PNG\x0d\x0a\x1a\x0a", "image/png", all},
300 {"pptx", fromDisk("pptx.pptx"), "application/vnd.openxmlformats-officedocument.presentationml.presentation", all},
301 {"pbm", "P1\n# comment\n\n6 10", "image/x-portable-bitmap", one},
302 {"pgm", "P2\n# comment\n\n6 10", "image/x-portable-graymap", one},
303 {"ppm", "P3\n# comment\n\n6 10", "image/x-portable-pixmap", one},
304 {
305 "pam",
306 `P7
307 WIDTH 4
308 HEIGHT 2
309 DEPTH 4
310 MAXVAL 255
311 TUPLTYPE RGB_ALPHA
312 ENDHDR`,
313 "image/x-portable-arbitrarymap",
314 one,
315 },
316 {"ps", "%!PS-Adobe-", "application/postscript", one},
317 {"psd", "8BPS", "image/vnd.adobe.photoshop", all},
318 {"p7s_pem", "-----BEGIN PKCS7", "application/pkcs7-signature", one},
319 {"p7s_der", "\x30\x82\x01\x26\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x07\x02\xa0\x82\x01\x17\x30", "application/pkcs7-signature", one},
320 {"py", "#!/usr/bin/python", "text/x-python", one},
321 {"py3", "#!/usr/bin/env python3", "text/x-python", one},
322 {"py3 with code", "#!/usr/bin/env -S python3\nprint(1)", "text/x-python", none},
323 {"pyc 1.0", "\x02\x09\x99\x00\x00\x00\x00\x00", "application/x-bytecode.python", none},
324 {"pyc 3.7", "\x3f\x0d\x0d\x0a\x00\x00\x00\x00", "application/x-bytecode.python", none},
325 {"pyc pypy3.7", "\xf0\x00\x0d\x0a\x00\x00\x00\x00", "application/x-bytecode.python", none},
326 {"pyc >3.14", "\x00\x0e\x0d\x0a\x00\x00\x00\x00", "application/x-bytecode.python", none},
327 {"qcp", "RIFF\xc0\xcf\x00\x00QLCMf", "audio/qcelp", one},
328 {"rar", "Rar!\x1a\x07\x01\x00", "application/vnd.rar", one},
329 {"rfc822", "Cc: [email protected]\nTo: [email protected]", "message/rfc822", one},
330 {"rfc822 case insensitive", "Cc: [email protected]\nDeLiVeReD-To: [email protected]", "message/rfc822", none},
331 {"rb", "#!/usr/local/bin/ruby", "text/x-ruby", one},
332 {"rmvb", ".RMF", "application/vnd.rn-realmedia-vbr", one},
333 {"rpm", "\xed\xab\xee\xdb", "application/x-rpm", one},
334 {"rss", "\x3c\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\x2d\x38\x22\x3f\x3e\x0a\x3c\x72\x73\x73", "application/rss+xml", one},
335 {"rtf", "{\\rtf", "text/rtf", one},
336 {"sh", "#!/bin/sh", "text/x-shellscript", one},
337 {"shp", fromDisk("shp.shp"), "application/vnd.shp", one},
338 {"shx", "\x00\x00\x27\x0a", "application/vnd.shx", one},
339 {"so", "\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00", "application/x-sharedlib", all},
340 {"sqlite", "SQLite format 3\x00", "application/vnd.sqlite3", one},
341 {"srt", "1\n00:02:16,612 --\x3e 00:02:19,376\nS", "application/x-subrip", one},
342 {"svg no xml header", `<svg xmlns="http://www.w3.org/2000/svg"`, "image/svg+xml", all},
343 {
344 "svg xml header",
345 `
346 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
347 <svg width="391" height="391" viewBox="-70.5 -70.5 391 391" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
348 <rect fill="#fff" stroke="#000" x="-70" y="-70" width="390" height="390"/>
349 </svg>
350 `,
351 "image/svg+xml",
352 all,
353 },
354 {
355 "svg with comment prefix",
356 `<!-- this comment should not affect --><svg xmlns="http://www.w3.org/2000/svg"`,
357 "image/svg+xml",
358 none,
359 },
360
361 {"swf", "CWS", "application/x-shockwave-flash", one},
362 {"tar", fromDisk("tar.tar"), "application/x-tar", all},
363 {"tcl", "#!/usr/bin/tcl", "text/x-tcl", one},
364 {"tcx", `<?xml version="1.0"?><TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">`, "application/vnd.garmin.tcx+xml", one},
365 {"tiff", "II*\x00", "image/tiff", one},
366 {"tsv", "a\t\"b\"\tc\n1\t2\t3", "text/tab-separated-values", all},
367 {"ttc", "ttcf\x00\x01\x00\x00", "font/collection", one},
368 {"ttf", "\x00\x01\x00\x00\x00\x0f\x00\x80\x00\x03\x00\x70\x4f\x53\x2f\x32", "font/ttf", one},
369 {"tzfile", fromDisk("tzfile"), "application/tzif", one},
370 {"utf16bebom txt", "\xfe\xff\x00\x74\x00\x68\x00\x69\x00\x73", "text/plain; charset=utf-16be", none},
371 {"utf16lebom txt", "\xff\xfe\x74\x00\x68\x00\x69\x00\x73\x00", "text/plain; charset=utf-16le", none},
372 {"utf32bebom txt", "\x00\x00\xfe\xff\x00\x00\x00\x74\x00\x00\x00\x68\x00\x00\x00\x69\x00\x00\x00\x73", "text/plain; charset=utf-32be", none},
373 {"utf32lebom txt", "\xff\xfe\x00\x00\x74\x00\x00\x00\x68\x00\x00\x00\x69\x00\x00\x00\x73\x00\x00\x00", "text/plain; charset=utf-32le", none},
374 {"utf8 txt", fromDisk("utf8.txt"), "text/plain; charset=utf-8", all},
375 {"utf8ctrlchars", "\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\x10", "application/octet-stream", none},
376 {"vcf", "BEGIN:VCARD\nV", "text/vcard", one},
377 {"vcf dos", "BEGIN:VCARD\r\nV", "text/vcard", none},
378 {"visio", "\x50\x4b\x03\x04\x14\x00\x00\x00\x00\x00\x83\x93\x11\x5b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x20\x00visio/", "application/vnd.ms-visio.drawing.main+xml", one},
379 {"voc", "Creative Voice File", "audio/x-unknown", one},
380 {"vtt", "WEBVTT", "text/vtt", one},
381 {"warc", "WARC/1.1", "application/warc", one},
382 {"wasm", "\x00asm", "application/wasm", one},
383 {"wav", "RIFF\xba\xa5\x04\x00WAVEf", "audio/wav", all},
384 {"webm", "\x1aE\xdf\xa3\x01\x00\x00\x00\x00\x00\x00\x1fB\x86\x81\x01B\xf7\x81\x01B\xf2\x81\x04B\xf3\x81\x08B\x82\x84webm", "video/webm", all},
385 {"webp", "RIFFhv\x00\x00WEBPV", "image/webp", all},
386 {"woff", "wOFF", "font/woff", one},
387 {"woff2", "wOF2", "font/woff2", one},
388 {"wpd", "\xffWPC____\x01\x0a", "application/vnd.wordperfect", one},
389 {"x3d", `<?xml version="1.0"?><X3D xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance">`, "model/x3d+xml", one},
390 {"xar", "xar!", "application/x-xar", one},
391 {"xcf", "gimp xcf", "image/x-xcf", one},
392 {"xfdf", `<?xml version="1.0"?><xfdf xmlns="http://ns.adobe.com/xfdf/">`, "application/vnd.adobe.xfdf", one},
393 {"xhtml1", `<?xml version="1.0"?><!DOCTYPE html`, "application/xhtml+xml", one},
394 {"xhtml2", `<?xml version="1.0"?><HtMl XMLNS=`, "application/xhtml+xml", none},
395 {"xlf", `<?xml version="1.0"?><xliff xmlns="urn:oasis:names:tc:xliff:document:1.2">`, "application/x-xliff+xml", one},
396 {"xlsx", fromDisk("xlsx.xlsx"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", all},
397 {"xml", "<?xml ", "text/xml; charset=utf-8", all},
398 {"xml withbr", "\x0D\x0A<?xml ", "text/xml; charset=utf-8", none},
399 {"xz", "\xfd7zXZ\x00", "application/x-xz", one},
400 {"zip", "PK\x03\x04", "application/zip", all},
401 // The word Hi compressed with zlib: echo Hi | pigz -z | od -A n -t x1
402 {"zlib", "\x78\x5e\xf3\xc8\xe4\x02\x00\x01\xb7\x00\xbc", "application/zlib", one},
403 {"zst", "(\xb5/\xfd", "application/zstd", all},
404 {"zst skippable frame", "\x50\x2A\x4D\x18", "application/zstd", none},
405 {"gedcom", "0 HEAD\r\n1 GEDC\r\n2 VERS 5.5.5\r\n2 FORM LINEAGE-LINKED", "text/vnd.familysearch.gedcom", none},
406 }
407
408 func TestDetect(t *testing.T) {
409 for _, tc := range testcases {
410 t.Run(tc.name, func(t *testing.T) {
411 if mtype := Detect([]byte(tc.data)); mtype.String() != tc.expectedMIME {
412 t.Errorf("Detect: Expected: %s != Detected: %s", tc.expectedMIME, mtype.String())
413 }
414 if mtype, err := DetectReader(strings.NewReader(tc.data)); err != nil {
415 t.Errorf("DetectReader: unexpected error: %s", err)
416 } else if mtype.String() != tc.expectedMIME {
417 t.Errorf("DetectReader: Expected: %s != Detected: %s", tc.expectedMIME, mtype.String())
418 }
419 })
420 }
421 }
422
423 func TestDetectWonkyReaders(t *testing.T) {
424 wonkyReaders := map[string]func(io.Reader) io.Reader{
425 "DataErrReader": iotest.DataErrReader,
426 "HalfReader": iotest.HalfReader,
427 "OneByteReader": iotest.OneByteReader,
428 }
429
430 data := []byte(`
431 <!DOCTYPE html>
432 <html lang="en">
433 <head>
434 <meta charset="utf-8">
435 </head>
436
437 <body>
438 </body>
439 </html>`)
440
441 for name, reader := range wonkyReaders {
442 t.Run(name, func(t *testing.T) {
443 wr := reader(bytes.NewReader(data))
444 if mtype, err := DetectReader(wr); err != nil {
445 t.Errorf("Unexpected error: %s", err)
446 } else if expect := "text/html; charset=utf-8"; mtype.String() != expect {
447 t.Errorf("Expected: %s != Detected: %s", expect, mtype.String())
448 }
449 })
450 }
451 }
452
453 // This test generates the doc file containing the table with the supported MIMEs.
454 func TestGenerateSupportedFormats(t *testing.T) {
455 if testing.Short() {
456 t.Skip()
457 }
458 f, err := os.Create("supported_mimes.md")
459 if err != nil {
460 t.Fatal(err)
461 }
462 defer f.Close()
463
464 nodes := root.flatten()
465 header := fmt.Sprintf(`## %d Supported MIME types
466 This file is automatically generated when running tests. Do not edit manually.
467
468 Extension | MIME type <br> Aliases | Hierarchy
469 --------- | ---------------------- | ---------
470 `, len(nodes))
471
472 if _, err := f.WriteString(header); err != nil {
473 t.Fatal(err)
474 }
475 for _, n := range nodes {
476 ext := n.extension
477 if ext == "" {
478 ext = "n/a"
479 }
480
481 mimeColum := fmt.Sprintf("**%s**", n.mime)
482 if len(n.aliases) > 0 {
483 mimeColum = fmt.Sprintf("**%s** <br> %s", n.mime, strings.Join(n.aliases, ", "))
484 }
485 str := fmt.Sprintf("**%s** | %s | %s\n", ext, mimeColum, n.hierarchy())
486 if _, err := f.WriteString(str); err != nil {
487 t.Fatal(err)
488 }
489 }
490 }
491
492 func TestEqualsAny(t *testing.T) {
493 type ss []string
494 testCases := []struct {
495 m1 string
496 m2 ss
497 res bool
498 }{
499 {"foo/bar", ss{"foo/bar"}, true},
500 {" foo/bar", ss{"foo/bar "}, true}, // whitespace
501 {" foo/bar", ss{"foo/BAR "}, true}, // case
502 {" foo/bar", ss{"foo/baz"}, false},
503 {";charset=utf-8", ss{""}, true},
504 {"", ss{"", "foo/bar"}, true},
505 {"foo/bar", ss{""}, false},
506 {"foo/bar", nil, false},
507 }
508 for _, tc := range testCases {
509 if EqualsAny(tc.m1, tc.m2...) != tc.res {
510 t.Errorf("Equality test failed for %+v", tc)
511 }
512 }
513 }
514
515 func TestFaultyInput(t *testing.T) {
516 inexistent := "inexistent.file"
517 if mtype, err := DetectFile(inexistent); err == nil {
518 t.Errorf("%s should not match successfully", inexistent)
519 } else if mtype.String() != "application/octet-stream" {
520 t.Errorf("inexistent.file expected application/octet-stream, got %s", mtype)
521 }
522
523 f, _ := os.Open(inexistent)
524 if mtype, err := DetectReader(f); err == nil {
525 t.Errorf("%s reader should not match successfully", inexistent)
526 } else if mtype.String() != "application/octet-stream" {
527 t.Errorf("inexistent.file reader expected application/octet-stream, got %s", mtype)
528 }
529 }
530
531 func TestHierarchy(t *testing.T) {
532 detectedMIME := Detect([]byte("<html></html>"))
533 expected := []string{
534 "text/html; charset=utf-8",
535 "text/plain",
536 "application/octet-stream",
537 }
538
539 got := []string{}
540 for mtype := detectedMIME; mtype != nil; mtype = mtype.Parent() {
541 got = append(got, mtype.String())
542 }
543 if le, lg := len(expected), len(got); le != lg {
544 t.Fatalf("hierarchy len error; expected: %d, got: %d", le, lg)
545 }
546
547 for i := range expected {
548 if expected[i] != got[i] {
549 t.Fatalf("hierarchy error; expected: %s, got: %s", expected, got)
550 }
551 }
552 }
553
554 func TestConcurrent(t *testing.T) {
555 if testing.Short() {
556 t.Skip()
557 }
558 wg := sync.WaitGroup{}
559 wg.Add(4)
560
561 n := uint32(1000)
562 Extend(func([]byte, uint32) bool { return false }, "e", ".e")
563 go func() {
564 for i := uint32(0); i < n; i++ {
565 Detect([]byte("text content"))
566 }
567 wg.Done()
568 }()
569 go func() {
570 for i := uint32(0); i < n; i++ {
571 SetLimit(5000 + i)
572 }
573 wg.Done()
574 }()
575 go func() {
576 for i := uint32(0); i < n; i++ {
577 Lookup("text/plain")
578 }
579 wg.Done()
580 }()
581 go func() {
582 for i := uint32(0); i < n; i++ {
583 Lookup("e").Extend(func([]byte, uint32) bool { return false }, "e", ".e")
584 }
585 wg.Done()
586 }()
587
588 wg.Wait()
589 // Reset to the original limit and MIME tree structure for benchmarks.
590 SetLimit(defaultLimit)
591 root.children = root.children[1:]
592 }
593
594 // For #162.
595 func TestEmptyInput(t *testing.T) {
596 mtype, err := DetectReader(bytes.NewReader(nil))
597 if err != nil {
598 t.Fatalf("empty reader err; expected: nil, got: %s", err)
599 }
600 plain := "text/plain"
601 if !mtype.Is(plain) {
602 t.Fatalf("empty reader detection; expected: %s, got: %s", plain, mtype)
603 }
604 mtype = Detect(nil)
605 if !mtype.Is(plain) {
606 t.Fatalf("empty bytes slice detection; expected: %s, got: %s", plain, mtype)
607 }
608 SetLimit(0)
609 mtype, err = DetectReader(bytes.NewReader(nil))
610 if err != nil {
611 t.Fatalf("0 limіt, empty reader err; expected: nil, got: %s", err)
612 }
613 if !mtype.Is(plain) {
614 t.Fatalf("0 limit, empty reader detection; expected: %s, got: %s", plain, mtype)
615 }
616 SetLimit(defaultLimit)
617 }
618
619 func BenchmarkOne(b *testing.B) {
620 r := rand.New(rand.NewSource(0))
621 // randData is used for the negative case benchmark.
622 randData := make([]byte, defaultLimit)
623 if _, err := io.ReadFull(r, randData); err != io.ErrUnexpectedEOF && err != nil {
624 b.Fatal(err)
625 }
626
627 for _, tc := range testcases {
628 if shouldRun := tc.bench == one || tc.bench == all; !shouldRun {
629 continue
630 }
631 data := []byte(tc.data)
632 parsed, _, _ := mime.ParseMediaType(tc.expectedMIME)
633 mtype := Lookup(parsed)
634 if mtype == nil || mtype.detector == nil {
635 b.Fatalf("mime should always be non-nil %s %s", mtype, tc.expectedMIME)
636 }
637 // data is used for the positive case benchmark.
638 b.Run(tc.name, func(b *testing.B) {
639 b.ReportAllocs()
640 for b.Loop() {
641 if !mtype.detector(data, defaultLimit) {
642 b.Fatalf("positive detection should never fail")
643 }
644 if mtype.detector(randData, defaultLimit) {
645 b.Fatalf("negative detection should always fail")
646 }
647 }
648 })
649 }
650 }
651
652 func BenchmarkAll(b *testing.B) {
653 r := rand.New(rand.NewSource(0))
654 // randData is used for the negative case benchmark.
655 randData := make([]byte, defaultLimit)
656 if _, err := io.ReadFull(r, randData); err != io.ErrUnexpectedEOF && err != nil {
657 b.Fatal(err)
658 }
659 for _, tc := range testcases {
660 if tc.bench != all {
661 continue
662 }
663 data := []byte(tc.data)
664 b.Run(tc.name, func(b *testing.B) {
665 b.ReportAllocs()
666 for b.Loop() {
667 // Benchmark both positive and negative.
668 Detect(data)
669 Detect(randData)
670 }
671 })
672 }
673 }
674
675 func BenchmarkAllTogether(b *testing.B) {
676 r := rand.New(rand.NewSource(0))
677 // randData is used for the negative case benchmark.
678 randData := make([]byte, defaultLimit)
679 if _, err := io.ReadFull(r, randData); err != io.ErrUnexpectedEOF && err != nil {
680 b.Fatal(err)
681 }
682 datas := make([][]byte, 0, len(testcases))
683 for _, tc := range testcases {
684 datas = append(datas, []byte(tc.data))
685 }
686 b.ResetTimer()
687 b.ReportAllocs()
688 for b.Loop() {
689 for _, d := range datas {
690 Detect(d)
691 Detect(randData)
692 }
693 }
694 }
695
696 // Check there are no panics for nil inputs and for truncated inputs.
697 func TestIndexOutOfRangePanic(t *testing.T) {
698 if testing.Short() {
699 t.Skip()
700 }
701 nodes := root.flatten()
702 testAtEachIndex := func(t *testing.T, in []byte) {
703 t.Helper()
704 for _, n := range nodes {
705 for i := 0; i < len(in); i++ {
706 n.detector(in[:i], 1<<10)
707 }
708 }
709 }
710
711 for _, tc := range testcases {
712 t.Run(tc.name, func(t *testing.T) {
713 testAtEachIndex(t, []byte(tc.data))
714 })
715 }
716 }
717
718 // MIME type equality ignores any optional MIME parameters, so, in order to not
719 // parse each alias when testing for equality, we must ensure they are
720 // registered with no parameters.
721 func TestMIMEFormat(t *testing.T) {
722 // Conventially, media types should be lower case, but exceptions exists.
723 // However, when testing equality, their lower case values should be used,
724 // regardless if they originally are lower or upper case.
725 // Up until now, all media types we registered have been lower case and
726 // without optional params. That helps to keep MIME.Is function simple.
727 // But, in the case we will add a MIME breaking the rule, we should know.
728 // That's the purpose of this test.
729 testNormalised := func(ms []string) {
730 for _, m := range ms {
731 normalised, _, err := mime.ParseMediaType(m)
732 if err != nil {
733 t.Errorf("error parsing %s: %s", m, err)
734 }
735 if m != normalised {
736 t.Errorf("registered MIME should be normalised: %s", m)
737 }
738 }
739 }
740 for _, n := range root.flatten() {
741 // All extensions must be dot prefixed so they are compatible
742 // with the stdlib mime package.
743 if n.Extension() != "" && !strings.HasPrefix(n.Extension(), ".") {
744 t.Errorf("extension %s should be dot prefixed", n.Extension())
745 }
746
747 testNormalised(append(n.aliases, n.String()))
748 }
749 }
750
751 func TestLookup(t *testing.T) {
752 data := []struct {
753 mime string
754 m *MIME
755 }{
756 {root.mime, root},
757 {zip.mime, zip},
758 {zip.aliases[0], zip},
759 {xlsx.mime, xlsx},
760 }
761
762 for _, tt := range data {
763 t.Run(fmt.Sprintf("lookup %s", tt.mime), func(t *testing.T) {
764 if m := Lookup(tt.mime); m != tt.m {
765 t.Fatalf("failed to lookup: %s", tt.mime)
766 }
767 })
768 }
769 }
770
771 func TestIs(t *testing.T) {
772 tcases := []struct {
773 name string
774 m *MIME
775 n string
776 expected bool
777 }{{
778 name: "mime matches",
779 m: &MIME{
780 mime: "text/xml",
781 aliases: []string{"application/xml"},
782 extension: ".xml",
783 },
784 n: "text/xml",
785 expected: true,
786 }, {
787 name: "alias matches",
788 m: &MIME{
789 mime: "text/xml",
790 aliases: []string{"application/xml"},
791 extension: ".xml",
792 },
793 n: "application/xml",
794 expected: true,
795 }, {
796 name: "mime matches because both m.mime and n are converted to lower case",
797 m: &MIME{
798 mime: "Text/xml",
799 aliases: []string{"application/xml"},
800 extension: ".xml",
801 },
802 n: "tEXT/XML",
803 expected: true,
804 }, {
805 name: "alias matches because n is converted to lower case",
806 m: &MIME{
807 mime: "text/xml",
808 aliases: []string{"application/xml"},
809 extension: ".xml",
810 },
811 n: "Application/xml",
812 expected: true,
813 }, {
814 name: "alias does not match because aliases are not converted to lower case",
815 m: &MIME{
816 mime: "text/xml",
817 aliases: []string{"Application/xml"},
818 extension: ".xml",
819 },
820 n: "Application/xml",
821 expected: false,
822 }, {
823 name: "empty string does not match anything",
824 m: &MIME{
825 mime: "text/xml",
826 aliases: []string{"application/xml"},
827 extension: ".xml",
828 },
829 n: "",
830 expected: false,
831 }}
832
833 for _, tc := range tcases {
834 t.Run(tc.name, func(t *testing.T) {
835 got := tc.m.Is(tc.n)
836 if got != tc.expected {
837 t.Errorf("expected: %t, got: %t", tc.expected, got)
838 }
839 })
840 }
841 }
842
843 func TestExtend(t *testing.T) {
844 data := []struct {
845 mime string
846 ext string
847 parent *MIME
848 }{
849 {"foo", ".foo", nil},
850 {"bar", ".bar", root},
851 {"baz", ".baz", zip},
852 {" UperCaseWithWhiteSpace/a+B; key=val ", ".upercase", nil},
853 }
854
855 for _, tt := range data {
856 t.Run(fmt.Sprintf("extending to %s", tt.mime), func(t *testing.T) {
857 extend := Extend
858 if tt.parent != nil {
859 extend = tt.parent.Extend
860 } else {
861 tt.parent = root
862 }
863
864 extend(func(raw []byte, limit uint32) bool { return false }, tt.mime, tt.ext)
865 m := Lookup(tt.mime)
866 if m == nil {
867 t.Fatalf("mime %s not found", tt.mime)
868 }
869 if m.parent != tt.parent {
870 t.Fatalf("mime %s has wrong parent: want %s, got %s", tt.mime, tt.parent.mime, m.parent.mime)
871 }
872 // Revert the Extend to restore previous MIME tree structure.
873 tt.parent.children = tt.parent.children[1:]
874 })
875 }
876 }
877
878 // Because of the random nature of fuzzing I don't think there is a way to test
879 // the correctness of the Detect results. Still there is value in fuzzing in
880 // search for panics.
881 func FuzzMimetype(f *testing.F) {
882 for _, tc := range testcases {
883 if tc.bench == one || tc.bench == all {
884 f.Add([]byte(tc.data), true)
885 }
886 }
887 // First node is root. Remove it because it matches any input.
888 detectors := root.flatten()[1:]
889 f.Fuzz(func(t *testing.T, data []byte, truncate bool) {
890 matched := false
891 limit := uint32(0)
892 if truncate {
893 limit = uint32(len(data)) //nolint:gosec
894 }
895 for _, d := range detectors {
896 if d.detector(data, limit) {
897 matched = true
898 }
899 }
900 if !matched {
901 t.Skip()
902 }
903 })
904 }
905
906 // For #680.
907 func TestInputIsNotMutated(t *testing.T) {
908 for _, tc := range testcases {
909 t.Run(tc.name, func(t *testing.T) {
910 passedBytes := []byte(tc.data)
911 Detect(passedBytes)
912
913 if pbs := string(passedBytes); pbs != tc.data {
914 t.Errorf("input should not be mutated; before: %s, after: %s", tc.data, pbs)
915 }
916 })
917 }
918 }
919
920 // For #744
921 func TestNDJSONCutOnSecondLine(t *testing.T) {
922 data := []byte(`{"key": "this json line has 43 characters"}
923 {"key": "this json line has 43 characters"}`)
924 SetLimit(uint32(len(data))) //nolint:gosec
925 mtype := Detect(data)
926 if !mtype.Is("application/x-ndjson") {
927 t.Errorf("expected nd-json two lines of JSON; got: %s", mtype)
928 }
929
930 SetLimit(43 + 43/2)
931 mtype = Detect(data)
932 if !mtype.Is("application/x-ndjson") {
933 t.Errorf("expected nd-json for one and a half lines of JSON; got: %s", mtype)
934 }
935 SetLimit(defaultLimit)
936 }
937
938 const (
939 // none means the testcase will not be benchmarked.
940 none = "none"
941 // one means just the detector function will be called for the testcase.
942 // For example: .txt input will be fed into .txt detector.
943 one = "one"
944 // all means all the detector functions will be called for the testcase.
945 // For example: .txt input will be fed into all detectors.
946 all = "all"
947 )
948
949 // offset prepends n nul bytes to s.
950 func offset(n int, s string) string {
951 prepend := make([]byte, n)
952 return string(prepend) + s
953 }
954 func fromDisk(path string) string {
955 data, err := os.ReadFile("testdata/" + path)
956 if err != nil {
957 panic(err)
958 }
959 return string(data)
960 }
961
962 // Ensure the signatures of exposed APIs don't accidentally change.
963 var (
964 _ func([]byte) *MIME = Detect
965 _ func(io.Reader) (*MIME, error) = DetectReader
966 _ func(string) (*MIME, error) = DetectFile
967 _ func(string, ...string) bool = EqualsAny
968 _ func(uint32) = SetLimit
969 _ func(string) *MIME = Lookup
970 m = &MIME{}
971 _ func() string = m.String
972 _ func() string = m.Extension
973 _ func() *MIME = m.Parent
974 _ func(string) bool = m.Is
975
976 _ func(func([]byte, uint32) bool, string, string, ...string) = Extend
977 _ func(func([]byte, uint32) bool, string, string, ...string) = m.Extend
978 )