1 import imp 2 import os 3 import py_compile 4 import shutil 5 import tempfile 6 import unittest 7 8 from test import test_support 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.cwd_drive = os.path.splitdrive(os.getcwd())[0] 17 # In these tests we compute relative paths. When using Windows, the 18 # current working directory path and the 'self.source_path' might be 19 # on different drives. Therefore we need to switch to the drive where 20 # the temporary source file lives. 21 drive = os.path.splitdrive(self.source_path)[0] 22 if drive: 23 os.chdir(drive) 24 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) 30 if self.cwd_drive: 31 os.chdir(self.cwd_drive) 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 37 def test_cwd(self): 38 cwd = os.getcwd() 39 os.chdir(self.directory) 40 py_compile.compile(os.path.basename(self.source_path), 41 os.path.basename(self.pyc_path)) 42 os.chdir(cwd) 43 self.assertTrue(os.path.exists(self.pyc_path)) 44 45 def test_relative_path(self): 46 py_compile.compile(os.path.relpath(self.source_path), 47 os.path.relpath(self.pyc_path)) 48 self.assertTrue(os.path.exists(self.pyc_path)) 49 50 def test_main(): 51 test_support.run_unittest(PyCompileTests) 52 53 if __name__ == "__main__": 54 test_main() 55