【发布时间】:2017-05-10 12:39:50
【问题描述】:
总结
我有一个Python based web scraping pet project,我正在尝试在其中实现一些 TDD,但我很快遇到了问题。单元测试需要互联网连接,以及下载 html 文本。虽然我知道实际的 解析 可以使用本地文件完成,但有些方法用于简单地重新定义 URL 并再次查询网站。这似乎打破了 TDD 的一些最佳实践(引用:Robert Martin 的 Clean Code 声称测试应该在任何环境中都可以运行)。虽然这是一个 Python 项目,但我在使用 R 进行 Yahoo Finance 抓取时遇到了类似的问题,我确信这种事情与语言无关。至少,这个问题似乎违反了 TDD 中的一个主要准则,即测试应该快速运行。
tldr;是否有在 TDD 中处理网络连接的最佳实践?
可重现的示例
AbstractScraper.py
from urllib.request import urlopen
from bs4 import BeautifulSoup
class AbstractScraper:
def __init__(self, url):
self.url = url
self.dataDictionary = None
def makeDataDictionary(self):
html = urlopen(self.url)
text = html.read().decode("utf-8")
soup = BeautifulSoup(text, "lxml")
self.dataDictionary = {"html": html, "text": text, "soup": soup}
def writeSoup(self, path):
with open(path, "w") as outfile:
outfile.write(self.dataDictionary["soup"].prettify())
TestAbstractScraper.py
import unittest
from http.client import HTTPResponse
from bs4 import BeautifulSoup
from CrackedScrapeProject.scrape.AbstractScraper import AbstractScraper
from io import StringIO
class TestAbstractScraperMethods(unittest.TestCase):
def setUp(self):
self.scraper = AbstractScraper("https://docs.python.org/2/library/unittest.html")
self.scraper.makeDataDictionary()
def test_dataDictionaryContents(self):
self.assertTrue(isinstance(self.scraper.dataDictionary, dict))
self.assertTrue(isinstance(self.scraper.dataDictionary["html"], HTTPResponse))
self.assertTrue(isinstance(self.scraper.dataDictionary["text"], str))
self.assertTrue(isinstance(self.scraper.dataDictionary["soup"], BeautifulSoup))
self.assertSetEqual(set(self.scraper.dataDictionary.keys()), set(["text", "soup", "html"]))
def test_writeSoup(self):
filePath = "C:/users/athompson/desktop/testFile.html"
self.scraper.writeSoup(filePath)
self.writtenData = open(filePath, "r").read()
self.assertEqual(self.writtenData, self.scraper.dataDictionary["soup"].prettify())
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestAbstractScraperMethods)
unittest.TextTestRunner(verbosity=2).run(suite)
【问题讨论】:
-
我建议模拟网络连接;那么您不仅不需要互联网连接,而且您可以绝对控制模拟连接返回的内容(然后您不会因网络故障和/或雅虎/等更改页面而导致虚假测试失败)。 docs.python.org/3/library/unittest.mock.html :) (当然,如果您尝试测试 yahoo/etc 没有更改页面,这将无济于事。)
-
单元测试从不需要任何连接。必须模拟测试单元之外的所有内容。测试连接可能在行为或集成测试中完成。
-
考虑从 bs 切换到 scrapy,它是一个强大的抓取工具,也可以自动化很多事情。此外,通过大量模块轻松学习。
标签: python unit-testing testing web-scraping