You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
2.4 KiB
66 lines
2.4 KiB
2 months ago
|
import unittest
|
||
|
from unittest.mock import patch # 使用 @patch 装饰器来模拟 requests.get 方法
|
||
|
import requests
|
||
|
from bullet_comments_crawler import get_bvid, get_cid, get_comment
|
||
|
|
||
|
class TestBulletCommentsCrawler(unittest.TestCase):
|
||
|
"""
|
||
|
测试 bullet_comments_crawler 模块中的函数。
|
||
|
"""
|
||
|
|
||
|
@patch('requests.get')
|
||
|
def test_get_bvid_valid(self, mock_get):
|
||
|
"""
|
||
|
测试 get_bvid 函数在接收到有效响应时的行为。
|
||
|
"""
|
||
|
mock_get.return_value.text = 'aid:1,bvid:"BV12XYZ",'
|
||
|
result = get_bvid('http://valid.url', {})
|
||
|
self.assertIn('BV12XYZ', result)
|
||
|
|
||
|
@patch('requests.get')
|
||
|
def test_get_bvid_invalid(self, mock_get):
|
||
|
"""
|
||
|
测试 get_bvid 函数在接收到无效响应时的行为。
|
||
|
"""
|
||
|
mock_get.side_effect = requests.exceptions.RequestException("Invalid URL")
|
||
|
result = get_bvid('http://invalid.url', {})
|
||
|
self.assertEqual(result, set())
|
||
|
|
||
|
@patch('requests.get')
|
||
|
def test_get_cid_valid(self, mock_get):
|
||
|
"""
|
||
|
测试 get_cid 函数在接收到有效 JSON 响应时的行为。
|
||
|
"""
|
||
|
mock_get.return_value.json.return_value = {'data': [{'cid': 111}]}
|
||
|
cid = get_cid('http://valid.api.url', {})
|
||
|
self.assertEqual(cid, 111)
|
||
|
|
||
|
@patch('requests.get')
|
||
|
def test_get_cid_invalid(self, mock_get):
|
||
|
"""
|
||
|
测试 get_cid 函数在接收到无效 JSON 响应时的行为。
|
||
|
"""
|
||
|
mock_get.return_value.json.return_value = {'data': []}
|
||
|
cid = get_cid('http://invalid.api.url', {})
|
||
|
self.assertIsNone(cid)
|
||
|
|
||
|
@patch('requests.get')
|
||
|
def test_get_comment_valid(self, mock_get):
|
||
|
"""
|
||
|
测试 get_comment 函数在接收到有效 XML 响应时的行为。
|
||
|
"""
|
||
|
mock_get.return_value.text = '<xml><d>弹幕1</d><d>弹幕2</d></xml>'
|
||
|
comments = get_comment('http://valid.comment.url', {})
|
||
|
self.assertEqual(comments, ['弹幕1', '弹幕2'])
|
||
|
|
||
|
@patch('requests.get')
|
||
|
def test_get_comment_invalid(self, mock_get):
|
||
|
"""
|
||
|
测试 get_comment 函数在接收到无效响应时的行为。
|
||
|
"""
|
||
|
mock_get.side_effect = requests.exceptions.RequestException("Invalid URL")
|
||
|
comments = get_comment('http://invalid.comment.url', {})
|
||
|
self.assertEqual(comments, [])
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
unittest.main()
|