1+ from bo import FileOperation
2+ import os
3+ from unittest .mock import patch , mock_open , MagicMock
4+
5+ class TestFileOperation ():
6+
7+ def test_on_init (self ):
8+ """
9+ This method is called when the operation is initialized.
10+ """
11+ # Create a FileOperation instance
12+ operation = FileOperation ()
13+
14+ # Set the path attribute
15+ operation .path = "/path/to/directory"
16+
17+ # Use a context manager to temporarily change the current working directory
18+ with patch .object (os , "chdir" ) as mock_chdir :
19+ # Call the on_init method
20+ operation .on_init ()
21+
22+ # Assert that the chdir function was called with the correct argument
23+ mock_chdir .assert_called_once_with ("/path/to/directory" )
24+
25+ @patch ('bo.FileOperation.put_line' )
26+ def test_on_post_message (self , mock_put_line ):
27+ # Create a mock PostMessage object
28+ post_message = MagicMock ()
29+ post_message .post .title = "Test Title"
30+ post_message .post .author = "Test Author"
31+ post_message .post .url = "http://test.com"
32+ post_message .post .selftext = "Test Text"
33+ post_message .found = "Test Company"
34+
35+ # Create a FileOperation object and call the on_post_message method with the mock PostMessage object
36+ file_operation = FileOperation ()
37+ file_operation .on_post_message (post_message )
38+
39+ # assert that the put_line has been called 4 times
40+ assert mock_put_line .call_count == 4
41+
42+ # assert that the put_line has been called with the correct arguments
43+ mock_put_line .call_args_list [0 ][0 ][0 ] == "Test Company.txt"
44+ mock_put_line .call_args_list [0 ][0 ][1 ] == '1970-01-01 01:00:01 : Test Title : Test Author : http://test.com'
45+ mock_put_line .call_args_list [1 ][0 ][0 ] == "Test Company.txt"
46+ mock_put_line .call_args_list [1 ][0 ][1 ] == ""
47+ mock_put_line .call_args_list [2 ][0 ][0 ] == "Test Company.txt"
48+ mock_put_line .call_args_list [2 ][0 ][1 ] == "Test Text"
49+ mock_put_line .call_args_list [3 ][0 ][0 ] == "Test Company.txt"
50+ mock_put_line .call_args_list [3 ][0 ][1 ] == ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *'
51+
52+ def test_put_line (self ):
53+ # create a mock file object
54+ m = mock_open ()
55+
56+ # patch the built-in open function with the mock object
57+ with patch ('builtins.open' , m ):
58+ # call the function with some test data
59+ filename = 'test.txt'
60+ string = 'hello world'
61+ FileOperation ().put_line (filename , string )
62+
63+ # check if the mock file object was called with the expected arguments
64+ m .assert_called_once_with (filename , 'a' , encoding = 'utf-8' )
65+ handle = m ()
66+ handle .write .assert_called_once_with (string )
0 commit comments