简体   繁体   English

在python中模拟对象的构造函数

[英]Mock the constructor of an object in python

I want to test a function that parse data from a web page, but I don't want that my test depend of modification of the HTML code or internet so I save the web pages. 我想测试一个可以解析网页数据的函数,但是我不想我的测试依赖于HTML代码或Internet的修改,所以我保存了网页。 The problem in the function I want to test I've got: 我要测试的功能中存在的问题:

url_query = "http://www.allocine.fr/film/fichefilm-%s/similaire/" %allocine_id
response = requests.get(url_query)
soup = BeautifulSoup(response.text, "html.parser")

So I did in my test: 所以我在测试中做了:

def test_Allocine_matrix_reloaded(self):
    #Load result Matrix allocine API
    test_file = open(MATRIX_RELOADED_TEST_FILE)
    matrix_reloaded_data = json.load(test_file)
    test_file.close()

    #Load result Matrix sim allocine webpage
    test_page = open(MATRIX_RELOADED_TEST_FILE)
    matrix_reloaded_sim_page = test_page.read()
    test_page.close()

    #Mocking functions
    allocine.get_allocine_info = mock.MagicMock(return_value=matrix_reloaded_data)
    requests.get = mock.MagicMock(return_value=matrix_reloaded_sim_page)

But I've got the error: 但是我有错误:

Traceback (most recent call last):
  File "info_allocine_test.py", line 34, in test_Allocine_matrix_reloaded
    friends_allocine_info = allocine.AllocineInfo(matrix_realoaded_allocine_id)
  File "info_allocine_flat.py", line 116, in __init__
    sim_allocine['sim'] = scrap_similar_movie_allocine(allocine_id)
  File "info_allocine_flat.py", line 255, in scrap_similar_movie_allocine
    soup = BeautifulSoup(response.text, "html.parser")
AttributeError: 'str' object has no attribute 'text'

How can I do to get the HTML code in soup variable? 如何获得soup变量中的HTML代码? (I'm using unites and mock) (我正在使用联合和模拟)

The best thing to do here would be to extract those three lines into a separate method or function which returns the downloaded text or the BeautifulSoup object. 最好的做法是将这三行提取到单独的方法或函数中,该方法或函数返回下载的文本或BeautifulSoup对象。 Your real function can call this to download the text, but your test can mock the whole function. 您的真实函数可以调用它来下载文本,但是您的测试可以模拟整个函数。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM