libmagic_test.py 1.5 KB

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