Test writing to a filehandle using .writelines()
(self)
| 627 | ) |
| 628 | |
| 629 | def test_writelines(self): |
| 630 | """ |
| 631 | Test writing to a filehandle using .writelines() |
| 632 | """ |
| 633 | # Test opening for non-binary writing |
| 634 | with patch("salt.utils.files.fopen", mock_open()): |
| 635 | with salt.utils.files.fopen("foo.txt", "w") as self.fh: |
| 636 | self.fh.writelines(self.questions_str_lines) |
| 637 | assert self.fh.writelines_calls == [ |
| 638 | self.questions_str_lines |
| 639 | ], self.fh.writelines_calls |
| 640 | |
| 641 | # Test opening for binary writing using "wb" |
| 642 | with patch("salt.utils.files.fopen", mock_open(read_data=b"")): |
| 643 | with salt.utils.files.fopen("foo.txt", "wb") as self.fh: |
| 644 | self.fh.writelines(self.questions_bytes_lines) |
| 645 | assert self.fh.writelines_calls == [ |
| 646 | self.questions_bytes_lines |
| 647 | ], self.fh.writelines_calls |
| 648 | |
| 649 | # Test opening for binary writing using "ab" |
| 650 | with patch("salt.utils.files.fopen", mock_open(read_data=b"")): |
| 651 | with salt.utils.files.fopen("foo.txt", "ab") as self.fh: |
| 652 | self.fh.writelines(self.questions_bytes_lines) |
| 653 | assert self.fh.writelines_calls == [ |
| 654 | self.questions_bytes_lines |
| 655 | ], self.fh.writelines_calls |
| 656 | |
| 657 | # Test opening for read-and-write using "r+b" |
| 658 | with patch("salt.utils.files.fopen", mock_open(read_data=b"")): |
| 659 | with salt.utils.files.fopen("foo.txt", "r+b") as self.fh: |
| 660 | self.fh.writelines(self.questions_bytes_lines) |
| 661 | assert self.fh.writelines_calls == [ |
| 662 | self.questions_bytes_lines |
| 663 | ], self.fh.writelines_calls |
| 664 | |
| 665 | # Test trying to write str types to a binary filehandle |
| 666 | with patch("salt.utils.files.fopen", mock_open(read_data=b"")): |
| 667 | with salt.utils.files.fopen("foo.txt", "wb") as self.fh: |
| 668 | try: |
| 669 | self.fh.writelines(["foo\n"]) |
| 670 | except TypeError: |
| 671 | # This exception is expected on Python 3 |
| 672 | pass |
| 673 | else: |
| 674 | # This write should work fine on Python 2 |
| 675 | raise Exception( |
| 676 | "Should not have been able to write a str to a " |
| 677 | "binary filehandle" |
| 678 | ) |
| 679 | |
| 680 | # Test trying to write bytestrings to a non-binary filehandle |
| 681 | with patch("salt.utils.files.fopen", mock_open()): |
| 682 | with salt.utils.files.fopen("foo.txt", "w") as self.fh: |
| 683 | try: |
| 684 | self.fh.write([b"foo\n"]) |
| 685 | except TypeError: |
| 686 | # This exception is expected on Python 3 |
nothing calls this directly
no test coverage detected