|
| 1 | +# Copyright 2009-2014 Ram Rachum. |
| 2 | +# This program is distributed under the MIT license. |
| 3 | + |
| 4 | +import pathlib |
| 5 | + |
| 6 | +import python_toolbox |
| 7 | +from python_toolbox import temp_file_tools |
| 8 | + |
| 9 | +from python_toolbox import file_tools |
| 10 | + |
| 11 | + |
| 12 | +def test(): |
| 13 | + with temp_file_tools.TemporaryFolder(prefix='test_python_toolbox_') as \ |
| 14 | + temporary_folder: |
| 15 | + get_file_names_set = \ |
| 16 | + lambda: set(path.name for path in temporary_folder.glob('*')) |
| 17 | + assert not get_file_names_set() |
| 18 | + |
| 19 | + file_path = temporary_folder / 'meow.txt' |
| 20 | + string_to_write = "I'm a cat, hear me meow!" |
| 21 | + |
| 22 | + assert file_tools.write_to_file_renaming_if_taken( |
| 23 | + file_path, string_to_write) == len(string_to_write) |
| 24 | + |
| 25 | + with file_path.open('r') as file: |
| 26 | + assert file.read() == string_to_write |
| 27 | + |
| 28 | + assert get_file_names_set() == {'meow.txt'} |
| 29 | + |
| 30 | + |
| 31 | + assert file_tools.write_to_file_renaming_if_taken( |
| 32 | + file_path, string_to_write) == len(string_to_write) |
| 33 | + assert file_tools.write_to_file_renaming_if_taken( |
| 34 | + file_path, string_to_write) == len(string_to_write) |
| 35 | + assert file_tools.write_to_file_renaming_if_taken( |
| 36 | + file_path, string_to_write) == len(string_to_write) |
| 37 | + |
| 38 | + with (temporary_folder / 'meow (2).txt').open('r') as last_file_input: |
| 39 | + assert last_file_input.read() == string_to_write |
| 40 | + |
| 41 | + assert get_file_names_set() == {'meow.txt', 'meow (1).txt', |
| 42 | + 'meow (2).txt', 'meow (3).txt'} |
| 43 | + |
| 44 | + with file_tools.create_file_renaming_if_taken(file_path) as last_file: |
| 45 | + assert not last_file.closed |
| 46 | + last_file.write(string_to_write[:5]) |
| 47 | + last_file.write(string_to_write[5:]) |
| 48 | + |
| 49 | + assert last_file.closed |
| 50 | + |
| 51 | + assert get_file_names_set() == {'meow.txt', 'meow (1).txt', |
| 52 | + 'meow (2).txt', 'meow (3).txt', |
| 53 | + 'meow (4).txt'} |
| 54 | + |
| 55 | + with pathlib.Path(last_file.name).open('r') as last_file_input: |
| 56 | + assert last_file_input.read() == string_to_write |
| 57 | + |
0 commit comments