Home | History | Annotate | Download | only in modulegraph_tests
      1 import unittest
      2 import encodings
      3 import encodings.aliases
      4 from modulegraph import util
      5 import sys
      6 
      7 try:
      8     from io import BytesIO
      9 except ImportError:
     10     from cStringIO import StringIO as BytesIO
     11 
     12 class TestUtil (unittest.TestCase):
     13     def test_imp_find_module(self):
     14         fn = util.imp_find_module('encodings.aliases')[1]
     15         self.assertTrue(encodings.aliases.__file__.startswith(fn))
     16 
     17     def test_imp_walk(self):
     18         imps = list(util.imp_walk('encodings.aliases'))
     19         self.assertEqual(len(imps), 2)
     20 
     21         self.assertEqual(imps[0][0], 'encodings')
     22         self.assertTrue(encodings.__file__.startswith(imps[0][1][1]))
     23 
     24         self.assertEqual(imps[1][0], 'aliases')
     25         self.assertTrue(encodings.aliases.__file__.startswith(imps[1][1][1]))
     26 
     27         # Close all files, avoid warning by unittest
     28         for i in imps:
     29             if i[1][0] is not None:
     30                 i[1][0].close()
     31 
     32 
     33     def test_guess_encoding(self):
     34         fp = BytesIO(b"# coding: utf-8")
     35         self.assertEqual(util.guess_encoding(fp), "utf-8")
     36 
     37         fp = BytesIO(b"\n# coding: utf-8")
     38         self.assertEqual(util.guess_encoding(fp), "utf-8")
     39 
     40         fp = BytesIO(b"# coding: latin-1")
     41         self.assertEqual(util.guess_encoding(fp), "latin-1")
     42 
     43         fp = BytesIO(b"\n# coding: latin-1")
     44         self.assertEqual(util.guess_encoding(fp), "latin-1")
     45 
     46         fp = BytesIO(b"#!/usr/bin/env/python\n# vim: set fileencoding=latin-1 :")
     47         self.assertEqual(util.guess_encoding(fp), "latin-1")
     48 
     49         fp = BytesIO(b"\n\n\n# coding: latin-1")
     50         if sys.version_info[0] == 2:
     51             self.assertEqual(util.guess_encoding(fp), "ascii")
     52         else:
     53             self.assertEqual(util.guess_encoding(fp), "utf-8")
     54 
     55         del fp
     56 
     57 
     58 if __name__ == "__main__":
     59     unittest.main()
     60