Commit 110304b5 by Simon Chen

Fix the api serializer so history data, if missing, are returned correctly

parent e3804fc3
......@@ -7,6 +7,7 @@ from decimal import Decimal
import waffle
from dateutil.parser import parse
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
......@@ -298,7 +299,10 @@ class CourseSerializer(serializers.HyperlinkedModelSerializer):
self.fields.pop('products', None)
def get_last_edited(self, obj):
return obj.history.latest().history_date.strftime(ISO_8601_FORMAT)
try:
return obj.history.latest().history_date.strftime(ISO_8601_FORMAT)
except ObjectDoesNotExist:
return None
def get_products_url(self, obj):
return reverse('api:v2:course-product-list', kwargs={'parent_lookup_course_id': obj.id},
......@@ -634,8 +638,11 @@ class CouponSerializer(ProductPaymentInfoMixin, serializers.ModelSerializer):
return offer_range.enterprise_customer if offer_range else None
def get_last_edited(self, obj):
history = obj.history.latest()
return history.history_user.username, history.history_date
try:
history = obj.history.latest()
return history.history_user.username, history.history_date
except ObjectDoesNotExist:
return None
def get_max_uses(self, obj):
offer = retrieve_offer(obj)
......
......@@ -490,6 +490,13 @@ class CouponViewSetFunctionalTest(CouponMixin, DiscoveryTestMixin, DiscoveryMock
self.assertEqual(coupon_data['category']['name'], self.data['category']['name'])
self.assertEqual(coupon_data['client'], self.data['client'])
def test_list_coupons_no_history(self):
self.coupon.history.all().delete()
response = self.client.get(COUPONS_LINK)
self.assertEqual(response.status_code, status.HTTP_200_OK)
coupon_data = json.loads(response.content)['results'][0]
self.assertEqual(coupon_data.get('last_edited'), None)
def test_list_and_details_endpoint_return_custom_code(self):
"""Test that the list and details endpoints return the correct code."""
self.data.update({
......@@ -516,6 +523,11 @@ class CouponViewSetFunctionalTest(CouponMixin, DiscoveryTestMixin, DiscoveryMock
self.client.post(COUPONS_LINK, json.dumps(self.data), 'application/json')
self.assert_post_response_status(self.data)
def test_coupon_details_no_history(self):
self.coupon.history.all().delete()
detail_response = self.get_response_json('GET', reverse('api:v2:coupons-detail', args=[self.coupon.id]))
self.assertEqual(detail_response['last_edited'], None)
def test_update(self):
"""Test updating a coupon."""
response_data = self.get_response_json(
......
......@@ -6,6 +6,7 @@ import jwt
import mock
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from oscar.core.loading import get_class, get_model
......@@ -41,7 +42,11 @@ class CourseViewSetTests(ProductSerializerMixin, DiscoveryTestMixin, TestCase):
products_url = self.get_full_url(reverse('api:v2:course-product-list',
kwargs={'parent_lookup_course_id': course.id}))
last_edited = course.history.latest().history_date.strftime(ISO_8601_FORMAT)
last_edited = None
try:
last_edited = course.history.latest().history_date.strftime(ISO_8601_FORMAT)
except ObjectDoesNotExist:
pass
enrollment_code = course.enrollment_code_product
data = {
......@@ -109,6 +114,14 @@ class CourseViewSetTests(ProductSerializerMixin, DiscoveryTestMixin, TestCase):
response = self.client.get(self.list_path)
self.assertDictEqual(json.loads(response.content), {'count': 0, 'next': None, 'previous': None, 'results': []})
def test_list_without_history(self):
course = Course.objects.all()[0]
course.history.all().delete()
response = self.client.get(self.list_path)
self.assertEqual(response.status_code, 200)
self.assertListEqual(json.loads(response.content)['results'], [self.serialize_course(self.course)])
def test_create(self):
""" Verify the view can create a new Course."""
Course.objects.all().delete()
......
......@@ -39,7 +39,7 @@ class StockRecordViewSetTests(ProductSerializerMixin, DiscoveryTestMixin, Thrott
self.assertEqual(StockRecord.objects.count(), 4)
results = [self.serialize_stockrecord(stockrecord) for stockrecord in
self.product.stockrecords.all()]
self.product.stockrecords.all().order_by('id')]
expected = {'count': 2, 'next': None, 'previous': None, 'results': results}
self.assertDictEqual(json.loads(response.content), expected)
......
......@@ -13,7 +13,7 @@ class StockRecordViewSet(viewsets.ModelViewSet):
serializer_class = serializers.StockRecordSerializer
def get_queryset(self):
return StockRecord.objects.filter(partner=self.request.site.siteconfiguration.partner)
return StockRecord.objects.filter(partner=self.request.site.siteconfiguration.partner).order_by('id')
def get_serializer_class(self):
serializer_class = self.serializer_class
......
......@@ -419,6 +419,22 @@ class UtilTests(CouponMixin, DiscoveryMockMixin, DiscoveryTestMixin, LmsApiMockM
self.assertNotIn('Course Seat Types', field_names)
self.assertNotIn('Redeemed For Course ID', field_names)
def test_report_with_no_coupon_history(self):
self.setup_coupons_for_report()
self.coupon.history.all().delete()
client = UserFactory()
basket = Basket.get_basket(client, self.site)
basket.add_product(self.coupon)
vouchers = self.coupon_vouchers.first().vouchers.all()
self.use_voucher('TESTORDER1', vouchers[1], self.user)
self.mock_course_api_response(course=self.course)
_, rows = generate_coupon_report(self.coupon_vouchers)
first_row = rows.pop(0)
self.assertEqual(first_row.get('Created By'), 'N/A')
self.assertEqual(first_row.get('Create Date'), 'N/A')
def test_report_for_dynamic_coupon_with_fixed_benefit_type(self):
""" Verify the coupon report contains correct data for coupon with fixed benefit type. """
dynamic_coupon = self.create_coupon(
......
......@@ -94,8 +94,12 @@ def _get_discount_info(discount_data):
def _get_info_for_coupon_report(coupon, voucher):
author = 'N/A'
created_date = 'N/A'
history = coupon.history.first()
author = history.history_user.full_name
if history:
author = history.history_user.full_name
created_date = history.history_date.strftime("%b %d, %y")
category_name = ProductCategory.objects.get(product=coupon).category.name
try:
......@@ -146,7 +150,7 @@ def _get_info_for_coupon_report(coupon, voucher):
'Coupon Start Date': voucher.start_datetime.strftime("%b %d, %y"),
'Coupon Type': coupon_type,
'Created By': author,
'Create Date': history.history_date.strftime("%b %d, %y"),
'Create Date': created_date,
'Discount Percentage': discount_percentage,
'Discount Amount': discount_amount,
'Email Domains': offer.email_domains,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment