我这样做的方式是创建假响应,这种方式可以离线测试解析函数。但是你通过使用真实的HTML来获得真实的情况。
此方法的一个问题是您的本地HTML文件可能不会反映最新的状态在线。所以如果HTML在线改变,你可能会有一个大错误,但你的测试用例仍然会通过。所以这可能不是测试这种方式的最佳方式。
我目前的工作流程是,无论何时出现错误,我都会发送一封电子邮件给管理员,并附有网址。然后,对于那个特定的错误,我创建了一个html文件,其中包含导致错误的内容。然后我为它创建一个单元测试。
这是我使用从一个本地HTML文件创建用于测试样品Scrapy HTTP响应代码:
# scrapyproject/tests/responses/__init__.py
import os
from scrapy.http import Response, Request
def fake_response_from_file(file_name, url=None):
"""
Create a Scrapy fake HTTP response from a HTML file
@param file_name: The relative filename from the responses directory,
but absolute paths are also accepted.
@param url: The URL of the response.
returns: A scrapy HTTP response which can be used for unittesting.
"""
if not url:
url = 'http://www.example.com'
request = Request(url=url)
if not file_name[0] == '/':
responses_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(responses_dir, file_name)
else:
file_path = file_name
file_content = open(file_path, 'r').read()
response = Response(url=url,
request=request,
body=file_content)
response.encoding = 'utf-8'
return response
样本HTML文件位于scrapyproject /测试/响应/ osdir/sample.html
然后测试用例可以看看如下: 测试用例位置是scrapyproject /测试/ test_osdir.py
import unittest
from scrapyproject.spiders import osdir_spider
from responses import fake_response_from_file
class OsdirSpiderTest(unittest.TestCase):
def setUp(self):
self.spider = osdir_spider.DirectorySpider()
def _test_item_results(self, results, expected_length):
count = 0
permalinks = set()
for item in results:
self.assertIsNotNone(item['content'])
self.assertIsNotNone(item['title'])
self.assertEqual(count, expected_length)
def test_parse(self):
results = self.spider.parse(fake_response_from_file('osdir/sample.html'))
self._test_item_results(results, 10)
这是BASICA lly我如何测试我的解析方法,但它不仅用于解析方法。如果它变得更复杂,我建议看看Mox
离线测试尼斯的做法。如何运行离线测试以确保您没有代码缺陷,然后运行在线测试以确保网站更改不会破坏您的程序? – Medeiros
@Medeiros多数民众赞成在我现在正在另一个项目中做它的方式。我使用@ integration = 1标记测试,以便我不必始终运行所有测试。我正在用nosetest标签插件来做这件事。 –
@SamStoelinga我也可以测试真实的数据吗?如果是这样,我怎么能在单元测试中使用scrapy“获取”响应?我很想检查我的蜘蛛是否仍然收集来自变化方的所有信息。 – lony