用于Web Scraping的测试驱动开发(TDD)

Ale*_*son 8 python testing unit-testing web-scraping

摘要

我有一个基于Python的网络抓取宠物项目,我正在尝试实现一些TDD,但我很快就遇到了问题.单元测试需要互联网连接,以及下载html文本.虽然我知道实际的解析可以使用本地文件完成,但是一些方法用于简单地重新定义URL并再次查询网站.这似乎打破了TDD的一些最佳实践(引用:罗伯特·马丁的清洁代码声称测试应该在任何环境中都可以运行).虽然这是一个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())
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

Dir*_*ann 6

正如您所说,在 TDD 期间运行的测试必须运行得很快,还有其他方面,例如确定性等(那么,如果连接中断怎么办?)。正如评论中提到的,这通常意味着您必须对那些令人不安的依赖项使用模拟。

然而,这里有一个基本假设:即,您正在编写的代码可以通过单元测试进行明智的测试。这是什么意思?这意味着单元测试很有可能会发现错误。换句话说,如果极不可能通过单元测试找到错误,那么单元测试就不是正确的做法。

关于您的函数makeDataDictionary,它主要由对依赖项的调用组成。因此,集成测试(即检查您的代码如何与其使用的真实库交互的测试)似乎可能有助于发现错误:您的代码是否使用正确的参数正确调用了库?图书馆是否以您期望的方式实际提供结果?交互顺序是否正确?库的模拟不会回答这些问题:如果您对使用的库的假设是错误的,那么您将根据错误的假设来实现模拟。

另一方面,如果您从 中模拟出所有依赖项makeDataDictionary,您希望找到哪些错误?可能(在函数的最后一行)数据字典本身的创建可能是错误的(例如,键的名称错误)。因此,从我的角度来看,这条线是makeDataDictionary实际单元测试有意义的唯一部分。

因此,我在这种情况下的建议是首先将具有纯逻辑(算法代码)的代码与由交互主导的代码分开。例如,创建一个_makeDataDictionary(html, text, soup)除了 return 什么都不做的辅助方法{"html": html, "text": text, "soup": soup}。然后,将单元测试应用于_makeDataDictionary,而不是应用于makeDataDictionary。相比之下,makeDataDictionary使用集成测试进行测试。

这也节省了大量的模拟工作:对于单元测试_makeDataDictionary,不需要模拟。对于集成测试makeDataDictionary,模拟毫无意义。对于调用makeDataDictionary并应进行单元测试的代码,最好将调用makeDataDictionary作为一个整体进行存根,而不是替换其各个依赖项。

然而,在 TDD 上下文中,这有点难以处理:TDD 似乎没有一个不适合进行单元测试的代码概念。但是,通过适当的提前思考(也称为设计阶段),您可以及早认识到是否应该将算法代码与交互主导的代码分开。另一个例子,人们不应该被误导,认为 TDD 消除了对一些适当设计工作的需要。