test_mimetypes.py 2.52 KB
Newer Older
1 2 3 4
import mimetypes
import StringIO
import unittest

5
from test import test_support
6 7 8

# Tell it we don't know about external files:
mimetypes.knownfiles = []
9
mimetypes.inited = False
10
mimetypes._default_mime_types()
11 12 13 14 15 16 17


class MimeTypesTestCase(unittest.TestCase):
    def setUp(self):
        self.db = mimetypes.MimeTypes()

    def test_default_data(self):
18 19 20 21 22
        eq = self.assertEqual
        eq(self.db.guess_type("foo.html"), ("text/html", None))
        eq(self.db.guess_type("foo.tgz"), ("application/x-tar", "gzip"))
        eq(self.db.guess_type("foo.tar.gz"), ("application/x-tar", "gzip"))
        eq(self.db.guess_type("foo.tar.Z"), ("application/x-tar", "compress"))
23 24

    def test_data_urls(self):
25 26 27 28 29
        eq = self.assertEqual
        guess_type = self.db.guess_type
        eq(guess_type("data:,thisIsTextPlain"), ("text/plain", None))
        eq(guess_type("data:;base64,thisIsTextPlain"), ("text/plain", None))
        eq(guess_type("data:text/x-foo,thisIsTextXFoo"), ("text/x-foo", None))
30 31

    def test_file_parsing(self):
32
        eq = self.assertEqual
33 34
        sio = StringIO.StringIO("x-application/x-unittest pyunit\n")
        self.db.readfp(sio)
35 36 37
        eq(self.db.guess_type("foo.pyunit"),
           ("x-application/x-unittest", None))
        eq(self.db.guess_extension("x-application/x-unittest"), ".pyunit")
38

39
    def test_non_standard_types(self):
40
        eq = self.assertEqual
Tim Peters's avatar
Tim Peters committed
41
        # First try strict
42 43
        eq(self.db.guess_type('foo.xul', strict=True), (None, None))
        eq(self.db.guess_extension('image/jpg', strict=True), None)
44
        # And then non-strict
45 46 47 48 49
        eq(self.db.guess_type('foo.xul', strict=False), ('text/xul', None))
        eq(self.db.guess_extension('image/jpg', strict=False), '.jpg')

    def test_guess_all_types(self):
        eq = self.assertEqual
50 51 52 53
        unless = self.failUnless
        # First try strict.  Use a set here for testing the results because if
        # test_urllib2 is run before test_mimetypes, global state is modified
        # such that the 'all' set will have more items in it.
54 55
        all = set(self.db.guess_all_extensions('text/plain', strict=True))
        unless(all >= set(['.bat', '.c', '.h', '.ksh', '.pl', '.txt']))
56 57 58 59 60 61 62
        # And now non-strict
        all = self.db.guess_all_extensions('image/jpg', strict=False)
        all.sort()
        eq(all, ['.jpg'])
        # And now for no hits
        all = self.db.guess_all_extensions('image/jpg', strict=True)
        eq(all, [])
63

64

65 66 67 68 69 70
def test_main():
    test_support.run_unittest(MimeTypesTestCase)


if __name__ == "__main__":
    test_main()