Created
March 10, 2020 17:52
-
-
Save asankulov/5dadaab5406ac43415d7e31892e10e25 to your computer and use it in GitHub Desktop.
Testing Simple View
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExchangeAPITestCase(APITestCase): | |
def setUp(self) -> None: | |
self.valid_base_query_param = 'USD' | |
self.valid_target_query_param = 'EUR' | |
self.valid_amount_query_param = 12.12 | |
self.valid_convert_return_value = 1404.75 | |
self.valid_serializer_data = { | |
'base': self.valid_base_query_param, | |
'target': self.valid_target_query_param, | |
'amount': self.valid_amount_query_param | |
} | |
@mock.patch.object(CurrencyConvertSerializer, 'is_valid') | |
@mock.patch('currency_exchanger.serializers.CurrencyConvertSerializer.data', | |
new_callable=PropertyMock) | |
@mock.patch.object(ExchangeRateService, 'convert') | |
def test_currency_convert_success(self, mock_is_valid, mock_data, mock_convert): | |
mock_is_valid.return_value = None | |
mock_data.return_value = self.valid_serializer_data | |
mock_convert.return_value = self.valid_convert_return_value | |
response = self.client.get(f"/api/exchange/?" | |
f"base={self.valid_base_query_param}&" | |
f"target={self.valid_target_query_param}&" | |
f"amount={self.valid_amount_query_param}") | |
self.assertTrue(mock_is_valid.called) | |
self.assertTrue(mock_convert.called) | |
self.assertTrue(mock_data.called) | |
# print(mock_convert.call_count) | |
# print(mock_is_valid.call_count) | |
# print(mock_data.call_count) | |
self.assertEqual(response.status_code, 200) | |
self.assertDictEqual(response.data, {'result': self.valid_convert_return_value}) | |
# AssertionError: {'result': None} != {'result': 1404.75} | |
# - {'result': None} | |
# + {'result': 1404.75} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework import status | |
from rest_framework.response import Response | |
from rest_framework.views import APIView | |
from .serializers import CurrencyConvertSerializer | |
from .services import ExchangeRateService | |
class CurrencyConvertAPIView(APIView): | |
def get(self, *args, **kwargs): | |
serializer = CurrencyConvertSerializer(data=self.request.query_params) | |
serializer.is_valid(raise_exception=True) | |
validated_data = serializer.data | |
exchange_service = ExchangeRateService() | |
result = exchange_service.convert(**validated_data) | |
return Response({'result': result}, status=status.HTTP_200_OK) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment