libmagic_test.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # coding: utf-8
  2. import unittest
  3. import os
  4. import magic
  5. import os.path
  6. # magic_descriptor is broken (?) in centos 7, so don't run those tests
  7. SKIP_FROM_DESCRIPTOR = bool(os.environ.get('SKIP_FROM_DESCRIPTOR'))
  8. TESTDATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testdata'))
  9. class MagicTestCase(unittest.TestCase):
  10. filename = os.path.join(TESTDATA_DIR, 'test.pdf')
  11. expected_mime_type = 'application/pdf'
  12. expected_encoding = 'us-ascii'
  13. expected_name = ('PDF document, version 1.2', 'PDF document, version 1.2, 2 pages')
  14. def assert_result(self, result):
  15. self.assertEqual(result.mime_type, self.expected_mime_type)
  16. self.assertEqual(result.encoding, self.expected_encoding)
  17. self.assertIn(result.name, self.expected_name)
  18. def test_detect_from_filename(self):
  19. result = magic.detect_from_filename(self.filename)
  20. self.assert_result(result)
  21. def test_detect_from_fobj(self):
  22. if SKIP_FROM_DESCRIPTOR:
  23. self.skipTest("magic_descriptor is broken in this version of libmagic")
  24. with open(self.filename) as fobj:
  25. result = magic.detect_from_fobj(fobj)
  26. self.assert_result(result)
  27. def test_detect_from_content(self):
  28. # differ from upstream by opening file in binary mode,
  29. # this avoids hitting a bug in python3+libfile bindings
  30. # see https://github.com/ahupp/python-magic/issues/152
  31. # for a similar issue
  32. with open(self.filename, 'rb') as fobj:
  33. result = magic.detect_from_content(fobj.read(4096))
  34. self.assert_result(result)
  35. if __name__ == '__main__':
  36. unittest.main()