From 6fb7d63c9e0a0a7634773634f08a52088d2d6ab1 Mon Sep 17 00:00:00 2001
From: Jeremy Bowman <jbowman@edx.org>
Date: Wed, 6 Sep 2017 11:31:37 -0400
Subject: [PATCH] Fixes for test order dependence

---
 .../student/tests/test_create_account.py      |  4 +--
 common/djangoapps/third_party_auth/saml.py    |  3 ++-
 .../tests/views/test_course_home.py           | 26 ++++++++++++-------
 .../tests/views/test_course_updates.py        |  5 ++--
 .../enterprise_support/tests/test_api.py      | 22 +++++++++++-----
 5 files changed, 39 insertions(+), 21 deletions(-)

diff --git a/common/djangoapps/student/tests/test_create_account.py b/common/djangoapps/student/tests/test_create_account.py
index da11e8e1a64..c8c5477e8d5 100644
--- a/common/djangoapps/student/tests/test_create_account.py
+++ b/common/djangoapps/student/tests/test_create_account.py
@@ -152,9 +152,9 @@ class TestCreateAccount(SiteMixin, TestCase):
             'country': self.params['country'],
         }
 
-        self.create_account_and_fetch_profile()
+        profile = self.create_account_and_fetch_profile()
 
-        mock_segment_identify.assert_called_with(1, expected_payload)
+        mock_segment_identify.assert_called_with(profile.user.id, expected_payload)
 
     @unittest.skipUnless(
         "microsite_configuration.middleware.MicrositeMiddleware" in settings.MIDDLEWARE_CLASSES,
diff --git a/common/djangoapps/third_party_auth/saml.py b/common/djangoapps/third_party_auth/saml.py
index 1e5e0a7e829..b70b17b92ea 100644
--- a/common/djangoapps/third_party_auth/saml.py
+++ b/common/djangoapps/third_party_auth/saml.py
@@ -2,6 +2,7 @@
 Slightly customized python-social-auth backend for SAML 2.0 support
 """
 import logging
+from copy import deepcopy
 
 import requests
 from django.contrib.sites.models import Site
@@ -191,7 +192,7 @@ class SapSuccessFactorsIdentityProvider(EdXSAMLIdentityProvider):
         Open edX platform registration form.
         """
         overrides = self.conf.get('sapsf_value_mappings', {})
-        base = self.default_value_mapping.copy()
+        base = deepcopy(self.default_value_mapping)
         for field, override in overrides.items():
             if field in base:
                 base[field].update(override)
diff --git a/openedx/features/course_experience/tests/views/test_course_home.py b/openedx/features/course_experience/tests/views/test_course_home.py
index a1e6876fda2..d655d495d88 100644
--- a/openedx/features/course_experience/tests/views/test_course_home.py
+++ b/openedx/features/course_experience/tests/views/test_course_home.py
@@ -31,7 +31,7 @@ from xmodule.modulestore import ModuleStoreEnum
 from xmodule.modulestore.tests.django_utils import CourseUserType, ModuleStoreTestCase, SharedModuleStoreTestCase
 from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls
 from .helpers import add_course_mode
-from .test_course_updates import create_course_update
+from .test_course_updates import create_course_update, remove_course_updates
 from ... import COURSE_PRE_START_ACCESS_FLAG
 
 TEST_PASSWORD = 'test'
@@ -125,6 +125,10 @@ class TestCourseHomePage(CourseHomePageTestCase):
         super(TestCourseHomePage, self).setUp()
         self.client.login(username=self.user.username, password=TEST_PASSWORD)
 
+    def tearDown(self):
+        remove_course_updates(self.user, self.course)
+        super(TestCourseHomePage, self).tearDown()
+
     @override_waffle_flag(UNIFIED_COURSE_TAB_FLAG, active=True)
     def test_welcome_message_when_unified(self):
         # Create a welcome message
@@ -204,6 +208,10 @@ class TestCourseHomePageAccess(CourseHomePageTestCase):
         # Add a welcome message
         create_course_update(self.course, self.staff_user, TEST_WELCOME_MESSAGE)
 
+    def tearDown(self):
+        remove_course_updates(self.staff_user, self.course)
+        super(TestCourseHomePageAccess, self).tearDown()
+
     @override_waffle_flag(UNIFIED_COURSE_TAB_FLAG, active=True)
     @override_waffle_flag(SHOW_REVIEWS_TOOL_FLAG, active=True)
     @ddt.data(
@@ -214,7 +222,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase):
     )
     @ddt.unpack
     def test_home_page(self, user_type, expected_message):
-        self.user = self.create_user_for_course(self.course, user_type)
+        self.create_user_for_course(self.course, user_type)
 
         # Render the course home page
         url = course_home_url(self.course)
@@ -252,7 +260,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase):
         """
         Verifies the course home tab when not unified.
         """
-        self.user = self.create_user_for_course(self.course, user_type)
+        self.create_user_for_course(self.course, user_type)
 
         # Render the course home page
         url = course_home_url(self.course)
@@ -294,7 +302,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase):
         the student dashboard, not a 404.
         """
         future_course = self.create_future_course()
-        self.user = self.create_user_for_course(future_course, CourseUserType.ENROLLED)
+        self.create_user_for_course(future_course, CourseUserType.ENROLLED)
 
         url = course_home_url(future_course)
         response = self.client.get(url)
@@ -315,7 +323,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase):
         the student dashboard, not a 404, even if the localized date is unicode
         """
         future_course = self.create_future_course()
-        self.user = self.create_user_for_course(future_course, CourseUserType.ENROLLED)
+        self.create_user_for_course(future_course, CourseUserType.ENROLLED)
 
         fake_unicode_start_time = u"üñîçø∂é_ßtå®t_tîµé"
         mock_strftime_localized.return_value = fake_unicode_start_time
@@ -334,7 +342,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase):
         """
         Ensure a non-existent course results in a 404.
         """
-        self.user = self.create_user_for_course(self.course, CourseUserType.ANONYMOUS)
+        self.create_user_for_course(self.course, CourseUserType.ANONYMOUS)
 
         url = course_home_url_from_string('not/a/course')
         response = self.client.get(url)
@@ -361,21 +369,21 @@ class TestCourseHomePageAccess(CourseHomePageTestCase):
         self.assertContains(response, TEST_COURSE_HOME_MESSAGE_ANONYMOUS)
 
         # Verify that unenrolled users are shown an enroll call to action message
-        self.user = self.create_user_for_course(self.course, CourseUserType.UNENROLLED)
+        user = self.create_user_for_course(self.course, CourseUserType.UNENROLLED)
         url = course_home_url(self.course)
         response = self.client.get(url)
         self.assertContains(response, TEST_COURSE_HOME_MESSAGE)
         self.assertContains(response, TEST_COURSE_HOME_MESSAGE_UNENROLLED)
 
         # Verify that enrolled users are not shown a message when enrolled and course has begun
-        CourseEnrollment.enroll(self.user, self.course.id)
+        CourseEnrollment.enroll(user, self.course.id)
         url = course_home_url(self.course)
         response = self.client.get(url)
         self.assertNotContains(response, TEST_COURSE_HOME_MESSAGE)
 
         # Verify that enrolled users are shown 'days until start' message before start date
         future_course = self.create_future_course()
-        CourseEnrollment.enroll(self.user, future_course.id)
+        CourseEnrollment.enroll(user, future_course.id)
         url = course_home_url(future_course)
         response = self.client.get(url)
         self.assertContains(response, TEST_COURSE_HOME_MESSAGE)
diff --git a/openedx/features/course_experience/tests/views/test_course_updates.py b/openedx/features/course_experience/tests/views/test_course_updates.py
index a346947917a..a2f8eaa93b4 100644
--- a/openedx/features/course_experience/tests/views/test_course_updates.py
+++ b/openedx/features/course_experience/tests/views/test_course_updates.py
@@ -70,9 +70,8 @@ def remove_course_updates(user, course):
     updates_usage_key = get_course_info_usage_key(course, 'updates')
     try:
         course_updates = modulestore().get_item(updates_usage_key)
-        course_updates.items = []
-        modulestore().update_item(course_updates, user.id)
-    except ItemNotFoundError:
+        modulestore().delete_item(course_updates.location, user.id)
+    except (ItemNotFoundError, ValueError):
         pass
 
 
diff --git a/openedx/features/enterprise_support/tests/test_api.py b/openedx/features/enterprise_support/tests/test_api.py
index 6b808630fe9..7d46e0c4f8c 100644
--- a/openedx/features/enterprise_support/tests/test_api.py
+++ b/openedx/features/enterprise_support/tests/test_api.py
@@ -10,7 +10,7 @@ import mock
 from django.conf import settings
 from django.core.urlresolvers import reverse
 from django.http import HttpResponseRedirect
-from django.test import SimpleTestCase
+from django.test import TestCase
 from django.test.utils import override_settings
 
 from openedx.features.enterprise_support.api import (
@@ -26,20 +26,30 @@ from openedx.features.enterprise_support.tests.mixins.enterprise import Enterpri
 from student.tests.factories import UserFactory
 
 
+class MockEnrollment(mock.MagicMock):
+    """
+    Mock object for an enrollment which has a consistent string representation
+    suitable for use in ddt parameters.
+    """
+    def __repr__(self):
+        return '<MockEnrollment course_id={}>'.format(getattr(self, 'course_id', None))
+
+
 @ddt.ddt
 @override_settings(ENABLE_ENTERPRISE_INTEGRATION=True)
 @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
-class TestEnterpriseApi(EnterpriseServiceMockMixin, SimpleTestCase):
+class TestEnterpriseApi(EnterpriseServiceMockMixin, TestCase):
     """
     Test enterprise support APIs.
     """
-    def setUp(self):
+    @classmethod
+    def setUpTestData(cls):
         UserFactory.create(
             username='enterprise_worker',
             email='ent_worker@example.com',
             password='password123',
         )
-        super(TestEnterpriseApi, self).setUp()
+        super(TestEnterpriseApi, cls).setUpTestData()
 
     @httpretty.activate
     @override_settings(ENTERPRISE_SERVICE_WORKER_USERNAME='enterprise_worker')
@@ -239,13 +249,13 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, SimpleTestCase):
         (True, {}, 'course', [], []),
         (True, {'real': 'enterprise'}, None, [], []),
         (True, {'name': 'GriffCo', 'uuid': ''}, 'real-course', [], []),
-        (True, {'name': 'GriffCo', 'uuid': ''}, 'real-course', [mock.MagicMock(course_id='other-id')], []),
+        (True, {'name': 'GriffCo', 'uuid': ''}, 'real-course', [MockEnrollment(course_id='other-id')], []),
         (
             True,
             {'name': 'GriffCo', 'uuid': 'real-uuid'},
             'real-course',
             [
-                mock.MagicMock(
+                MockEnrollment(
                     course_id='real-course',
                     course_overview=mock.MagicMock(
                         display_name='My Cool Course'
-- 
GitLab