【发布时间】:2020-02-21 06:45:31
【问题描述】:
我正在尝试在修补 BeautifulSoup.select 时使用 assertRaises 测试异常。
从网页中获取 ID 的方法,采用 html resultsPage
def parseOutIds(resultsPage):
soup = BeautifulSoup(resultsPage, "html.parser")
records = soup.select('some-html-tags')
parsed = []
for record in records:
try:
ampData = json.loads(record["other-tags"])
parsed.append(ampData)
except json.decoder.JSONDecodeError from err # Missing coverage
return parsed
上面的辅助方法和测试。我正在提高ValueError,因为json.decoder.JSONDecodeError 基于此answer 继承自它。
def loadHtml(self, fileName):
with open('path/to/test'+filename) as f:
self.html = file.read().strip()
def test_parseOutIds(self):
self.loadHtml('test-html.html')
#errorMock method just raises ValueError exception
bsPatch = patch('bs4.BeautifulSoup.select', self.errorMock)
with bsPatch:
with self.assertRaises(ValueError):
parseOutIds(self.html)
我上面的当前测试缺少异常行的保险。
其他要点:
- 我也必须修补 json.load 吗?
- 根据我从其他答案中看到的情况,由于存在循环,我是否还模拟了另一种方法?
【问题讨论】:
标签: python json unit-testing beautifulsoup mocking