1#!/usr/bin/env python 2# 3# Copyright 2017 - The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17"""Unit test for gsi_util.utils.file_utils.""" 18 19import os 20import tempfile 21import unittest 22 23from gsi_util.utils import file_utils 24 25 26class UnopenedTemporaryFileTest(unittest.TestCase): 27 """Unit test for UnopenedTemporaryFile.""" 28 29 def test_normal(self): 30 with file_utils.UnopenedTemporaryFile( 31 prefix='prefix', suffix='suffix') as f: 32 self.assertTrue(os.path.exists(f)) 33 self.assertEqual(0, os.path.getsize(f)) 34 self.assertRegexpMatches(os.path.basename(f), r'prefix.+suffix') 35 self.assertEqual(tempfile.gettempdir(), os.path.dirname(f)) 36 self.assertFalse(os.path.exists(f)) 37 38 def test_remove_before_exit(self): 39 with file_utils.UnopenedTemporaryFile() as f: 40 self.assertTrue(os.path.exists(f)) 41 os.unlink(f) 42 self.assertFalse(os.path.exists(f)) 43 self.assertFalse(os.path.exists(f)) 44 45 def test_rename_before_exit(self): 46 with file_utils.UnopenedTemporaryFile() as f: 47 self.assertTrue(os.path.exists(f)) 48 new_name = f + '.new' 49 os.rename(f, new_name) 50 self.assertFalse(os.path.exists(f)) 51 self.assertFalse(os.path.exists(f)) 52 self.assertTrue(os.path.exists(new_name)) 53 os.unlink(new_name) 54 55 56if __name__ == '__main__': 57 unittest.main() 58