Debian Codegraph @

mimetype_test.go

raw symbols ◀ ▶ SCIP
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 if tc.data == "debian-packaging-removed" {
411 continue
412 }
413 t.Run(tc.name, func(t *testing.T) {
414 if mtype := Detect([]byte(tc.data)); mtype.String() != tc.expectedMIME {
415 t.Errorf("Detect: Expected: %s != Detected: %s", tc.expectedMIME, mtype.String())
416 }
417 if mtype, err := DetectReader(strings.NewReader(tc.data)); err != nil {
418 t.Errorf("DetectReader: unexpected error: %s", err)
419 } else if mtype.String() != tc.expectedMIME {
420 t.Errorf("DetectReader: Expected: %s != Detected: %s", tc.expectedMIME, mtype.String())
421 }
422 })
423 }
424 }
425
426 func TestDetectWonkyReaders(t *testing.T) {
427 wonkyReaders := map[string]func(io.Reader) io.Reader{
428 "DataErrReader": iotest.DataErrReader,
429 "HalfReader": iotest.HalfReader,
430 "OneByteReader": iotest.OneByteReader,
431 }
432
433 data := []byte(`
434 <!DOCTYPE html>
435 <html lang="en">
436 <head>
437 <meta charset="utf-8">
438 </head>
439
440 <body>
441 </body>
442 </html>`)
443
444 for name, reader := range wonkyReaders {
445 t.Run(name, func(t *testing.T) {
446 wr := reader(bytes.NewReader(data))
447 if mtype, err := DetectReader(wr); err != nil {
448 t.Errorf("Unexpected error: %s", err)
449 } else if expect := "text/html; charset=utf-8"; mtype.String() != expect {
450 t.Errorf("Expected: %s != Detected: %s", expect, mtype.String())
451 }
452 })
453 }
454 }
455
456 // This test generates the doc file containing the table with the supported MIMEs.
457 func TestGenerateSupportedFormats(t *testing.T) {
458 if testing.Short() {
459 t.Skip()
460 }
461 f, err := os.Create("supported_mimes.md")
462 if err != nil {
463 t.Fatal(err)
464 }
465 defer f.Close()
466
467 nodes := root.flatten()
468 header := fmt.Sprintf(`## %d Supported MIME types
469 This file is automatically generated when running tests. Do not edit manually.
470
471 Extension | MIME type <br> Aliases | Hierarchy
472 --------- | ---------------------- | ---------
473 `, len(nodes))
474
475 if _, err := f.WriteString(header); err != nil {
476 t.Fatal(err)
477 }
478 for _, n := range nodes {
479 ext := n.extension
480 if ext == "" {
481 ext = "n/a"
482 }
483
484 mimeColum := fmt.Sprintf("**%s**", n.mime)
485 if len(n.aliases) > 0 {
486 mimeColum = fmt.Sprintf("**%s** <br> %s", n.mime, strings.Join(n.aliases, ", "))
487 }
488 str := fmt.Sprintf("**%s** | %s | %s\n", ext, mimeColum, n.hierarchy())
489 if _, err := f.WriteString(str); err != nil {
490 t.Fatal(err)
491 }
492 }
493 }
494
495 func TestEqualsAny(t *testing.T) {
496 type ss []string
497 testCases := []struct {
498 m1 string
499 m2 ss
500 res bool
501 }{
502 {"foo/bar", ss{"foo/bar"}, true},
503 {" foo/bar", ss{"foo/bar "}, true}, // whitespace
504 {" foo/bar", ss{"foo/BAR "}, true}, // case
505 {" foo/bar", ss{"foo/baz"}, false},
506 {";charset=utf-8", ss{""}, true},
507 {"", ss{"", "foo/bar"}, true},
508 {"foo/bar", ss{""}, false},
509 {"foo/bar", nil, false},
510 }
511 for _, tc := range testCases {
512 if EqualsAny(tc.m1, tc.m2...) != tc.res {
513 t.Errorf("Equality test failed for %+v", tc)
514 }
515 }
516 }
517
518 func TestFaultyInput(t *testing.T) {
519 inexistent := "inexistent.file"
520 if mtype, err := DetectFile(inexistent); err == nil {
521 t.Errorf("%s should not match successfully", inexistent)
522 } else if mtype.String() != "application/octet-stream" {
523 t.Errorf("inexistent.file expected application/octet-stream, got %s", mtype)
524 }
525
526 f, _ := os.Open(inexistent)
527 if mtype, err := DetectReader(f); err == nil {
528 t.Errorf("%s reader should not match successfully", inexistent)
529 } else if mtype.String() != "application/octet-stream" {
530 t.Errorf("inexistent.file reader expected application/octet-stream, got %s", mtype)
531 }
532 }
533
534 func TestHierarchy(t *testing.T) {
535 detectedMIME := Detect([]byte("<html></html>"))
536 expected := []string{
537 "text/html; charset=utf-8",
538 "text/plain",
539 "application/octet-stream",
540 }
541
542 got := []string{}
543 for mtype := detectedMIME; mtype != nil; mtype = mtype.Parent() {
544 got = append(got, mtype.String())
545 }
546 if le, lg := len(expected), len(got); le != lg {
547 t.Fatalf("hierarchy len error; expected: %d, got: %d", le, lg)
548 }
549
550 for i := range expected {
551 if expected[i] != got[i] {
552 t.Fatalf("hierarchy error; expected: %s, got: %s", expected, got)
553 }
554 }
555 }
556
557 func TestConcurrent(t *testing.T) {
558 if testing.Short() {
559 t.Skip()
560 }
561 wg := sync.WaitGroup{}
562 wg.Add(4)
563
564 n := uint32(1000)
565 Extend(func([]byte, uint32) bool { return false }, "e", ".e")
566 go func() {
567 for i := uint32(0); i < n; i++ {
568 Detect([]byte("text content"))
569 }
570 wg.Done()
571 }()
572 go func() {
573 for i := uint32(0); i < n; i++ {
574 SetLimit(5000 + i)
575 }
576 wg.Done()
577 }()
578 go func() {
579 for i := uint32(0); i < n; i++ {
580 Lookup("text/plain")
581 }
582 wg.Done()
583 }()
584 go func() {
585 for i := uint32(0); i < n; i++ {
586 Lookup("e").Extend(func([]byte, uint32) bool { return false }, "e", ".e")
587 }
588 wg.Done()
589 }()
590
591 wg.Wait()
592 // Reset to the original limit and MIME tree structure for benchmarks.
593 SetLimit(defaultLimit)
594 root.children = root.children[1:]
595 }
596
597 // For #162.
598 func TestEmptyInput(t *testing.T) {
599 mtype, err := DetectReader(bytes.NewReader(nil))
600 if err != nil {
601 t.Fatalf("empty reader err; expected: nil, got: %s", err)
602 }
603 plain := "text/plain"
604 if !mtype.Is(plain) {
605 t.Fatalf("empty reader detection; expected: %s, got: %s", plain, mtype)
606 }
607 mtype = Detect(nil)
608 if !mtype.Is(plain) {
609 t.Fatalf("empty bytes slice detection; expected: %s, got: %s", plain, mtype)
610 }
611 SetLimit(0)
612 mtype, err = DetectReader(bytes.NewReader(nil))
613 if err != nil {
614 t.Fatalf("0 limÑ–t, empty reader err; expected: nil, got: %s", err)
615 }
616 if !mtype.Is(plain) {
617 t.Fatalf("0 limit, empty reader detection; expected: %s, got: %s", plain, mtype)
618 }
619 SetLimit(defaultLimit)
620 }
621
622 func BenchmarkOne(b *testing.B) {
623 r := rand.New(rand.NewSource(0))
624 // randData is used for the negative case benchmark.
625 randData := make([]byte, defaultLimit)
626 if _, err := io.ReadFull(r, randData); err != io.ErrUnexpectedEOF && err != nil {
627 b.Fatal(err)
628 }
629
630 for _, tc := range testcases {
631 if shouldRun := tc.bench == one || tc.bench == all; !shouldRun {
632 continue
633 }
634 data := []byte(tc.data)
635 parsed, _, _ := mime.ParseMediaType(tc.expectedMIME)
636 mtype := Lookup(parsed)
637 if mtype == nil || mtype.detector == nil {
638 b.Fatalf("mime should always be non-nil %s %s", mtype, tc.expectedMIME)
639 }
640 // data is used for the positive case benchmark.
641 b.Run(tc.name, func(b *testing.B) {
642 b.ReportAllocs()
643 for b.Loop() {
644 if !mtype.detector(data, defaultLimit) {
645 b.Fatalf("positive detection should never fail")
646 }
647 if mtype.detector(randData, defaultLimit) {
648 b.Fatalf("negative detection should always fail")
649 }
650 }
651 })
652 }
653 }
654
655 func BenchmarkAll(b *testing.B) {
656 r := rand.New(rand.NewSource(0))
657 // randData is used for the negative case benchmark.
658 randData := make([]byte, defaultLimit)
659 if _, err := io.ReadFull(r, randData); err != io.ErrUnexpectedEOF && err != nil {
660 b.Fatal(err)
661 }
662 for _, tc := range testcases {
663 if tc.bench != all {
664 continue
665 }
666 data := []byte(tc.data)
667 b.Run(tc.name, func(b *testing.B) {
668 b.ReportAllocs()
669 for b.Loop() {
670 // Benchmark both positive and negative.
671 Detect(data)
672 Detect(randData)
673 }
674 })
675 }
676 }
677
678 func BenchmarkAllTogether(b *testing.B) {
679 r := rand.New(rand.NewSource(0))
680 // randData is used for the negative case benchmark.
681 randData := make([]byte, defaultLimit)
682 if _, err := io.ReadFull(r, randData); err != io.ErrUnexpectedEOF && err != nil {
683 b.Fatal(err)
684 }
685 datas := make([][]byte, 0, len(testcases))
686 for _, tc := range testcases {
687 datas = append(datas, []byte(tc.data))
688 }
689 b.ResetTimer()
690 b.ReportAllocs()
691 for b.Loop() {
692 for _, d := range datas {
693 Detect(d)
694 Detect(randData)
695 }
696 }
697 }
698
699 // Check there are no panics for nil inputs and for truncated inputs.
700 func TestIndexOutOfRangePanic(t *testing.T) {
701 if testing.Short() {
702 t.Skip()
703 }
704 nodes := root.flatten()
705 testAtEachIndex := func(t *testing.T, in []byte) {
706 t.Helper()
707 for _, n := range nodes {
708 for i := 0; i < len(in); i++ {
709 n.detector(in[:i], 1<<10)
710 }
711 }
712 }
713
714 for _, tc := range testcases {
•715 if tc.data == "debian-packaging-removed" {
716 continue
717 }
718 t.Run(tc.name, func(t *testing.T) {
719 testAtEachIndex(t, []byte(tc.data))
720 })
721 }
722 }
723
724 // MIME type equality ignores any optional MIME parameters, so, in order to not
725 // parse each alias when testing for equality, we must ensure they are
726 // registered with no parameters.
727 func TestMIMEFormat(t *testing.T) {
728 // Conventially, media types should be lower case, but exceptions exists.
729 // However, when testing equality, their lower case values should be used,
730 // regardless if they originally are lower or upper case.
731 // Up until now, all media types we registered have been lower case and
732 // without optional params. That helps to keep MIME.Is function simple.
733 // But, in the case we will add a MIME breaking the rule, we should know.
734 // That's the purpose of this test.
735 testNormalised := func(ms []string) {
736 for _, m := range ms {
737 normalised, _, err := mime.ParseMediaType(m)
738 if err != nil {
739 t.Errorf("error parsing %s: %s", m, err)
740 }
741 if m != normalised {
742 t.Errorf("registered MIME should be normalised: %s", m)
743 }
744 }
745 }
746 for _, n := range root.flatten() {
747 // All extensions must be dot prefixed so they are compatible
748 // with the stdlib mime package.
749 if n.Extension() != "" && !strings.HasPrefix(n.Extension(), ".") {
750 t.Errorf("extension %s should be dot prefixed", n.Extension())
751 }
752
753 testNormalised(append(n.aliases, n.String()))
754 }
755 }
756
757 func TestLookup(t *testing.T) {
758 data := []struct {
759 mime string
760 m *MIME
761 }{
762 {root.mime, root},
763 {zip.mime, zip},
764 {zip.aliases[0], zip},
765 {xlsx.mime, xlsx},
766 }
767
768 for _, tt := range data {
769 t.Run(fmt.Sprintf("lookup %s", tt.mime), func(t *testing.T) {
770 if m := Lookup(tt.mime); m != tt.m {
771 t.Fatalf("failed to lookup: %s", tt.mime)
772 }
773 })
774 }
775 }
776
777 func TestIs(t *testing.T) {
778 tcases := []struct {
779 name string
780 m *MIME
781 n string
782 expected bool
783 }{{
784 name: "mime matches",
785 m: &MIME{
786 mime: "text/xml",
787 aliases: []string{"application/xml"},
788 extension: ".xml",
789 },
790 n: "text/xml",
791 expected: true,
792 }, {
793 name: "alias matches",
794 m: &MIME{
795 mime: "text/xml",
796 aliases: []string{"application/xml"},
797 extension: ".xml",
798 },
799 n: "application/xml",
800 expected: true,
801 }, {
802 name: "mime matches because both m.mime and n are converted to lower case",
803 m: &MIME{
804 mime: "Text/xml",
805 aliases: []string{"application/xml"},
806 extension: ".xml",
807 },
808 n: "tEXT/XML",
809 expected: true,
810 }, {
811 name: "alias matches because n is converted to lower case",
812 m: &MIME{
813 mime: "text/xml",
814 aliases: []string{"application/xml"},
815 extension: ".xml",
816 },
817 n: "Application/xml",
818 expected: true,
819 }, {
820 name: "alias does not match because aliases are not converted to lower case",
821 m: &MIME{
822 mime: "text/xml",
823 aliases: []string{"Application/xml"},
824 extension: ".xml",
825 },
826 n: "Application/xml",
827 expected: false,
828 }, {
829 name: "empty string does not match anything",
830 m: &MIME{
831 mime: "text/xml",
832 aliases: []string{"application/xml"},
833 extension: ".xml",
834 },
835 n: "",
836 expected: false,
837 }}
838
839 for _, tc := range tcases {
840 t.Run(tc.name, func(t *testing.T) {
841 got := tc.m.Is(tc.n)
842 if got != tc.expected {
843 t.Errorf("expected: %t, got: %t", tc.expected, got)
844 }
845 })
846 }
847 }
848
849 func TestExtend(t *testing.T) {
850 data := []struct {
851 mime string
852 ext string
853 parent *MIME
854 }{
855 {"foo", ".foo", nil},
856 {"bar", ".bar", root},
857 {"baz", ".baz", zip},
858 {" UperCaseWithWhiteSpace/a+B; key=val ", ".upercase", nil},
859 }
860
861 for _, tt := range data {
862 t.Run(fmt.Sprintf("extending to %s", tt.mime), func(t *testing.T) {
863 extend := Extend
864 if tt.parent != nil {
865 extend = tt.parent.Extend
866 } else {
867 tt.parent = root
868 }
869
870 extend(func(raw []byte, limit uint32) bool { return false }, tt.mime, tt.ext)
871 m := Lookup(tt.mime)
872 if m == nil {
873 t.Fatalf("mime %s not found", tt.mime)
874 }
875 if m.parent != tt.parent {
876 t.Fatalf("mime %s has wrong parent: want %s, got %s", tt.mime, tt.parent.mime, m.parent.mime)
877 }
878 // Revert the Extend to restore previous MIME tree structure.
879 tt.parent.children = tt.parent.children[1:]
880 })
881 }
882 }
883
884 // Because of the random nature of fuzzing I don't think there is a way to test
885 // the correctness of the Detect results. Still there is value in fuzzing in
886 // search for panics.
887 func FuzzMimetype(f *testing.F) {
888 for _, tc := range testcases {
889 if tc.bench == one || tc.bench == all {
890 f.Add([]byte(tc.data), true)
891 }
892 }
893 // First node is root. Remove it because it matches any input.
894 detectors := root.flatten()[1:]
895 f.Fuzz(func(t *testing.T, data []byte, truncate bool) {
896 matched := false
897 limit := uint32(0)
898 if truncate {
899 limit = uint32(len(data)) //nolint:gosec
900 }
901 for _, d := range detectors {
902 if d.detector(data, limit) {
903 matched = true
904 }
905 }
906 if !matched {
907 t.Skip()
908 }
909 })
910 }
911
912 // For #680.
913 func TestInputIsNotMutated(t *testing.T) {
914 for _, tc := range testcases {
915 t.Run(tc.name, func(t *testing.T) {
916 passedBytes := []byte(tc.data)
917 Detect(passedBytes)
918
919 if pbs := string(passedBytes); pbs != tc.data {
920 t.Errorf("input should not be mutated; before: %s, after: %s", tc.data, pbs)
921 }
922 })
923 }
924 }
925
926 // For #744
927 func TestNDJSONCutOnSecondLine(t *testing.T) {
928 data := []byte(`{"key": "this json line has 43 characters"}
929 {"key": "this json line has 43 characters"}`)
930 SetLimit(uint32(len(data))) //nolint:gosec
931 mtype := Detect(data)
932 if !mtype.Is("application/x-ndjson") {
933 t.Errorf("expected nd-json two lines of JSON; got: %s", mtype)
934 }
935
936 SetLimit(43 + 43/2)
937 mtype = Detect(data)
938 if !mtype.Is("application/x-ndjson") {
939 t.Errorf("expected nd-json for one and a half lines of JSON; got: %s", mtype)
940 }
941 SetLimit(defaultLimit)
942 }
943
944 const (
945 // none means the testcase will not be benchmarked.
946 none = "none"
947 // one means just the detector function will be called for the testcase.
948 // For example: .txt input will be fed into .txt detector.
949 one = "one"
950 // all means all the detector functions will be called for the testcase.
951 // For example: .txt input will be fed into all detectors.
952 all = "all"
953 )
954
955 // offset prepends n nul bytes to s.
956 func offset(n int, s string) string {
957 prepend := make([]byte, n)
958 return string(prepend) + s
959 }
•960
961 func fromDisk(path string) string {
962 data, err := os.ReadFile("testdata/" + path)
963 if err != nil {
•964 if strings.HasSuffix(err.Error(), "open testdata/"+path+": no such file or directory") {
965 fmt.Println(err.Error())
966 fmt.Println("(removed from Debian packaging)")
967 return "debian-packaging-removed"
968 }
969 panic(err)
970 }
971 return string(data)
972 }
973
974 // Ensure the signatures of exposed APIs don't accidentally change.
975 var (
976 _ func([]byte) *MIME = Detect
977 _ func(io.Reader) (*MIME, error) = DetectReader
978 _ func(string) (*MIME, error) = DetectFile
979 _ func(string, ...string) bool = EqualsAny
980 _ func(uint32) = SetLimit
981 _ func(string) *MIME = Lookup
982 m = &MIME{}
983 _ func() string = m.String
984 _ func() string = m.Extension
985 _ func() *MIME = m.Parent
986 _ func(string) bool = m.Is
987
988 _ func(func([]byte, uint32) bool, string, string, ...string) = Extend
989 _ func(func([]byte, uint32) bool, string, string, ...string) = m.Extend
990 )