diff --git a/test_emotion_analysis.py b/test_emotion_analysis.py new file mode 100644 index 0000000..a8e040c --- /dev/null +++ b/test_emotion_analysis.py @@ -0,0 +1,36 @@ +import unittest +from unittest.mock import patch, mock_open +from emotion_analysis import emotion_aly + + +class TestEmotionAnalysis(unittest.TestCase): + # 测试 emotion_aly 函数在文件有数据时的反应 + @patch('builtins.open', new_callable=mock_open, read_data='这场比赛真的很棒!\nAI 技术越来越强大\n非常激动!') + @patch('os.path.exists', return_value=True) + @patch('matplotlib.pyplot.savefig') + @patch('matplotlib.pyplot.show') + @patch('matplotlib.pyplot.pie') + @patch('matplotlib.pyplot.tight_layout') + def test_emotion_aly(self, mock_tight_layout, mock_pie, mock_show, mock_savefig, mock_exists, mock_file): + search_word = "test_aly" + emotion_aly(search_word) + + # 验证 savefig 方法被调用 + mock_savefig.assert_called_once() + # 验证 pie 方法被调用 + mock_pie.assert_called_once() + + # 测试 emotion_aly 函数在文件为空时的反应 + @patch('builtins.open', new_callable=mock_open, read_data='') + @patch('os.path.exists', return_value=True) + @patch('matplotlib.pyplot.savefig') + @patch('matplotlib.pyplot.show') + def test_empty_file(self, mock_show, mock_savefig, mock_exists, mock_file): + search_word = "test_empty" + emotion_aly(search_word) + + # 验证在文件为空的情况下,不调用 savefig 方法 + mock_savefig.assert_not_called() + +if __name__ == "__main__": + unittest.main()