You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
3.8 KiB

16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
  1. from . import util as source_util
  2. from importlib import _bootstrap
  3. import codecs
  4. import re
  5. import sys
  6. # Because sys.path gets essentially blanked, need to have unicodedata already
  7. # imported for the parser to use.
  8. import unicodedata
  9. import unittest
  10. CODING_RE = re.compile(r'coding[:=]\s*([-\w.]+)')
  11. class EncodingTest(unittest.TestCase):
  12. """PEP 3120 makes UTF-8 the default encoding for source code
  13. [default encoding].
  14. PEP 263 specifies how that can change on a per-file basis. Either the first
  15. or second line can contain the encoding line [encoding first line]
  16. encoding second line]. If the file has the BOM marker it is considered UTF-8
  17. implicitly [BOM]. If any encoding is specified it must be UTF-8, else it is
  18. an error [BOM and utf-8][BOM conflict].
  19. """
  20. variable = '\u00fc'
  21. character = '\u00c9'
  22. source_line = "{0} = '{1}'\n".format(variable, character)
  23. module_name = '_temp'
  24. def run_test(self, source):
  25. with source_util.create_modules(self.module_name) as mapping:
  26. with open(mapping[self.module_name], 'wb') as file:
  27. file.write(source)
  28. loader = _bootstrap.SourceFileLoader(self.module_name,
  29. mapping[self.module_name])
  30. return loader.load_module(self.module_name)
  31. def create_source(self, encoding):
  32. encoding_line = "# coding={0}".format(encoding)
  33. assert CODING_RE.search(encoding_line)
  34. source_lines = [encoding_line.encode('utf-8')]
  35. source_lines.append(self.source_line.encode(encoding))
  36. return b'\n'.join(source_lines)
  37. def test_non_obvious_encoding(self):
  38. # Make sure that an encoding that has never been a standard one for
  39. # Python works.
  40. encoding_line = "# coding=koi8-r"
  41. assert CODING_RE.search(encoding_line)
  42. source = "{0}\na=42\n".format(encoding_line).encode("koi8-r")
  43. self.run_test(source)
  44. # [default encoding]
  45. def test_default_encoding(self):
  46. self.run_test(self.source_line.encode('utf-8'))
  47. # [encoding first line]
  48. def test_encoding_on_first_line(self):
  49. encoding = 'Latin-1'
  50. source = self.create_source(encoding)
  51. self.run_test(source)
  52. # [encoding second line]
  53. def test_encoding_on_second_line(self):
  54. source = b"#/usr/bin/python\n" + self.create_source('Latin-1')
  55. self.run_test(source)
  56. # [BOM]
  57. def test_bom(self):
  58. self.run_test(codecs.BOM_UTF8 + self.source_line.encode('utf-8'))
  59. # [BOM and utf-8]
  60. def test_bom_and_utf_8(self):
  61. source = codecs.BOM_UTF8 + self.create_source('utf-8')
  62. self.run_test(source)
  63. # [BOM conflict]
  64. def test_bom_conflict(self):
  65. source = codecs.BOM_UTF8 + self.create_source('latin-1')
  66. with self.assertRaises(SyntaxError):
  67. self.run_test(source)
  68. class LineEndingTest(unittest.TestCase):
  69. r"""Source written with the three types of line endings (\n, \r\n, \r)
  70. need to be readable [cr][crlf][lf]."""
  71. def run_test(self, line_ending):
  72. module_name = '_temp'
  73. source_lines = [b"a = 42", b"b = -13", b'']
  74. source = line_ending.join(source_lines)
  75. with source_util.create_modules(module_name) as mapping:
  76. with open(mapping[module_name], 'wb') as file:
  77. file.write(source)
  78. loader = _bootstrap.SourceFileLoader(module_name,
  79. mapping[module_name])
  80. return loader.load_module(module_name)
  81. # [cr]
  82. def test_cr(self):
  83. self.run_test(b'\r')
  84. # [crlf]
  85. def test_crlf(self):
  86. self.run_test(b'\r\n')
  87. # [lf]
  88. def test_lf(self):
  89. self.run_test(b'\n')
  90. def test_main():
  91. from test.support import run_unittest
  92. run_unittest(EncodingTest, LineEndingTest)
  93. if __name__ == '__main__':
  94. test_main()