0

I know that there are tutorials and other posts about mocks in Python but I'm new to testing and mocks, I read some posts and watched a tutorial but they confused me more. I have two examples that I just wrote fast and I wanna know how can I use mocks to test two examples.

In the first example test the the value that gets returned and in the second one test that a file gets created if we create a new instance of the 'MyFile' class.

1:

def get_link_tags(url):
    response = requests.get(url)

    pattern = re.compile("<link.*>")
    found_link_tags = pattern.findall(response.text)
    return found_link_tags

2:

class MyFile:
    def __init__(self, filename, content):
        self.content = content

        with open(filename, "w") as fl:
            fl.write(content)

Thank you

1 Answer 1

3

In the first example, you want to mock requests.get so that you can control its return value. Since requests.get is actually a Mock object when you call get_link_tags, its return value will be as well, so you can configure its text attribute to be whatever data you want.

with mock.patch('requests.get') as mock_get:
    mock_get.return_value.text = "my test data"
    rv = get_link_tags("http://example.com")

The second example is a little tricker; the mock library provides a function to make it simpler.

m = mock.mock_open()
with mock.patch('__main__.open', m):
    f = MyFile('foo.txt', 'data')
    h = m()
    h.write.assert_called_once_with('data')

m is a mock object that replaces open everywhere in the body of the with statement. The key thing to note is that when m is called both inside MyFile and manually in the next line, a reference to the same mock object is returned. This lets you test how the fake file inside MyFile is used.

Sign up to request clarification or add additional context in comments.

4 Comments

Since there are not any <link> tags in response.text (which now is the string "my test data") the get_link_tags will return an empty list. Is self.assertEqual(rv, []) appropriate to complete the test or should any of the mock assert methods be called?
In this case, self.assertEqual is fine, since you aren't concerned with the actual behavior of the mock so much as what the rest of get_link_tags does with the data the mock returns. Ideally, you would have multiple tests, each one setting mock_get.return_value.text to different values, to confirm that get_link_tags does the right thing with each.
One thing you might do with the mock object, for example, is verify that it is called with the argument passed to get_link_tags.
Thank you so much for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.