我這樣做的方式是創建假響應,這種方式可以離線測試解析函數。但是你通過使用真實的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