0leg
0leg

Reputation: 14134

Mocking a field in request

There are 2 frameworks - Django and Flask. Django runs the project with REST, while Flask runs an Orchestration Layer.

Now there is a test, which supposed to check one of CRUD methods:

@mock.patch('requests.post')
def test_create(self, request_mock,):
    request_mock.return_value = self.response_generator.create()
    response = self.client.post(url_for('foo.list', account='bar'),
                                content_type='application/json',
                                data=json.dumps({
                                    "name": "Foo",
                                    "type": "baz"
                                }))
    self.assertEqual(response.status_code, 201)

name and type are mandatory fields. name is just a string. But type is a url to the type (in the REST), so when baz is passed it uses magic to connect to the REST and retrieve data.

The problem is that when running the test Django with the REST is offline, while the test still tries to connect to it resulting in timeout error.

with ConnectionError: HTTPConnectionPool(host='10.10.10.10', port=8000): Max retries exceeded with url: /rest/accounts/bar/baz/ (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused',))


Question: now how does one mock just that type field, so it doesn't call offline server?

Upvotes: 0

Views: 254

Answers (1)

Enrique Saez
Enrique Saez

Reputation: 2690

The very first condition for useful unit tests is mocking the external dependencies that those tests may have. Just like in your case, you should be able to run it regardless of the availability of the service you are trying to test.

Although I do not know what self.client stands for (since you did not include the code for it) I guess by the error response you posted, that you created a urllib client.

However, if your intention is to test a view within your Django project, you should make use of the django test client as the Django docs suggest. Depending on your needs you should also consider RequestFactory.

Therefore there would be no need of having a urllib client since the framework is providing you with the required unit testing tools.

There are also similar questions

Upvotes: 1

Related Questions