Commit 512db7be by Will Daly

Fix embargo middleware with tests

parent ee71eba1
...@@ -166,7 +166,7 @@ class EmbargoMiddleware(object): ...@@ -166,7 +166,7 @@ class EmbargoMiddleware(object):
profile_country = cache.get(cache_key) profile_country = cache.get(cache_key)
if profile_country is None: if profile_country is None:
profile = getattr(user, 'profile', None) profile = getattr(user, 'profile', None)
if profile is not None and profile.country is not None: if profile is not None and profile.country.code is not None:
profile_country = profile.country.code.upper() profile_country = profile.country.code.upper()
else: else:
profile_country = "" profile_country = ""
......
...@@ -8,6 +8,7 @@ import unittest ...@@ -8,6 +8,7 @@ import unittest
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.conf import settings from django.conf import settings
from django.db import connection, transaction
from django.test.utils import override_settings from django.test.utils import override_settings
import ddt import ddt
...@@ -267,6 +268,24 @@ class EmbargoMiddlewareTests(ModuleStoreTestCase): ...@@ -267,6 +268,24 @@ class EmbargoMiddlewareTests(ModuleStoreTestCase):
with self.assertNumQueries(12): with self.assertNumQueries(12):
self.client.get(self.embargoed_page) self.client.get(self.embargoed_page)
def test_embargo_profile_country_db_null(self):
# Django country fields treat NULL values inconsistently.
# When saving a profile with country set to None, Django saves an empty string to the database.
# However, when the country field loads a NULL value from the database, it sets
# `country.code` to `None`. This caused a bug in which country values created by
# the original South schema migration -- which defaulted to NULL -- caused a runtime
# exception when the embargo middleware treated the value as a string.
# In order to simulate this behavior, we can't simply set `profile.country = None`.
# (because when we save it, it will set the database field to an empty string instead of NULL)
query = "UPDATE auth_userprofile SET country = NULL WHERE id = %s"
connection.cursor().execute(query, [str(self.user.profile.id)])
transaction.commit_unless_managed()
# Attempt to access an embargoed course
# Verify that the student can access the page without an error
response = self.client.get(self.embargoed_page)
self.assertEqual(response.status_code, 200)
@mock.patch.dict(settings.FEATURES, {'EMBARGO': False}) @mock.patch.dict(settings.FEATURES, {'EMBARGO': False})
def test_countries_embargo_off(self): def test_countries_embargo_off(self):
# When the middleware is turned off, all requests should go through # When the middleware is turned off, all requests should go through
......
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