简体   繁体   English

单元测试模拟 urllib.request.urlretrieve() Python 3 和内部函数

[英]Unit test mock urllib.request.urlretrieve() Python 3 and internal function

How can I mock or unit test a function/method that uses urllib.request.urlretrieve to save a file?如何模拟或单元测试使用urllib.request.urlretrieve保存文件的函数/方法?

This is the part of code the I'm trying to to test:这是我要测试的代码部分:

from urllib import request
from config import cvs_site, proxy


class Collector(object):
    """Class Collector"""
    ...


def __init__(self, code_num=""):
    self.code_num = sec_id.upper()
    self.csv_file = "csv_files/code_num.csv"

    # load proxy if it is configured
    if proxy:
        proxies = {"http": proxy, "https": proxy, "ftp": proxy}
        proxy_connect = request.ProxyHandler(proxies)
        opener = request.build_opener(proxy_connect)
        request.install_opener(opener)

    def _collect_data():
        try:
            print("\nAccessing to retrieve CVS informations.")
            request.urlretrieve(cvs_site, self.cvs_file)
        except error.URLError as e:
            exit("\033[1;31m[ERROR]\033[1;00m {0}\n".format(e))

...

def some_function(self):
    _collect_data()
...

Should I test all internal functions (_functions())?我应该测试所有内部函数 (_functions()) 吗?

How to mock it?如何嘲笑它?

To solve it I did some modifications on my code, to then created the test with mock.为了解决这个问题,我对我的代码做了一些修改,然后用模拟创建了测试。

REMARK: I'm still learning unit tests and mock, any new comments here is good because I'm not confident that I went to correct way :)备注:我仍在学习单元测试和模拟,这里的任何新评论都很好,因为我不确定我是否采用了正确的方法:)

  1. the function _collect_data() there is not necessities to be inside of __init__() , then I moved it to outside.函数 _collect_data() 不需要在__init__()里面,然后我把它移到外面。

  2. the _collect_data is a function with specific action, save the file, but need to return something to able to mock works with this. _collect_data 是一个具有特定操作的函数,保存文件,但需要返回一些东西才能模拟使用它。

  3. the argument was moved from Class to function参数从类移到函数

The code new looks like it:新的代码看起来像这样:

from config import proxy
from config import cvs_site
from urllib import request


class Collector(object):
    """Class Collector"""


def __init__(self):

    self.csv_file = "csv_files/code_num.csv"

    # load proxy if it is configured
    if proxy:
        proxies = {"http": proxy, "https": proxy, "ftp": proxy}
        proxy_connect = request.ProxyHandler(proxies)
        opener = request.build_opener(proxy_connect)
        request.install_opener(opener)


def _collect_data():
    try:
        print("\nAccessing to retrieve CVS informations.")
        return request.urlretrieve(cvs_site, self.cvs_file)
    except error.URLError as e:
        return "\033[1;31m[ERROR]\033[1;00m {0}\n".format(e)
...


def some_function(self, code_num=""):
    code_num = code_num.upper()
    self._collect_data()
...

To test this code I create this:为了测试这段代码,我创建了这个:

import unittest
import mock
from saassist.datacollector import Collector


class TestCollector(unittest.TestCase):
    def setUp(self):
        self.apar_test = Collector()

    @mock.patch("saassist.datacollector.request")
    def test_collect_data(self, mock_collect_data):

        mock_collect_data.urlretrieve.return_value = "File Collected OK"
        self.assertEqual("File Collected OK", self.apar_test._collect_data())

Well, I don't know which more could be tested for it, but to start I think it is good :)好吧,我不知道还有哪些可以测试,但首先我认为它很好:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python 2.7中使用urllib.request.urlretrieve - How can I use urllib.request.urlretrieve with python 2.7 无法在Python中使用“ urllib.request.urlretrieve”下载图像 - failing at downloading an image with “urllib.request.urlretrieve” in Python 尝试在Python中下载jpeg时出现urllib.request.urlretrieve错误 - urllib.request.urlretrieve ERROR trying to download jpeg in Python Python:urllib.request.urlretrieve保存一个空文件。 在其中写道“提供的id参数为空。” - Python: urllib.request.urlretrieve saves an empty file. Writes in it “Supplied id parameter is empty.” Python,基本问题:如何使用 urllib.request.urlretrieve 下载多个 url - Python, basic question: How do I download multiple url's with urllib.request.urlretrieve 使用urllib.request.urlretrieve下载需要固定的时间 - downloading with urllib.request.urlretrieve takes fixed time HTTP 错误 404:未找到 urllib.request.urlretrieve - HTTP Error 404: Not Found urllib.request.urlretrieve 使用什么命令代替 urllib.request.urlretrieve? - What command to use instead of urllib.request.urlretrieve? urllib.request.urlretrieve不通过HTTPS下载文件 - urllib.request.urlretrieve not downloading files over HTTPS urllib.request.urlretrieve 如果不返回会做什么 - What does urllib.request.urlretrieve do if not returned
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM