Meador Inge | 6f16660 | 2011-11-25 23:36:48 -0600 | [diff] [blame] | 1 | import imp |
| 2 | import os |
| 3 | import py_compile |
| 4 | import shutil |
| 5 | import tempfile |
| 6 | import unittest |
| 7 | |
| 8 | from test import support, script_helper |
| 9 | |
| 10 | class PyCompileTests(unittest.TestCase): |
| 11 | |
| 12 | def setUp(self): |
| 13 | self.directory = tempfile.mkdtemp() |
| 14 | self.source_path = os.path.join(self.directory, '_test.py') |
| 15 | self.pyc_path = self.source_path + 'c' |
| 16 | self.cache_path = imp.cache_from_source(self.source_path) |
Meador Inge | fb36b3f | 2011-11-26 11:37:02 -0600 | [diff] [blame] | 17 | self.cwd_drive = os.path.splitdrive(os.getcwd())[0] |
| 18 | # In these tests we compute relative paths. When using Windows, the |
| 19 | # current working directory path and the 'self.source_path' might be |
| 20 | # on different drives. Therefore we need to switch to the drive where |
| 21 | # the temporary source file lives. |
| 22 | drive = os.path.splitdrive(self.source_path)[0] |
| 23 | if drive: |
| 24 | os.chdir(drive) |
Meador Inge | 6f16660 | 2011-11-25 23:36:48 -0600 | [diff] [blame] | 25 | with open(self.source_path, 'w') as file: |
| 26 | file.write('x = 123\n') |
| 27 | |
| 28 | def tearDown(self): |
| 29 | shutil.rmtree(self.directory) |
Meador Inge | fb36b3f | 2011-11-26 11:37:02 -0600 | [diff] [blame] | 30 | if self.cwd_drive: |
| 31 | os.chdir(self.cwd_drive) |
Meador Inge | 6f16660 | 2011-11-25 23:36:48 -0600 | [diff] [blame] | 32 | |
| 33 | def test_absolute_path(self): |
| 34 | py_compile.compile(self.source_path, self.pyc_path) |
| 35 | self.assertTrue(os.path.exists(self.pyc_path)) |
| 36 | self.assertFalse(os.path.exists(self.cache_path)) |
| 37 | |
| 38 | def test_cache_path(self): |
| 39 | py_compile.compile(self.source_path) |
| 40 | self.assertTrue(os.path.exists(self.cache_path)) |
| 41 | |
Meador Inge | 22b9b37 | 2011-11-28 09:27:32 -0600 | [diff] [blame] | 42 | def test_cwd(self): |
| 43 | cwd = os.getcwd() |
| 44 | os.chdir(self.directory) |
| 45 | py_compile.compile(os.path.basename(self.source_path), |
| 46 | os.path.basename(self.pyc_path)) |
| 47 | os.chdir(cwd) |
| 48 | self.assertTrue(os.path.exists(self.pyc_path)) |
| 49 | self.assertFalse(os.path.exists(self.cache_path)) |
| 50 | |
Meador Inge | 6f16660 | 2011-11-25 23:36:48 -0600 | [diff] [blame] | 51 | def test_relative_path(self): |
| 52 | py_compile.compile(os.path.relpath(self.source_path), |
| 53 | os.path.relpath(self.pyc_path)) |
| 54 | self.assertTrue(os.path.exists(self.pyc_path)) |
| 55 | self.assertFalse(os.path.exists(self.cache_path)) |
| 56 | |
| 57 | def test_main(): |
| 58 | support.run_unittest(PyCompileTests) |
| 59 | |
| 60 | if __name__ == "__main__": |
| 61 | test_main() |