mel
mel

Reputation: 2790

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. 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? (I'm using unites and mock)

Upvotes: 2

Views: 967

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599638

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. Your real function can call this to download the text, but your test can mock the whole function.

Upvotes: 4

Related Questions