[英]How to move the mock.patch to the setUp?
我有以下兩個單元測試:
@mock.patch('news.resources.generator.Generator.get_header')
@mock.patch('news.scraper.bbc_spider.BBCSpider.save_scraped_rss_into_news_model')
@mock.patch('news.scraper.bbc_spider.BBCSpider.get_news_urls')
@mock.patch('requests.get')
def test_get_header_is_called(self, req_get, spi_news, spi_save_rss, get_head):
spi_news.return_value = {'x': 1}
gen = Generator()
gen.get()
get_head.assert_called_with()
@mock.patch('news.resources.generator.Generator.get_header')
@mock.patch('news.scraper.bbc_spider.BBCSpider.save_scraped_rss_into_news_model')
@mock.patch('news.scraper.bbc_spider.BBCSpider.get_news_urls')
@mock.patch('requests.get')
def test_task_url_is_save_scraped_rss_into_news_model(self, req_get, spi_news, spi_save_rss, get_head):
spi_news.return_value = {'x': 1}
gen = Generator()
gen.get()
tasks = self.taskqueue_stub.GetTasks("newstasks")
self.assertEqual(tasks[0]['url'], '/v1/worker/save-scraped-rss-into-news-model')
如您所見,有很多代碼重復。 有沒有一種方法可以將模擬文件.patch移到setUp()?
Class TestGenerator(TestBase):
def setUp(self):
super(TestGenerator, self).setUp()
mock.patch() ???
def test_get_header_is_called(self, req_get, spi_news, spi_save_rss, get_head):
spi_news.return_value = {'x': 1}
gen = Generator()
gen.get()
get_head.assert_called_with()
def test_task_url_is_save_scraped_rss_into_news_model(self, req_get, spi_news, spi_save_rss, get_head):
spi_news.return_value = {'x': 1}
gen = Generator()
gen.get()
tasks = self.taskqueue_stub.GetTasks("newstasks")
self.assertEqual(tasks[0]['url'], '/v1/worker/save-scraped-rss-into-news-model')
您在這里有2個選項-首先,您可以將補丁移至該類:
@mock.patch('news.resources.generator.Generator.get_header')
@mock.patch('news.scraper.bbc_spider.BBCSpider.save_scraped_rss_into_news_model')
@mock.patch('news.scraper.bbc_spider.BBCSpider.get_news_urls')
@mock.patch('requests.get')
class TestGenerator(TestBase):
def test_get_header_is_called(self, req_get, spi_news, spi_save_rss, get_head):
pass
當您在類的mock.patch
家族中使用某些東西時,它的行為就像您分別修補了以“ test” 1開頭的每個方法一樣。
您的另一個選擇是在安裝程序中啟動修補程序。 在一個虛構的示例中(保存輸入),它看起來像這樣:
class SomeTest(TestCase):
def setUp(self):
super(SomeTest, self).setUp()
patch = mock.patch('foo.bar.baz')
mock_baz = patch.start() # may want to keep a reference to this if you need to do per-test configuration
self.addCleanup(patch.stop)
addCleanup
是在python2.7中添加的(太棒了!)。 如果您不需要較舊的python2.x版本,則應使用它,因為它比其他版本更健壯。 最簡單的選擇是僅停止tearDown中的所有修補程序:
class SomeTest(TestCase):
def setUp(self):
super(SomeTest, self).setUp()
patch = mock.patch('foo.bar.baz')
mock_baz = patch.start() # may want to keep a reference to this if you need to do per-test configuration
def tearDown(self):
super(SomeTest, self).tearDown()
mock.patch.stopall()
但您也可以保留對各個修補程序的引用self.patch1 = mock.patch(...)
,然后根據需要在tearDown
單獨停止該修補程序。
1實際上, mock.TEST_PREFIX
默認為"test"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.