Skip to content

Instantly share code, notes, and snippets.

@Ibrahem3amer
Created March 2, 2018 14:03
Show Gist options
  • Select an option

  • Save Ibrahem3amer/7f84f8d358f3693a55f1758e574165cc to your computer and use it in GitHub Desktop.

Select an option

Save Ibrahem3amer/7f84f8d358f3693a55f1758e574165cc to your computer and use it in GitHub Desktop.
Testable code
# The legacy code before I make it more testable.
data = copy.copy(request.data)
try:
file_data = FileData.objects.get(id=data['bill_reference'])
aggregator = UserAccount.objects.get(username=file_data.data['paid_through'])
except KeyError:
try:
file_data = FileData.objects.get(id=data['ref'])
aggregator = UserAccount.objects.get(username=file_data.data['paid_through'])
except FileData.DoesNotExist:
return JsonResponse({"message": "Ref is not proper"}, status=status.HTTP_404_NOT_FOUND)
if file_data.has_transaction:
return JsonResponse({"message": "This client had paid before"}, status=201)
--------------------------------------------------------------------------------------
# Some touches to unitize the code so that it can be tested with multiple cases.
data = copy.copy(request.data)
if not data:
return JsonResponse({"message": "No data was provided"}, status=status.HTTP_400_BAD_REQUEST)
# Getting related payment details. Yelling with 404 of related data isn't found.
bill_refrence = data.get('bill_reference', None) or data.get('ref', None)
try:
file_data = FileData.objects.get(id=bill_refrence)
aggregator = UserAccount.objects.get(username=file_data.data['paid_through'])
except (FileData.DoesNotExist, KeyError) as e:
return JsonResponse({"message": "Ref is not proper"}, status=status.HTTP_404_NOT_FOUND)
except UserAccount.DoesNotExist:
return JsonResponse({"message": "No aggregator found."}, status=status.HTTP_404_NOT_FOUND)
# Handling the already-paid situation.
if file_data.has_transaction:
return JsonResponse({"message": "This client had paid before"}, status=201)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment