Exemple #1
0
class SyncOrgVenuesTestSuite(EventTestCase):
    """Test /answer"""
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_sync_org_venues_without_cohort(self):
        """Test /answer without auth"""
        model = self.generate_models(organization=True)

        try:
            sync_org_venues(model['organization'])
        except Exception as e:
            self.assertEquals(str(e), (
                'First you must specify to which academy this organization belongs'
            ))

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_sync_org_venues_without_cohort(self):
        """Test /answer without auth"""
        model = self.generate_models(organization=True, academy=True)

        try:
            sync_org_venues(model['organization'])
        except Exception as e:
            self.assertEquals(str(e),
                              ('The path you requested does not exist.'))
Exemple #2
0
class AnswerIdTrackerTestSuite(FeedbackTestCase):
    """Test /answer/:id/tracker.png"""

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_tracker_without_auth(self):
        """Test /answer/:id/tracker.png without auth"""
        url = reverse_lazy('feedback:answer_id_tracker', kwargs={'answer_id': 9999})
        response = self.client.get(url)

        self.assertEqual(response['content-type'], 'image/png')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_answer(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_tracker_without_data(self):
        """Test /answer/:id/tracker.png without auth"""
        self.generate_models(authenticate=True)
        url = reverse_lazy('feedback:answer_id_tracker', kwargs={'answer_id': 9999})
        response = self.client.get(url)

        self.assertEqual(response['content-type'], 'image/png')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_answer(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_tracker_with_data_without_status(self):
        """Test /answer/:id/tracker.png without auth"""
        model = self.generate_models(authenticate=True, answer=True)
        db = self.model_to_dict(model, 'answer')
        url = reverse_lazy('feedback:answer_id_tracker', kwargs={'answer_id': model['answer'].id})
        response = self.client.get(url)

        # db['status'] = 'OPENED'

        self.assertEqual(response['content-type'], 'image/png')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_tracker_with_data(self):
        """Test /answer/:id/tracker.png without auth"""
        model = self.generate_models(authenticate=True, answer=True, answer_status='SENT')
        db = self.model_to_dict(model, 'answer')
        url = reverse_lazy('feedback:answer_id_tracker', kwargs={'answer_id': model['answer'].id})
        response = self.client.get(url)

        db['status'] = 'OPENED'

        self.assertEqual(response['content-type'], 'image/png')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.check_all_opened_at_and_remove_it(self.all_answer_dict()), [db])
Exemple #3
0
class academyTestSuite(AdmissionsTestCase):
    """Test /academy"""

    def test_academy_without_auth(self):
        """Test /academy without auth"""
        url = reverse_lazy('admissions:academy')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': 'Authentication credentials were not provided.',
            'status_code': status.HTTP_401_UNAUTHORIZED
        })
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_academy_without_data(self):
        """Test /academy without auth"""
        url = reverse_lazy('admissions:academy')
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_academy(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_with_data(self):
        """Test /academy without auth"""
        self.generate_models(authenticate=True, academy=True)
        url = reverse_lazy('admissions:academy')
        model_dict = self.remove_dinamics_fields(self.academy.__dict__)

        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'id': self.academy.id,
            'name': self.academy.name,
            'slug': self.academy.slug,
            'street_address': self.academy.street_address,
            'country': self.academy.country.code,
            'city': self.academy.city.id,
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_academy(), 1)
        self.assertEqual(self.get_academy_dict(1), model_dict)
Exemple #4
0
class AcademyCohortTestSuite(AdmissionsTestCase):
    """Test /academy/cohort"""
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_delete_duplicates(self):
        """Test /academy/cohort without auth"""
        self.generate_models(cohort=True, user=True)
        models = [
            mixer.blend('admissions.CohortUser',
                        user=self.user,
                        cohort=self.cohort) for _ in range(0, 10)
        ]
        model_dict = self.remove_dinamics_fields(models[0].__dict__)
        command = Command()

        self.assertEqual(command.handle(), None)
        self.assertEqual(self.count_cohort_user(), 1)
        self.assertEqual(self.all_cohort_user_dict(), [model_dict])
class MediaTestSuite(MediaTestCase):
    """Test /answer"""
    """
    🔽🔽🔽 Auth
    """
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_type_slug__without_auth(self):
        """Test /answer without auth"""
        url = reverse_lazy('activity:type_slug',
                           kwargs={'activity_slug': 'they-killed-kenny'})
        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_type_slug__wrong_academy(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        url = reverse_lazy('activity:type_slug',
                           kwargs={'activity_slug': 'they-killed-kenny'})
        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_type_slug__without_capability(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('activity:type_slug',
                           kwargs={'activity_slug': 'they-killed-kenny'})
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(
            json, {
                'detail':
                "You (user: 1) don't have this capability: read_activity for academy 1",
                'status_code': 403,
            })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    """
    🔽🔽🔽 Bad slug
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_type_slug__without_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        self.generate_models(authenticate=True,
                             profile_academy=True,
                             capability='read_activity',
                             role='potato')

        url = reverse_lazy('activity:type_slug',
                           kwargs={'activity_slug': 'they-killed-kenny'})
        response = self.client.get(url)
        json = response.json()
        expected = {'detail': 'activity-not-found', 'status_code': 400}

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    """
    🔽🔽🔽 Get
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_type_slug(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        self.generate_models(authenticate=True,
                             profile_academy=True,
                             capability='read_activity',
                             role='potato')

        url = reverse_lazy('activity:type_slug',
                           kwargs={'activity_slug': 'academy-registration'})
        response = self.client.get(url)
        json = response.json()
        expected = {
            'description': 'When student successfuly join to academy',
            'slug': 'academy-registration',
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Exemple #6
0
class AnswerTestSuite(FeedbackTestCase):
    """Test /answer"""

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_without_auth(self):
        """Test /answer without auth"""
        url = reverse_lazy('feedback:answer')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_wrong_academy(self):
        """Test /answer without auth"""
        url = reverse_lazy('feedback:answer')
        response = self.client.get(url, **{'HTTP_Academy': 1 })
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_without_capability(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('feedback:answer')
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': "You (user: 1) don't have this capability: read_nps_answers for academy 1",
            'status_code': 403
        })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_without_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        models = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_nps_answers', role='potato')
        url = reverse_lazy('feedback:answer')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_answer(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, answer=True, profile_academy=True,
            capability='read_nps_answers', role='potato')
        db = self.model_to_dict(model, 'answer')
        url = reverse_lazy('feedback:answer')
        response = self.client.get(url)
        json = response.json()

        json = [{**x, 'created_at': None} for x in json if self.assertDatetime(x['created_at'])]

        self.assertEqual(json, [{
            'created_at': None,
            'academy': {
                'id': model['answer'].academy.id,
                'name': model['answer'].academy.name,
                'slug': model['answer'].academy.slug,
            },
            'cohort': {
                'id': model['answer'].cohort.id,
                'name': model['answer'].cohort.name,
                'slug': model['answer'].cohort.slug,
            },
            'comment': model['answer'].comment,
            'event': model['answer'].event,
            'highest': model['answer'].highest,
            'id': model['answer'].id,
            'lang': model['answer'].lang,
            'lowest': model['answer'].lowest,
            'mentor': {
                'first_name':  model['answer'].mentor.first_name,
                'id':  model['answer'].mentor.id,
                'last_name':  model['answer'].mentor.last_name,
            },
            'score': model['answer'].score,
            'status': model['answer'].status,
            'title': model['answer'].title,
            'user': {
                'first_name': model['user'].first_name,
                'id': model['user'].id,
                'last_name': model['user'].last_name,
            },
        }])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_bad_param_user_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, user=True, answer=True, profile_academy=True,
            capability='read_nps_answers', role='potato')
        db = self.model_to_dict(model, 'answer')
        params = {
            'user': 9999
        }
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?{urllib.parse.urlencode(params)}'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_param_user_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, user=True, answer=True, profile_academy=True,
            capability='read_nps_answers', role='potato')
        db = self.model_to_dict(model, 'answer')
        params = {
            'user': model['user'].id,
        }
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?{urllib.parse.urlencode(params)}'
        response = self.client.get(url)
        json = response.json()

        json = [{**x, 'created_at': None} for x in json if self.assertDatetime(x['created_at'])]

        self.assertEqual(json, [{
            'created_at': None,
            'academy': {
                'id': model['answer'].academy.id,
                'name': model['answer'].academy.name,
                'slug': model['answer'].academy.slug,
            },
            'cohort': {
                'id': model['answer'].cohort.id,
                'name': model['answer'].cohort.name,
                'slug': model['answer'].cohort.slug,
            },
            'comment': model['answer'].comment,
            'event': model['answer'].event,
            'highest': model['answer'].highest,
            'id': model['answer'].id,
            'lang': model['answer'].lang,
            'lowest': model['answer'].lowest,
            'mentor': {
                'first_name':  model['answer'].mentor.first_name,
                'id':  model['answer'].mentor.id,
                'last_name':  model['answer'].mentor.last_name,
            },
            'score': model['answer'].score,
            'status': model['answer'].status,
            'title': model['answer'].title,
            'user': {
                'first_name': model['user'].first_name,
                'id': model['user'].id,
                'last_name': model['user'].last_name,
            },
        }])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_bad_param_cohort_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, user=True, cohort=True, answer=True, profile_academy=True,
            capability='read_nps_answers', role='potato')
        db = self.model_to_dict(model, 'answer')
        params = {
            'cohort': 'they-killed-kenny',
        }
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?{urllib.parse.urlencode(params)}'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_param_cohort_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, user=True, cohort=True, answer=True, profile_academy=True,
            capability='read_nps_answers', role='potato')
        db = self.model_to_dict(model, 'answer')
        params = {
            'cohort': model['cohort'].slug,
        }
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?{urllib.parse.urlencode(params)}'
        response = self.client.get(url)
        json = response.json()

        json = [{**x, 'created_at': None} for x in json if self.assertDatetime(x['created_at'])]

        self.assertEqual(json, [{
            'created_at': None,
            'academy': {
                'id': model['answer'].academy.id,
                'name': model['answer'].academy.name,
                'slug': model['answer'].academy.slug,
            },
            'cohort': {
                'id': model['cohort'].id,
                'name': model['cohort'].name,
                'slug': model['cohort'].slug,
            },
            'comment': model['answer'].comment,
            'event': model['answer'].event,
            'highest': model['answer'].highest,
            'id': model['answer'].id,
            'lang': model['answer'].lang,
            'lowest': model['answer'].lowest,
            'mentor': {
                'first_name':  model['answer'].mentor.first_name,
                'id':  model['answer'].mentor.id,
                'last_name':  model['answer'].mentor.last_name,
            },
            'score': model['answer'].score,
            'status': model['answer'].status,
            'title': model['answer'].title,
            'user': {
                'first_name': model['user'].first_name,
                'id': model['user'].id,
                'last_name': model['user'].last_name,
            },
        }])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_param_academy_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, user=True, cohort=True, academy=True,
            answer=True, profile_academy=True, capability='read_nps_answers', role='potato')
        db = self.model_to_dict(model, 'answer')
        params = {
            'academy': model['academy'].id,
        }
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?{urllib.parse.urlencode(params)}'
        response = self.client.get(url)
        json = response.json()

        json = [{**x, 'created_at': None} for x in json if self.assertDatetime(x['created_at'])]

        self.assertEqual(json, [{
            'created_at': None,
            'academy': {
                'id': model['answer'].academy.id,
                'name': model['answer'].academy.name,
                'slug': model['answer'].academy.slug,
            },
            'cohort': {
                'id': model['cohort'].id,
                'name': model['cohort'].name,
                'slug': model['cohort'].slug,
            },
            'comment': model['answer'].comment,
            'event': model['answer'].event,
            'highest': model['answer'].highest,
            'id': model['answer'].id,
            'lang': model['answer'].lang,
            'lowest': model['answer'].lowest,
            'mentor': {
                'first_name':  model['answer'].mentor.first_name,
                'id':  model['answer'].mentor.id,
                'last_name':  model['answer'].mentor.last_name,
            },
            'score': model['answer'].score,
            'status': model['answer'].status,
            'title': model['answer'].title,
            'user': {
                'first_name': model['user'].first_name,
                'id': model['user'].id,
                'last_name': model['user'].last_name,
            },
        }])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_bad_param_mentor_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, user=True, cohort=True, academy=True,
            answer=True, profile_academy=True, capability='read_nps_answers',
            role='potato')
        db = self.model_to_dict(model, 'answer')
        params = {
            'mentor': 9999,
        }
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?{urllib.parse.urlencode(params)}'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_param_mentor_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, user=True, cohort=True, academy=True,
            answer=True, profile_academy=True, capability='read_nps_answers',
            role='potato')
        db = self.model_to_dict(model, 'answer')
        params = {
            'mentor': model['user'].id,
        }
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?{urllib.parse.urlencode(params)}'
        response = self.client.get(url, headers={"Academy": model['academy'].id})
        json = response.json()

        json = [{**x, 'created_at': None} for x in json if self.assertDatetime(x['created_at'])]

        self.assertEqual(json, [{
            'created_at': None,
            'academy': {
                'id': model['answer'].academy.id,
                'name': model['answer'].academy.name,
                'slug': model['answer'].academy.slug,
            },
            'cohort': {
                'id': model['cohort'].id,
                'name': model['cohort'].name,
                'slug': model['cohort'].slug,
            },
            'comment': model['answer'].comment,
            'event': model['answer'].event,
            'highest': model['answer'].highest,
            'id': model['answer'].id,
            'lang': model['answer'].lang,
            'lowest': model['answer'].lowest,
            'mentor': {
                'first_name': model['user'].first_name,
                'id': model['user'].id,
                'last_name': model['user'].last_name,
            },
            'score': model['answer'].score,
            'status': model['answer'].status,
            'title': model['answer'].title,
            'user': {
                'first_name': model['user'].first_name,
                'id': model['user'].id,
                'last_name': model['user'].last_name,
            },
        }])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_bad_param_event_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, user=True, cohort=True, academy=True,
            answer=True, event=True, profile_academy=True,
            capability='read_nps_answers', role='potato')
        db = self.model_to_dict(model, 'answer')
        params = {
            'event': 9999,
        }
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?{urllib.parse.urlencode(params)}'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_param_event_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, user=True, cohort=True, academy=True,
            answer=True, event=True, profile_academy=True,
            capability='read_nps_answers', role='potato')
        db = self.model_to_dict(model, 'answer')
        params = {
            'event': model['event'].id,
        }
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?{urllib.parse.urlencode(params)}'
        response = self.client.get(url)
        json = response.json()

        json = [{**x, 'created_at': None} for x in json if self.assertDatetime(x['created_at'])]

        self.assertEqual(json, [{
            'created_at': None,
            'academy': {
                'id': model['answer'].academy.id,
                'name': model['answer'].academy.name,
                'slug': model['answer'].academy.slug,
            },
            'cohort': {
                'id': model['cohort'].id,
                'name': model['cohort'].name,
                'slug': model['cohort'].slug,
            },
            'comment': model['answer'].comment,
            'event': {
                'id': model['event'].id,
                'description': model['event'].description,
                'excerpt': model['event'].excerpt,
                'lang': model['event'].lang,
                'title': model['event'].title,
            },
            'highest': model['answer'].highest,
            'id': model['answer'].id,
            'lang': model['answer'].lang,
            'lowest': model['answer'].lowest,
            'mentor': {
                'first_name': model['user'].first_name,
                'id': model['user'].id,
                'last_name': model['user'].last_name,
            },
            'score': model['answer'].score,
            'status': model['answer'].status,
            'title': model['answer'].title,
            'user': {
                'first_name': model['user'].first_name,
                'id': model['user'].id,
                'last_name': model['user'].last_name,
            },
        }])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_bad_param_score_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, user=True, cohort=True, academy=True,
            event=True, profile_academy=True, capability='read_nps_answers', role='potato')

        for number in range(1, 10):
            self.remove_all_answer()
            score = str(number)

            answer_kwargs = {
                'score': score
            }
            model = self.generate_models(answer=True, answer_kwargs=answer_kwargs, models=base)
            db = self.model_to_dict(model, 'answer')
            params = {
                'score': 1 if number == 10 else number + 1,
            }
            base_url = reverse_lazy('feedback:answer')
            url = f'{base_url}?{urllib.parse.urlencode(params)}'
            response = self.client.get(url)
            json = response.json()

            self.assertEqual(json, [])

            db['score'] = score
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_param_score_with_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, user=True, cohort=True, academy=True,
            event=True, profile_academy=True, capability='read_nps_answers', role='potato')

        for number in range(1, 10):
            self.remove_all_answer()
            score = str(number)

            answer_kwargs = {
                'score': score
            }
            model = self.generate_models(answer=True, answer_kwargs=answer_kwargs, models=base)
            db = self.model_to_dict(model, 'answer')
            params = {
                'score': score,
            }
            base_url = reverse_lazy('feedback:answer')
            url = f'{base_url}?{urllib.parse.urlencode(params)}'
            response = self.client.get(url, headers={"Academy", model['academy'].id })
            json = response.json()

            json = [{**x, 'created_at': None} for x in json if self.assertDatetime(x['created_at'])]

            self.assertEqual(json, [{
                'created_at': None,
                'academy': {
                    'id': model['answer'].academy.id,
                    'name': model['answer'].academy.name,
                    'slug': model['answer'].academy.slug,
                },
                'cohort': {
                    'id': model['cohort'].id,
                    'name': model['cohort'].name,
                    'slug': model['cohort'].slug,
                },
                'comment': model['answer'].comment,
                'event': {
                    'id': model['event'].id,
                    'description': model['event'].description,
                    'excerpt': model['event'].excerpt,
                    'lang': model['event'].lang,
                    'title': model['event'].title,
                },
                'highest': model['answer'].highest,
                'id': model['answer'].id,
                'lang': model['answer'].lang,
                'lowest': model['answer'].lowest,
                'mentor': {
                    'first_name': model['user'].first_name,
                    'id': model['user'].id,
                    'last_name': model['user'].last_name,
                },
                'score': score,
                'status': model['answer'].status,
                'title': model['answer'].title,
                'user': {
                    'first_name': model['user'].first_name,
                    'id': model['user'].id,
                    'last_name': model['user'].last_name,
                },
            }])

            db['score'] = score

            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_data_without_pagination_get_just_100(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_nps_answers', role='potato')

        models = [self.generate_models(answer=True, models=base) for _ in range(0, 105)]
        ordened_models = sorted(models, key=lambda x: x['answer'].created_at,
            reverse=True)

        url = reverse_lazy('feedback:answer')
        response = self.client.get(url)
        json = response.json()

        json = [{**x, 'created_at': None} for x in json
            if self.assertDatetime(x['created_at'])]

        expected = [{
            'id': model['answer'].id,
            'title': model['answer'].title,
            'lowest': model['answer'].lowest,
            'highest': model['answer'].highest,
            'lang': model['answer'].lang,
            'comment': model['answer'].comment,
            'score': model['answer'].score,
            'status': model['answer'].status,
            'created_at': None,
            'user': {
                'id': model['user'].id,
                'first_name': model['user'].first_name,
                'last_name': model['user'].last_name,
            },
            'academy': {
                'id': model['answer'].academy.id,
                'slug': model['answer'].academy.slug,
                'name': model['answer'].academy.name,
            },
            'cohort': {
                'id': model['answer'].cohort.id,
                'slug': model['answer'].cohort.slug,
                'name': model['answer'].cohort.name,
            },
            'mentor': {
                'id':  model['answer'].mentor.id,
                'first_name':  model['answer'].mentor.first_name,
                'last_name':  model['answer'].mentor.last_name,
            },
            'event': model['answer'].event,
        } for model in ordened_models][:100]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [{
            **self.model_to_dict(model, 'answer'),
        } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_data_with_pagination_first_five(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_nps_answers', role='potato')

        models = [self.generate_models(answer=True, models=base) for _ in range(0, 10)]
        ordened_models = sorted(models, key=lambda x: x['answer'].created_at,
            reverse=True)

        url = reverse_lazy('feedback:answer') + '?limit=5&offset=0'
        response = self.client.get(url)
        json = response.json()

        prev_results = json['results']
        json['results'] = [{**x, 'created_at': None} for x in prev_results
            if self.assertDatetime(x['created_at'])]

        results = [{
            'id': model['answer'].id,
            'title': model['answer'].title,
            'lowest': model['answer'].lowest,
            'highest': model['answer'].highest,
            'lang': model['answer'].lang,
            'comment': model['answer'].comment,
            'score': model['answer'].score,
            'status': model['answer'].status,
            'created_at': None,
            'user': {
                'id': model['user'].id,
                'first_name': model['user'].first_name,
                'last_name': model['user'].last_name,
            },
            'academy': {
                'id': model['answer'].academy.id,
                'slug': model['answer'].academy.slug,
                'name': model['answer'].academy.name,
            },
            'cohort': {
                'id': model['answer'].cohort.id,
                'slug': model['answer'].cohort.slug,
                'name': model['answer'].cohort.name,
            },
            'mentor': {
                'id':  model['answer'].mentor.id,
                'first_name':  model['answer'].mentor.first_name,
                'last_name':  model['answer'].mentor.last_name,
            },
            'event': model['answer'].event,
        } for model in ordened_models][:5]

        expected = {
            'count': 10,
            'first': None,
            'next': 'http://testserver/v1/feedback/academy/answer?limit=5&'
                f'offset=5',
            'previous': None,
            'last': 'http://testserver/v1/feedback/academy/answer?limit=5&'
                f'offset=5',
            'results': results
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [{
            **self.model_to_dict(model, 'answer'),
        } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_data_with_pagination_last_five(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_nps_answers', role='potato')

        models = [self.generate_models(answer=True, models=base) for _ in range(0, 10)]
        ordened_models = sorted(models, key=lambda x: x['answer'].created_at,
            reverse=True)

        url = reverse_lazy('feedback:answer') + '?limit=5&offset=5'
        response = self.client.get(url)
        json = response.json()

        prev_results = json['results']
        json['results'] = [{**x, 'created_at': None} for x in prev_results
            if self.assertDatetime(x['created_at'])]

        results = [{
            'id': model['answer'].id,
            'title': model['answer'].title,
            'lowest': model['answer'].lowest,
            'highest': model['answer'].highest,
            'lang': model['answer'].lang,
            'comment': model['answer'].comment,
            'score': model['answer'].score,
            'status': model['answer'].status,
            'created_at': None,
            'user': {
                'id': model['user'].id,
                'first_name': model['user'].first_name,
                'last_name': model['user'].last_name,
            },
            'academy': {
                'id': model['answer'].academy.id,
                'slug': model['answer'].academy.slug,
                'name': model['answer'].academy.name,
            },
            'cohort': {
                'id': model['answer'].cohort.id,
                'slug': model['answer'].cohort.slug,
                'name': model['answer'].cohort.name,
            },
            'mentor': {
                'id':  model['answer'].mentor.id,
                'first_name':  model['answer'].mentor.first_name,
                'last_name':  model['answer'].mentor.last_name,
            },
            'event': model['answer'].event,
        } for model in ordened_models][5:]

        expected = {
            'count': 10,
            'first': 'http://testserver/v1/feedback/academy/answer?limit=5',
            'next': None,
            'previous': 'http://testserver/v1/feedback/academy/answer?limit=5',
            'last': None,
            'results': results,
        }

        self.assertEqual(json, expected)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [{
            **self.model_to_dict(model, 'answer'),
        } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_data_with_pagination_last_five(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_nps_answers', role='potato')

        models = [self.generate_models(answer=True, models=base) for _ in range(0, 10)]
        url = reverse_lazy('feedback:answer') + '?limit=5&offset=10'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': 'http://testserver/v1/feedback/academy/answer?limit=5',
            'next': None,
            'previous': 'http://testserver/v1/feedback/academy/answer?limit=5&offset=5',
            'last': None,
            'results': [],
        }

        self.assertEqual(json, expected)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [{
            **self.model_to_dict(model, 'answer'),
        } for model in models])

    """
    🔽🔽🔽 With full like querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_query_like_full_name(self):
        """Test /answer with like full name"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True, 
            capability='read_nps_answers', role='potato')
        del base['user']
        user_kwargs = {
                'email':  '*****@*****.**',
                'first_name': 'Rene',
                'last_name': 'Descartes',
            }
        user_kwargs_2 = {
                'email': '*****@*****.**',
                'first_name': 'Reinaldo',
                'last_name': 'Descarado',
            }
        models = [
            self.generate_models(user=True, answer=True, user_kwargs=user_kwargs, models=base),
            self.generate_models(user=True, answer=True, user_kwargs=user_kwargs_2, models=base),
        ]

        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?like=Rene Descartes'

        response = self.client.get(url)
        json = response.json()

        expected = [
            {
                'created_at': self.datetime_to_iso(models[0].answer.created_at),
                'academy': {
                    'id': models[0].answer.academy.id,
                    'name': models[0].answer.academy.name,
                    'slug': models[0].answer.academy.slug,
                },
                'cohort': {
                    'id': models[0].cohort.id,
                    'name': models[0].cohort.name,
                    'slug': models[0].cohort.slug,
                },
                'comment': models[0].answer.comment,
                'event': models[0].answer.event,
                'highest': models[0].answer.highest,
                'id': models[0].answer.id,
                'lang': models[0].answer.lang,
                'lowest': models[0].answer.lowest,
                'mentor': {
                    'first_name':  models[0].answer.mentor.first_name,
                    'id':  models[0].answer.mentor.id,
                    'last_name':  models[0].answer.mentor.last_name,
                },
                'score': models[0].answer.score,
                'status': models[0].answer.status,
                'title': models[0].answer.title,
                'user': {
                    'first_name': 'Rene',
                    'id': 2,
                    'last_name': 'Descartes',
                },
            }
        ]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_query_like_first_name(self):
        """Test /answer with like first name"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True, 
            capability='read_nps_answers', role='potato')
        del base['user']
        user_kwargs = {
                'email':  '*****@*****.**',
                'first_name': 'Rene',
                'last_name': 'Descartes',
            }
        user_kwargs_2 = {
                'email': '*****@*****.**',
                'first_name': 'Reinaldo',
                'last_name': 'Descarado',
            }
        models = [
            self.generate_models(user=True, answer=True, user_kwargs=user_kwargs, models=base),
            self.generate_models(user=True, answer=True, user_kwargs=user_kwargs_2, models=base),
        ]
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?like=Rene'

        response = self.client.get(url)
        json = response.json()

        expected = [
            {
                'created_at': self.datetime_to_iso(models[0].answer.created_at),
                'academy': {
                    'id': models[0].answer.academy.id,
                    'name': models[0].answer.academy.name,
                    'slug': models[0].answer.academy.slug,
                },
                'cohort': {
                    'id': models[0].cohort.id,
                    'name': models[0].cohort.name,
                    'slug': models[0].cohort.slug,
                },
                'comment': models[0].answer.comment,
                'event': models[0].answer.event,
                'highest': models[0].answer.highest,
                'id': models[0].answer.id,
                'lang': models[0].answer.lang,
                'lowest': models[0].answer.lowest,
                'mentor': {
                    'first_name':  models[0].answer.mentor.first_name,
                    'id':  models[0].answer.mentor.id,
                    'last_name':  models[0].answer.mentor.last_name,
                },
                'score': models[0].answer.score,
                'status': models[0].answer.status,
                'title': models[0].answer.title,
                'user': {
                    'first_name': 'Rene',
                    'id': 2,
                    'last_name': 'Descartes',
                },
            }
        ]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_query_like_last_name(self):
        """Test /answer with like last name"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True, 
            capability='read_nps_answers', role='potato')
        del base['user']
        user_kwargs = {
                'email':  '*****@*****.**',
                'first_name': 'Rene',
                'last_name': 'Descartes',
            }
        user_kwargs_2 = {
                'email': '*****@*****.**',
                'first_name': 'Reinaldo',
                'last_name': 'Descarado',
            }
        models = [
            self.generate_models(user=True, answer=True, user_kwargs=user_kwargs, models=base),
            self.generate_models(user=True, answer=True, user_kwargs=user_kwargs_2, models=base),
        ]
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}?like=Descartes'

        response = self.client.get(url)
        json = response.json()

        expected = [
            {
                'created_at': self.datetime_to_iso(models[0].answer.created_at),
                'academy': {
                    'id': models[0].answer.academy.id,
                    'name': models[0].answer.academy.name,
                    'slug': models[0].answer.academy.slug,
                },
                'cohort': {
                    'id': models[0].cohort.id,
                    'name': models[0].cohort.name,
                    'slug': models[0].cohort.slug,
                },
                'comment': models[0].answer.comment,
                'event': models[0].answer.event,
                'highest': models[0].answer.highest,
                'id': models[0].answer.id,
                'lang': models[0].answer.lang,
                'lowest': models[0].answer.lowest,
                'mentor': {
                    'first_name':  models[0].answer.mentor.first_name,
                    'id':  models[0].answer.mentor.id,
                    'last_name':  models[0].answer.mentor.last_name,
                },
                'score': models[0].answer.score,
                'status': models[0].answer.status,
                'title': models[0].answer.title,
                'user': {
                    'first_name': 'Rene',
                    'id': 2,
                    'last_name': 'Descartes',
                },
            }
        ]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_with_query_like_email(self):
        """Test /answer with like email"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True, 
            capability='read_nps_answers', role='potato')
        del base['user']
        user_kwargs = {
                'email':  '*****@*****.**',
                'first_name': 'Rene',
                'last_name': 'Descartes',
            }
        user_kwargs_2 = {
                'email': '*****@*****.**',
                'first_name': 'Reinaldo',
                'last_name': 'Descarado',
            }
        models = [
            self.generate_models(user=True, answer=True, user_kwargs=user_kwargs, models=base),
            self.generate_models(user=True, answer=True, user_kwargs=user_kwargs_2, models=base),
        ]
        base_url = reverse_lazy('feedback:answer')
        url = f'{base_url}[email protected]'

        response = self.client.get(url)
        json = response.json()

        expected = [
            {
                'created_at': self.datetime_to_iso(models[0].answer.created_at),
                'academy': {
                    'id': models[0].answer.academy.id,
                    'name': models[0].answer.academy.name,
                    'slug': models[0].answer.academy.slug,
                },
                'cohort': {
                    'id': models[0].cohort.id,
                    'name': models[0].cohort.name,
                    'slug': models[0].cohort.slug,
                },
                'comment': models[0].answer.comment,
                'event': models[0].answer.event,
                'highest': models[0].answer.highest,
                'id': models[0].answer.id,
                'lang': models[0].answer.lang,
                'lowest': models[0].answer.lowest,
                'mentor': {
                    'first_name':  models[0].answer.mentor.first_name,
                    'id':  models[0].answer.mentor.id,
                    'last_name':  models[0].answer.mentor.last_name,
                },
                'score': models[0].answer.score,
                'status': models[0].answer.status,
                'title': models[0].answer.title,
                'user': {
                    'first_name': 'Rene',
                    'id': 2,
                    'last_name': 'Descartes',
                },
            }
        ]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Exemple #7
0
class CohortUserTestSuite(MarketingTestCase):
    """Test /academy/lead"""

    """
    🔽🔽🔽 Auth
    """
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__without_auth(self):
        """Test /cohort/:id/user without auth"""
        url = reverse_lazy('marketing:lead_all')
        response = self.client.get(url)
        json = response.json()
        expected = {
            'detail': 'Authentication credentials were not provided.',
            'status_code': 401
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(self.all_form_entry_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__without_profile_acedemy(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        url = reverse_lazy('marketing:lead_all')
        model = self.generate_models(authenticate=True, form_entry=True)

        response = self.client.get(url)
        json = response.json()

        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        }])

    """
    🔽🔽🔽 Without data
    """
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__without_data(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        url = reverse_lazy('marketing:lead_all')
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato')

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [])

    """
    🔽🔽🔽 With data
    """
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        url = reverse_lazy('marketing:lead_all')
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato', form_entry=True,
            form_entry_kwargs=generate_form_entry_kwargs())

        response = self.client.get(url)
        json = response.json()

        self.assertDatetime(json[0]['created_at'])
        del json[0]['created_at']

        expected = [{
            'academy': {
                'id':  model.form_entry.academy.id,
                'name': model.form_entry.academy.name,
                'slug': model.form_entry.academy.slug
            },
            'country': model.form_entry.country,
            'course': model.form_entry.course,
            'email': model.form_entry.email,
            'first_name': model.form_entry.first_name,
            'gclid': model.form_entry.gclid,
            'id': model.form_entry.id,
            'language': model.form_entry.language,
            'last_name': model.form_entry.last_name,
            'lead_type': model.form_entry.lead_type,
            'location': model.form_entry.location,
            'storage_status': model.form_entry.storage_status,
            'tags': model.form_entry.tags,
            'utm_campaign': model.form_entry.utm_campaign,
            'utm_medium': model.form_entry.utm_medium,
            'utm_source': model.form_entry.utm_source,
            'utm_url': model.form_entry.utm_url,
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        }])

    """
    🔽🔽🔽 Academy in querystring
    """
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__with_bad_academy_in_querystring(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        url = reverse_lazy('marketing:lead_all') + '?academy=freyja'
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato', form_entry=True)

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__with_academy_in_querystring(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        academy_kwargs = {'slug': 'freyja'}
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato', form_entry=True,
            academy_kwargs=academy_kwargs)

        url = reverse_lazy('marketing:lead_all') + '?academy=freyja'
        response = self.client.get(url)
        json = response.json()

        self.assertDatetime(json[0]['created_at'])
        del json[0]['created_at']

        expected = [{
            'academy': {
                'id':  model.form_entry.academy.id,
                'name': model.form_entry.academy.name,
                'slug': model.form_entry.academy.slug
            },
            'country': model.form_entry.country,
            'course': model.form_entry.course,
            'email': model.form_entry.email,
            'first_name': model.form_entry.first_name,
            'gclid': model.form_entry.gclid,
            'id': model.form_entry.id,
            'language': model.form_entry.language,
            'last_name': model.form_entry.last_name,
            'lead_type': model.form_entry.lead_type,
            'location': model.form_entry.location,
            'storage_status': model.form_entry.storage_status,
            'tags': model.form_entry.tags,
            'utm_campaign': model.form_entry.utm_campaign,
            'utm_medium': model.form_entry.utm_medium,
            'utm_source': model.form_entry.utm_source,
            'utm_url': model.form_entry.utm_url,
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__with_two_academy_in_querystring(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        base = self.generate_models(user=True)

        models = [self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato', form_entry=True, models=base,
            academy_kwargs={'slug': 'konan' if index == 0 else 'freyja'})
            for index in range(0, 2)]

        models.sort(key=lambda x: x.form_entry.created_at)
        url = reverse_lazy('marketing:lead_all') + '?academy=' + ','.join([x.academy.slug for x in models])
        response = self.client.get(url)
        json = response.json()

        self.assertDatetime(json[0]['created_at'])
        del json[0]['created_at']

        self.assertDatetime(json[1]['created_at'])
        del json[1]['created_at']

        expected = [{
            'academy': {
                'id':  model.form_entry.academy.id,
                'name': model.form_entry.academy.name,
                'slug': model.form_entry.academy.slug
            },
            'country': model.form_entry.country,
            'course': model.form_entry.course,
            'email': model.form_entry.email,
            'first_name': model.form_entry.first_name,
            'gclid': model.form_entry.gclid,
            'id': model.form_entry.id,
            'language': model.form_entry.language,
            'last_name': model.form_entry.last_name,
            'lead_type': model.form_entry.lead_type,
            'location': model.form_entry.location,
            'storage_status': model.form_entry.storage_status,
            'tags': model.form_entry.tags,
            'utm_campaign': model.form_entry.utm_campaign,
            'utm_medium': model.form_entry.utm_medium,
            'utm_source': model.form_entry.utm_source,
            'utm_url': model.form_entry.utm_url,
        } for model in models]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        } for model in models])

    """
    🔽🔽🔽 Start in querystring
    """
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__with_bad_start_in_querystring(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        url = reverse_lazy('marketing:lead_all') + '?start=2100-01-01'
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato', form_entry=True)

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__with_start_in_querystring(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        query_date = (timezone.now() - timedelta(hours=48)).strftime("%Y-%m-%d")
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato', form_entry=True)

        url = reverse_lazy('marketing:lead_all') + f'?start={query_date}'
        response = self.client.get(url)
        json = response.json()

        self.assertDatetime(json[0]['created_at'])
        del json[0]['created_at']

        expected = [{
            'academy': {
                'id':  model.form_entry.academy.id,
                'name': model.form_entry.academy.name,
                'slug': model.form_entry.academy.slug
            },
            'country': model.form_entry.country,
            'course': model.form_entry.course,
            'email': model.form_entry.email,
            'first_name': model.form_entry.first_name,
            'gclid': model.form_entry.gclid,
            'id': model.form_entry.id,
            'language': model.form_entry.language,
            'last_name': model.form_entry.last_name,
            'lead_type': model.form_entry.lead_type,
            'location': model.form_entry.location,
            'storage_status': model.form_entry.storage_status,
            'tags': model.form_entry.tags,
            'utm_campaign': model.form_entry.utm_campaign,
            'utm_medium': model.form_entry.utm_medium,
            'utm_source': model.form_entry.utm_source,
            'utm_url': model.form_entry.utm_url,
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        }])

    """
    🔽🔽🔽 End in querystring
    """
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__with_bad_end_in_querystring(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        url = reverse_lazy('marketing:lead_all') + '?end=1900-01-01'
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato', form_entry=True)

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_lead_all__with_end_in_querystring(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        query_date = (timezone.now() + timedelta(hours=48)).strftime("%Y-%m-%d")
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato', form_entry=True)

        url = reverse_lazy('marketing:lead_all') + f'?end={query_date}'
        response = self.client.get(url)
        json = response.json()

        self.assertDatetime(json[0]['created_at'])
        del json[0]['created_at']

        expected = [{
            'academy': {
                'id':  model.form_entry.academy.id,
                'name': model.form_entry.academy.name,
                'slug': model.form_entry.academy.slug
            },
            'country': model.form_entry.country,
            'course': model.form_entry.course,
            'email': model.form_entry.email,
            'first_name': model.form_entry.first_name,
            'gclid': model.form_entry.gclid,
            'id': model.form_entry.id,
            'language': model.form_entry.language,
            'last_name': model.form_entry.last_name,
            'lead_type': model.form_entry.lead_type,
            'location': model.form_entry.location,
            'storage_status': model.form_entry.storage_status,
            'tags': model.form_entry.tags,
            'utm_campaign': model.form_entry.utm_campaign,
            'utm_medium': model.form_entry.utm_medium,
            'utm_source': model.form_entry.utm_source,
            'utm_url': model.form_entry.utm_url,
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        }])
Exemple #8
0
class AcademyEventTestSuite(EventTestCase):
    cache = EventCache()

    def test_all_academy_events_no_auth(self):
        self.headers(academy=1)
        url = reverse_lazy('events:academy_all_events')

        response = self.client.get(url)
        json = response.json()
        expected = {
            'detail': 'Authentication credentials were not provided.',
            'status_code': 401
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 401)

    def test_all_academy_events_without_capability(self):
        self.headers(academy=1)
        url = reverse_lazy('events:academy_all_events')
        self.generate_models(authenticate=True)

        response = self.client.get(url)
        json = response.json()
        expected = {
            'detail':
            "You (user: 1) don't have this capability: read_event for academy 1",
            'status_code': 403
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 403)

    def test_all_academy_events_wrong_city(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     venue=True,
                                     event=True)
        url = reverse_lazy('events:academy_all_events') + "?city=patata"

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

    def test_all_academy_events_correct_city(self):
        self.headers(academy=1)
        venue_kwargs = {"city": "santiago"}
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     venue_kwargs=venue_kwargs,
                                     venue=True,
                                     event=True)
        url = reverse_lazy('events:academy_all_events') + "?city=santiago"
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'banner':
            model['event'].banner,
            'ending_at':
            datetime_to_iso_format(model['event'].ending_at),
            'event_type':
            model['event'].event_type,
            'excerpt':
            model['event'].excerpt,
            'id':
            model['event'].id,
            'lang':
            model['event'].lang,
            'online_event':
            model['event'].online_event,
            'starting_at':
            datetime_to_iso_format(model['event'].starting_at),
            'status':
            model['event'].status,
            'title':
            model['event'].title,
            'url':
            model['event'].url,
            'venue': {
                'city': model['event'].venue.city,
                'id': model['event'].id,
                'state': model['event'].venue.state,
                'street_address': model['event'].venue.street_address,
                'title': model['event'].venue.title,
                'zip_code': model['event'].venue.zip_code
            }
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

    def test_all_academy_events_wrong_country(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     venue=True,
                                     event=True)
        url = reverse_lazy('events:academy_all_events') + "?country=patata"

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

    def test_all_academy_events_correct_country(self):
        self.headers(academy=1)
        venue_kwargs = {"country": "chile"}
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     venue_kwargs=venue_kwargs,
                                     venue=True,
                                     event=True)
        url = reverse_lazy('events:academy_all_events') + "?country=chile"
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'banner':
            model['event'].banner,
            'ending_at':
            datetime_to_iso_format(model['event'].ending_at),
            'event_type':
            model['event'].event_type,
            'excerpt':
            model['event'].excerpt,
            'id':
            model['event'].id,
            'lang':
            model['event'].lang,
            'online_event':
            model['event'].online_event,
            'starting_at':
            datetime_to_iso_format(model['event'].starting_at),
            'status':
            model['event'].status,
            'title':
            model['event'].title,
            'url':
            model['event'].url,
            'venue': {
                'city': model['event'].venue.city,
                'id': model['event'].id,
                'state': model['event'].venue.state,
                'street_address': model['event'].venue.street_address,
                'title': model['event'].venue.title,
                'zip_code': model['event'].venue.zip_code
            }
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

    def test_all_academy_events_wrong_zip_code(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     venue=True,
                                     event=True)
        url = reverse_lazy(
            'events:academy_all_events') + "?zip_code=12345678965412"

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

    def test_all_academy_events_correct_zip_code(self):
        self.headers(academy=1)
        venue_kwargs = {"zip_code": "33178"}
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     venue_kwargs=venue_kwargs,
                                     venue=True,
                                     event=True)
        url = reverse_lazy('events:academy_all_events') + "?zip_code=33178"
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'banner':
            model['event'].banner,
            'ending_at':
            datetime_to_iso_format(model['event'].ending_at),
            'event_type':
            model['event'].event_type,
            'excerpt':
            model['event'].excerpt,
            'id':
            model['event'].id,
            'lang':
            model['event'].lang,
            'online_event':
            model['event'].online_event,
            'starting_at':
            datetime_to_iso_format(model['event'].starting_at),
            'status':
            model['event'].status,
            'title':
            model['event'].title,
            'url':
            model['event'].url,
            'venue': {
                'city': model['event'].venue.city,
                'id': model['event'].id,
                'state': model['event'].venue.state,
                'street_address': model['event'].venue.street_address,
                'title': model['event'].venue.title,
                'zip_code': model['event'].venue.zip_code
            }
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

    def test_all_academy_events_upcoming(self):
        self.headers(academy=1)
        event_kwargs = {"starting_at": timezone.now()}
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     venue=True,
                                     event=True,
                                     event_kwargs=event_kwargs)
        url = reverse_lazy('events:academy_all_events') + "?past=true"

        response = self.client.get(url)
        json = response.json()
        expected = [{
            'banner':
            model['event'].banner,
            'ending_at':
            datetime_to_iso_format(model['event'].ending_at),
            'event_type':
            model['event'].event_type,
            'excerpt':
            model['event'].excerpt,
            'id':
            model['event'].id,
            'lang':
            model['event'].lang,
            'online_event':
            model['event'].online_event,
            'starting_at':
            datetime_to_iso_format(model['event'].starting_at),
            'status':
            model['event'].status,
            'title':
            model['event'].title,
            'url':
            model['event'].url,
            'venue': {
                'city': model['event'].venue.city,
                'id': model['event'].id,
                'state': model['event'].venue.state,
                'street_address': model['event'].venue.street_address,
                'title': model['event'].venue.title,
                'zip_code': model['event'].venue.zip_code
            }
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_all_academy_events_not_found(self):
        self.headers(academy=1)
        url = reverse_lazy('events:academy_all_events')
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True)

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_all_academy_events(self, models=None):
        self.headers(academy=1)
        url = reverse_lazy('events:academy_all_events')

        if models is None:
            models = [
                self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     event=True)
            ]

        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model['event'].id,
            'banner':
            model['event'].banner,
            'ending_at':
            datetime_to_iso_format(model['event'].ending_at),
            'event_type':
            model['event'].event_type,
            'excerpt':
            model['event'].excerpt,
            'lang':
            model['event'].lang,
            'online_event':
            model['event'].online_event,
            'starting_at':
            datetime_to_iso_format(model['event'].starting_at),
            'status':
            model['event'].status,
            'title':
            model['event'].title,
            'url':
            model['event'].url,
            'venue':
            model['event'].venue
        } for model in models]

        expected.reverse()

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

        self.assertEqual(self.all_event_dict(), [{
            **self.model_to_dict(model, 'event'),
        } for model in models])
        return models

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_all_academy_events_post_without_required_fields(self):
        self.headers(academy=1)

        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_event',
                                     role='potato')

        url = reverse_lazy('events:academy_all_events')
        data = {}

        response = self.client.post(url, data)
        json = response.json()
        expected = {
            'url': ['This field is required.'],
            'banner': ['This field is required.'],
            'capacity': ['This field is required.'],
            'starting_at': ['This field is required.'],
            'ending_at': ['This field is required.']
        }

        self.assertEqual(json, expected)

        self.assertEqual(self.all_event_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_all_academy_events_post_without_required_fields____(self):
        self.headers(academy=1)

        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_event',
                                     role='potato')

        url = reverse_lazy('events:academy_all_events')
        current_date = self.datetime_now()
        data = {
            'url': 'https://www.google.com/',
            'banner': 'https://www.google.com/banner',
            'capacity': 11,
            'starting_at': self.datetime_to_iso(current_date),
            'ending_at': self.datetime_to_iso(current_date),
        }

        response = self.client.post(url, data)
        json = response.json()

        self.assertDatetime(json['created_at'])
        self.assertDatetime(json['updated_at'])

        del json['created_at']
        del json['updated_at']

        expected = {
            'academy': 1,
            'author': None,
            'description': None,
            'event_type': None,
            'eventbrite_id': None,
            'eventbrite_organizer_id': None,
            'eventbrite_status': None,
            'eventbrite_url': None,
            'excerpt': None,
            'host': None,
            'id': 1,
            'lang': None,
            'online_event': False,
            'organization': None,
            'published_at': None,
            'status': 'DRAFT',
            'sync_desc': None,
            'sync_status': 'PENDING',
            'title': None,
            'venue': None,
            **data,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 201)
        self.assertEqual(self.all_event_dict(), [{
            'academy_id': 1,
            'author_id': None,
            'banner': 'https://www.google.com/banner',
            'capacity': 11,
            'description': None,
            'ending_at': current_date,
            'event_type_id': None,
            'eventbrite_id': None,
            'eventbrite_organizer_id': None,
            'eventbrite_status': None,
            'eventbrite_url': None,
            'excerpt': None,
            'host_id': None,
            'id': 1,
            'lang': None,
            'online_event': False,
            'organization_id': None,
            'published_at': None,
            'starting_at': current_date,
            'status': 'DRAFT',
            'sync_desc': None,
            'sync_status': 'PENDING',
            'title': None,
            'url': 'https://www.google.com/',
            'venue_id': None,
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_all_academy_events_pagination(self):
        self.headers(academy=1)
        url = reverse_lazy('events:academy_all_events')
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     event=True)

        base = model.copy()
        del base['event']

        models = [model] + [
            self.generate_models(event=True, models=base)
            for _ in range(0, 105)
        ]
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model['event'].id,
            'excerpt':
            model['event'].excerpt,
            'title':
            model['event'].title,
            'lang':
            model['event'].lang,
            'url':
            model['event'].url,
            'banner':
            model['event'].banner,
            'starting_at':
            self.datetime_to_iso(model['event'].starting_at),
            'ending_at':
            self.datetime_to_iso(model['event'].ending_at),
            'status':
            model['event'].status,
            'event_type':
            model['event'].event_type,
            'online_event':
            model['event'].online_event,
            'venue':
            model['event'].venue
        } for model in models]
        expected.sort(key=lambda x: x['starting_at'], reverse=True)
        expected = expected[0:100]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.all_event_dict(),
                         [{
                             'academy_id': model['event'].academy_id,
                             'author_id': model['event'].author_id,
                             'banner': model['event'].banner,
                             'capacity': model['event'].capacity,
                             'description': None,
                             'ending_at': model['event'].ending_at,
                             'event_type_id': None,
                             'eventbrite_id': None,
                             'eventbrite_organizer_id': None,
                             'eventbrite_status': None,
                             'eventbrite_url': None,
                             'excerpt': None,
                             'host_id': model['event'].host_id,
                             'id': model['event'].id,
                             'lang': None,
                             'online_event': False,
                             'organization_id': None,
                             'published_at': None,
                             'starting_at': model['event'].starting_at,
                             'status': 'DRAFT',
                             'sync_desc': None,
                             'sync_status': 'PENDING',
                             'title': None,
                             'url': model['event'].url,
                             'venue_id': None
                         } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_all_academy_events_pagination_first_five(self):
        self.headers(academy=1)
        url = reverse_lazy('events:academy_all_events') + '?limit=5&offset=0'
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     event=True)

        base = model.copy()
        del base['event']

        models = [model] + [
            self.generate_models(event=True, models=base) for _ in range(0, 9)
        ]
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model['event'].id,
            'excerpt':
            model['event'].excerpt,
            'title':
            model['event'].title,
            'lang':
            model['event'].lang,
            'url':
            model['event'].url,
            'banner':
            model['event'].banner,
            'starting_at':
            self.datetime_to_iso(model['event'].starting_at),
            'ending_at':
            self.datetime_to_iso(model['event'].ending_at),
            'status':
            model['event'].status,
            'event_type':
            model['event'].event_type,
            'online_event':
            model['event'].online_event,
            'venue':
            model['event'].venue
        } for model in models]
        expected.sort(key=lambda x: x['starting_at'], reverse=True)
        expected = expected[0:5]
        expected = {
            'count': 10,
            'first': None,
            'next':
            'http://testserver/v1/events/academy/event?limit=5&offset=5',
            'previous': None,
            'last':
            'http://testserver/v1/events/academy/event?limit=5&offset=5',
            'results': expected
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.all_event_dict(),
                         [{
                             'academy_id': model['event'].academy_id,
                             'author_id': model['event'].author_id,
                             'banner': model['event'].banner,
                             'capacity': model['event'].capacity,
                             'description': None,
                             'ending_at': model['event'].ending_at,
                             'event_type_id': None,
                             'eventbrite_id': None,
                             'eventbrite_organizer_id': None,
                             'eventbrite_status': None,
                             'eventbrite_url': None,
                             'excerpt': None,
                             'host_id': model['event'].host_id,
                             'id': model['event'].id,
                             'lang': None,
                             'online_event': False,
                             'organization_id': None,
                             'published_at': None,
                             'starting_at': model['event'].starting_at,
                             'status': 'DRAFT',
                             'sync_desc': None,
                             'sync_status': 'PENDING',
                             'title': None,
                             'url': model['event'].url,
                             'venue_id': None
                         } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_all_academy_events_pagination_last_five(self):
        self.headers(academy=1)
        url = reverse_lazy('events:academy_all_events') + '?limit=5&offset=5'
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     event=True)

        base = model.copy()
        del base['event']

        models = [model] + [
            self.generate_models(event=True, models=base) for _ in range(0, 9)
        ]
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model['event'].id,
            'excerpt':
            model['event'].excerpt,
            'title':
            model['event'].title,
            'lang':
            model['event'].lang,
            'url':
            model['event'].url,
            'banner':
            model['event'].banner,
            'starting_at':
            self.datetime_to_iso(model['event'].starting_at),
            'ending_at':
            self.datetime_to_iso(model['event'].ending_at),
            'status':
            model['event'].status,
            'event_type':
            model['event'].event_type,
            'online_event':
            model['event'].online_event,
            'venue':
            model['event'].venue
        } for model in models]
        expected.sort(key=lambda x: x['starting_at'], reverse=True)
        expected = expected[5:10]
        expected = {
            'count': 10,
            'first': 'http://testserver/v1/events/academy/event?limit=5',
            'next': None,
            'previous': 'http://testserver/v1/events/academy/event?limit=5',
            'last': None,
            'results': expected
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.all_event_dict(),
                         [{
                             'academy_id': model['event'].academy_id,
                             'author_id': model['event'].author_id,
                             'banner': model['event'].banner,
                             'capacity': model['event'].capacity,
                             'description': None,
                             'ending_at': model['event'].ending_at,
                             'event_type_id': None,
                             'eventbrite_id': None,
                             'eventbrite_organizer_id': None,
                             'eventbrite_status': None,
                             'eventbrite_url': None,
                             'excerpt': None,
                             'host_id': model['event'].host_id,
                             'id': model['event'].id,
                             'lang': None,
                             'online_event': False,
                             'organization_id': None,
                             'published_at': None,
                             'starting_at': model['event'].starting_at,
                             'status': 'DRAFT',
                             'sync_desc': None,
                             'sync_status': 'PENDING',
                             'title': None,
                             'url': model['event'].url,
                             'venue_id': None
                         } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_all_academy_events_pagination_after_last_five(self):
        self.headers(academy=1)
        url = reverse_lazy('events:academy_all_events') + '?limit=5&offset=10'
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_event',
                                     role='potato',
                                     syllabus=True,
                                     event=True)

        base = model.copy()
        del base['event']

        models = [model] + [
            self.generate_models(event=True, models=base) for _ in range(0, 9)
        ]
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': 'http://testserver/v1/events/academy/event?limit=5',
            'next': None,
            'previous':
            'http://testserver/v1/events/academy/event?limit=5&offset=5',
            'last': None,
            'results': []
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.all_event_dict(),
                         [{
                             'academy_id': model['event'].academy_id,
                             'author_id': model['event'].author_id,
                             'banner': model['event'].banner,
                             'capacity': model['event'].capacity,
                             'description': None,
                             'ending_at': model['event'].ending_at,
                             'event_type_id': None,
                             'eventbrite_id': None,
                             'eventbrite_organizer_id': None,
                             'eventbrite_status': None,
                             'eventbrite_url': None,
                             'excerpt': None,
                             'host_id': model['event'].host_id,
                             'id': model['event'].id,
                             'lang': None,
                             'online_event': False,
                             'organization_id': None,
                             'published_at': None,
                             'starting_at': model['event'].starting_at,
                             'status': 'DRAFT',
                             'sync_desc': None,
                             'sync_status': 'PENDING',
                             'title': None,
                             'url': model['event'].url,
                             'venue_id': None
                         } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_all_academy_events_with_data_testing_cache(self):
        """Test /cohort without auth"""
        cache_keys = [
            'Event__academy_id=1&event_id=None&city=None&'
            'country=None&zip_code=None&upcoming=None&past=None&limit=None&offset=None'
        ]

        self.assertEqual(self.cache.keys(), [])

        old_models = self.test_all_academy_events()
        self.assertEqual(self.cache.keys(), cache_keys)

        self.test_all_academy_events(old_models)
        self.assertEqual(self.cache.keys(), cache_keys)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_event_type_no_results(self):
        self.headers(academy=1)
        url = reverse_lazy('events:type')
        self.generate_models(authenticate=True)

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_cohort_with_data_testing_cache_and_remove_in_post(self):
        """Test /cohort without auth"""
        cache_keys = [
            'Event__academy_id=1&event_id=None&city=None&'
            'country=None&zip_code=None&upcoming=None&past=None&limit=None&offset=None'
        ]

        self.assertEqual(self.cache.keys(), [])

        old_model = self.test_all_academy_events()
        self.assertEqual(self.cache.keys(), cache_keys)

        self.headers(academy=1)

        base = old_model[0].copy()

        del base['profile_academy']
        del base['capability']
        del base['role']
        del base['user']

        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_event',
                                     role='potato2',
                                     models=base)

        url = reverse_lazy('events:academy_all_events')
        current_date = self.datetime_now()
        data = {
            'url': 'https://www.google.com/',
            'banner': 'https://www.google.com/banner',
            'capacity': 11,
            'starting_at': self.datetime_to_iso(current_date),
            'ending_at': self.datetime_to_iso(current_date),
        }

        response = self.client.post(url, data)
        json = response.json()

        self.assertDatetime(json['created_at'])
        self.assertDatetime(json['updated_at'])

        del json['created_at']
        del json['updated_at']

        expected = {
            'academy': 1,
            'author': None,
            'description': None,
            'event_type': None,
            'eventbrite_id': None,
            'eventbrite_organizer_id': None,
            'eventbrite_status': None,
            'eventbrite_url': None,
            'excerpt': None,
            'host': None,
            'id': 2,
            'lang': None,
            'online_event': False,
            'organization': None,
            'published_at': None,
            'status': 'DRAFT',
            'sync_desc': None,
            'sync_status': 'PENDING',
            'title': None,
            'venue': None,
            **data,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 201)
        self.assertEqual(self.all_event_dict(), [{
            **self.model_to_dict(old_model[0], 'event'),
        }, {
            'academy_id': 1,
            'author_id': None,
            'banner': 'https://www.google.com/banner',
            'capacity': 11,
            'description': None,
            'ending_at': current_date,
            'event_type_id': None,
            'eventbrite_id': None,
            'eventbrite_organizer_id': None,
            'eventbrite_status': None,
            'eventbrite_url': None,
            'excerpt': None,
            'host_id': None,
            'id': 2,
            'lang': None,
            'online_event': False,
            'organization_id': None,
            'published_at': None,
            'starting_at': current_date,
            'status': 'DRAFT',
            'sync_desc': None,
            'sync_status': 'PENDING',
            'title': None,
            'url': 'https://www.google.com/',
            'venue_id': None,
        }])
        self.assertEqual(self.cache.keys(), [])

        base = [
            self.generate_models(authenticate=True, models=old_model[0]),
            self.generate_models(event=self.get_event(2), models=base),
        ]

        self.test_all_academy_events(base)
        self.assertEqual(self.cache.keys(), cache_keys)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_event_type_with_results(self):
        self.headers(academy=1)
        url = reverse_lazy('events:type')
        event_type_kwargs = {
            "slug": "potato",
            "name": "Potato",
            "created_at": timezone.now(),
            "updated_at": timezone.now()
        }
        model = self.generate_models(authenticate=True,
                                     event=True,
                                     event_type=True,
                                     event_type_kwargs=event_type_kwargs)

        response = self.client.get(url)
        json = response.json()
        expected = [{
            'academy': model['event_type'].academy,
            'id': model['event_type'].id,
            'name': model['event_type'].name,
            'slug': model['event_type'].slug
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

        self.assertEqual(self.all_event_type_dict(), [{
            **self.model_to_dict(model, 'event_type'),
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_event_type_no_match_slug(self):
        self.headers(academy=1)
        url = reverse_lazy('events:type') + '?academy=banana'
        event_type_kwargs = {
            "slug": "potato",
            "name": "Potato",
            "created_at": timezone.now(),
            "updated_at": timezone.now()
        }
        model = self.generate_models(authenticate=True,
                                     event=True,
                                     event_type=True,
                                     event_type_kwargs=event_type_kwargs)

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)

        self.assertEqual(self.all_event_type_dict(), [{
            **self.model_to_dict(model, 'event_type'),
        }])
Exemple #9
0
class MediaTestSuite(MediaTestCase):
    """Test /answer"""
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root_without_auth(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root_wrong_academy(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:root')
        response = self.client.get(url, **{'HTTP_Academy': 1})
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root_without_capability(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('media:root')
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(
            json, {
                'detail':
                "You (user: 1) don't have this capability: read_media for academy 1",
                'status_code': 403
            })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root_without_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        models = self.generate_models(authenticate=True,
                                      profile_academy=True,
                                      capability='read_media',
                                      role='potato')
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_media',
                                     role='potato',
                                     media=True)
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root_with_category(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_media',
                                     role='potato',
                                     media=True,
                                     category=True)
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()
        self.print_model(model, 'media')
        self.print_model(model, 'category')

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash':
            model['media'].hash,
            'hits':
            model['media'].hits,
            'id':
            model['media'].id,
            'mime':
            model['media'].mime,
            'name':
            model['media'].name,
            'slug':
            model['media'].slug,
            'url':
            model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root_with_category_with_bad_academy_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_media',
                                     role='potato',
                                     media=True,
                                     category=True)
        url = reverse_lazy('media:root') + '?academy=0'
        response = self.client.get(url)
        json = response.json()
        self.print_model(model, 'media')
        self.print_model(model, 'category')

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root_with_category_with_academy_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_media',
                                     role='potato',
                                     media=True,
                                     category=True)
        url = reverse_lazy('media:root') + '?academy=1'
        response = self.client.get(url)
        json = response.json()
        self.print_model(model, 'media')
        self.print_model(model, 'category')

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash':
            model['media'].hash,
            'hits':
            model['media'].hits,
            'id':
            model['media'].id,
            'mime':
            model['media'].mime,
            'name':
            model['media'].name,
            'slug':
            model['media'].slug,
            'url':
            model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root_with_category_with_bad_mime_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_media',
                                     role='potato',
                                     media=True,
                                     category=True)
        url = reverse_lazy('media:root') + '?mime=application/hitman'
        response = self.client.get(url)
        json = response.json()
        self.print_model(model, 'media')
        self.print_model(model, 'category')

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root_with_category_with_mime_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_media',
                                     role='potato',
                                     media=True,
                                     category=True)
        url = reverse_lazy('media:root') + '?mime=' + model['media'].mime
        response = self.client.get(url)
        json = response.json()
        self.print_model(model, 'media')
        self.print_model(model, 'category')

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash':
            model['media'].hash,
            'hits':
            model['media'].hits,
            'id':
            model['media'].id,
            'mime':
            model['media'].mime,
            'name':
            model['media'].name,
            'slug':
            model['media'].slug,
            'url':
            model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    def test_root_pagination_with_105(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True,
                                    role=role,
                                    capability='read_media',
                                    profile_academy=True)

        models = [
            self.generate_models(media=True, models=base)
            for _ in range(0, 105)
        ]
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'categories': [],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        } for model in models if model['media'].id < 101]

        self.assertEqual(json, expected)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    def test_root_pagination_first_five(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True,
                                    role=role,
                                    capability='read_media',
                                    profile_academy=True)

        models = [
            self.generate_models(media=True, models=base)
            for _ in range(0, 10)
        ]
        url = reverse_lazy('media:root') + '?limit=5&offset=0'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count':
            10,
            'first':
            None,
            'last':
            'http://testserver/v1/media/?limit=5&offset=5',
            'next':
            'http://testserver/v1/media/?limit=5&offset=5',
            'previous':
            None,
            'results': [{
                'categories': [],
                'hash': model['media'].hash,
                'hits': model['media'].hits,
                'id': model['media'].id,
                'mime': model['media'].mime,
                'name': model['media'].name,
                'slug': model['media'].slug,
                'url': model['media'].url
            } for model in models if model['media'].id < 6]
        }

        self.assertEqual(json, expected)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    def test_root_pagination_last_five(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True,
                                    role=role,
                                    capability='read_media',
                                    profile_academy=True)

        models = [
            self.generate_models(media=True, models=base)
            for _ in range(0, 10)
        ]
        url = reverse_lazy('media:root') + '?limit=5&offset=5'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count':
            10,
            'first':
            'http://testserver/v1/media/?limit=5',
            'last':
            None,
            'next':
            None,
            'previous':
            'http://testserver/v1/media/?limit=5',
            'results': [{
                'categories': [],
                'hash': model['media'].hash,
                'hits': model['media'].hits,
                'id': model['media'].id,
                'mime': model['media'].mime,
                'name': model['media'].name,
                'slug': model['media'].slug,
                'url': model['media'].url
            } for model in models if model['media'].id > 5]
        }

        self.assertEqual(json, expected)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    def test_root_pagination_after_last_five(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True,
                                    role=role,
                                    capability='read_media',
                                    profile_academy=True)

        models = [
            self.generate_models(media=True, models=base)
            for _ in range(0, 10)
        ]
        url = reverse_lazy('media:root') + '?limit=5&offset=10'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': 'http://testserver/v1/media/?limit=5',
            'last': None,
            'next': None,
            'previous': 'http://testserver/v1/media/?limit=5&offset=5',
            'results': []
        }

        self.assertEqual(json, expected)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])
class CohortAllTestSuite(AdmissionsTestCase):
    """Test /cohort/all"""
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_without_auth(self):
        """Test /cohort/all without auth"""
        url = reverse_lazy('admissions:cohort_all')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_without_data(self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True)
        url = reverse_lazy('admissions:cohort_all')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_cohort_but_without_profile_academy(self):
        """Test /cohort/all without auth"""
        url = reverse_lazy('admissions:cohort_all')
        model = self.generate_models(authenticate=True, cohort=True)

        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    """
    🔽🔽🔽 Sort querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all__with_data__with_sort(self):
        """Test /cohort/all without auth"""
        base = self.generate_models(authenticate=True,
                                    profile_academy=True,
                                    skip_cohort=True)

        models = [
            self.generate_models(cohort=True, syllabus=True, models=base)
            for _ in range(0, 2)
        ]
        ordened_models = sorted(models,
                                key=lambda x: x['cohort'].slug,
                                reverse=True)

        url = reverse_lazy('admissions:cohort_all') + '?sort=-slug'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model.cohort.id,
            'slug':
            model.cohort.slug,
            'name':
            model.cohort.name,
            'current_day':
            model.cohort.current_day,
            'never_ends':
            model['cohort'].never_ends,
            'private':
            model['cohort'].private,
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model.cohort.kickoff_date.isoformat()),
            'ending_date':
            model.cohort.ending_date,
            'stage':
            model.cohort.stage,
            'language':
            model.cohort.language,
            'syllabus': {
                'version': model.cohort.syllabus.version,
                'certificate': {
                    'id':
                    model.cohort.syllabus.certificate.id,
                    'slug':
                    model.cohort.syllabus.certificate.slug,
                    'name':
                    model.cohort.syllabus.certificate.name,
                    'duration_in_days':
                    model.cohort.syllabus.certificate.duration_in_days,
                }
            },
            'academy': {
                'id': model.cohort.academy.id,
                'slug': model.cohort.academy.slug,
                'name': model.cohort.academy.name,
                'country': {
                    'code': model.cohort.academy.country.code,
                    'name': model.cohort.academy.country.name,
                },
                'city': {
                    'name': model.cohort.academy.city.name,
                },
                'logo_url': model.cohort.academy.logo_url,
            },
        } for model in ordened_models]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_bad_get_academy(self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True)

        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?academy=they-killed-kenny'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_academy(self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     syllabus=True)

        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?academy={model.academy.slug}'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model.cohort.id,
            'slug':
            model.cohort.slug,
            'name':
            model.cohort.name,
            'never_ends':
            model['cohort'].never_ends,
            'private':
            model['cohort'].private,
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model.cohort.kickoff_date.isoformat()),
            'ending_date':
            model.cohort.ending_date,
            'stage':
            model.cohort.stage,
            'language':
            model.cohort.language,
            'current_day':
            model.cohort.current_day,
            'syllabus': {
                'version': model.cohort.syllabus.version,
                'certificate': {
                    'id':
                    model.cohort.syllabus.certificate.id,
                    'slug':
                    model.cohort.syllabus.certificate.slug,
                    'name':
                    model.cohort.syllabus.certificate.name,
                    'duration_in_days':
                    model.cohort.syllabus.certificate.duration_in_days,
                }
            },
            'academy': {
                'id': model.cohort.academy.id,
                'slug': model.cohort.academy.slug,
                'name': model.cohort.academy.name,
                'country': {
                    'code': model.cohort.academy.country.code,
                    'name': model.cohort.academy.country.name,
                },
                'city': {
                    'name': model.cohort.academy.city.name,
                },
                'logo_url': model.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_bad_get_location(self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True)

        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?location=they-killed-kenny'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_location(self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     syllabus=True)

        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?location={model.academy.slug}'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model.cohort.id,
            'slug':
            model.cohort.slug,
            'name':
            model.cohort.name,
            'never_ends':
            model['cohort'].never_ends,
            'private':
            model['cohort'].private,
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model.cohort.kickoff_date.isoformat()),
            'ending_date':
            model.cohort.ending_date,
            'stage':
            model.cohort.stage,
            'language':
            model.cohort.language,
            'current_day':
            model.cohort.current_day,
            'syllabus': {
                'version': model.cohort.syllabus.version,
                'certificate': {
                    'id':
                    model.cohort.syllabus.certificate.id,
                    'slug':
                    model.cohort.syllabus.certificate.slug,
                    'name':
                    model.cohort.syllabus.certificate.name,
                    'duration_in_days':
                    model.cohort.syllabus.certificate.duration_in_days,
                }
            },
            'academy': {
                'id': model.cohort.academy.id,
                'slug': model.cohort.academy.slug,
                'name': model.cohort.academy.name,
                'country': {
                    'code': model.cohort.academy.country.code,
                    'name': model.cohort.academy.country.name,
                },
                'city': {
                    'name': model.cohort.academy.city.name,
                },
                'logo_url': model.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_location_with_comma(self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     syllabus=True)

        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?location={model.academy.slug},they-killed-kenny'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model.cohort.id,
            'slug':
            model.cohort.slug,
            'name':
            model.cohort.name,
            'never_ends':
            model['cohort'].never_ends,
            'private':
            model['cohort'].private,
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model.cohort.kickoff_date.isoformat()),
            'ending_date':
            model.cohort.ending_date,
            'stage':
            model.cohort.stage,
            'language':
            model.cohort.language,
            'current_day':
            model.cohort.current_day,
            'syllabus': {
                'version': model.cohort.syllabus.version,
                'certificate': {
                    'id':
                    model.cohort.syllabus.certificate.id,
                    'slug':
                    model.cohort.syllabus.certificate.slug,
                    'name':
                    model.cohort.syllabus.certificate.name,
                    'duration_in_days':
                    model.cohort.syllabus.certificate.duration_in_days,
                }
            },
            'academy': {
                'id': model.cohort.academy.id,
                'slug': model.cohort.academy.slug,
                'name': model.cohort.academy.name,
                'country': {
                    'code': model.cohort.academy.country.code,
                    'name': model.cohort.academy.country.name,
                },
                'city': {
                    'name': model.cohort.academy.city.name,
                },
                'logo_url': model.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_upcoming_false(self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     syllabus=True)

        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?upcoming=false'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model.cohort.id,
            'slug':
            model.cohort.slug,
            'name':
            model.cohort.name,
            'never_ends':
            model['cohort'].never_ends,
            'private':
            model['cohort'].private,
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model.cohort.kickoff_date.isoformat()),
            'ending_date':
            model.cohort.ending_date,
            'stage':
            model.cohort.stage,
            'language':
            model.cohort.language,
            'current_day':
            model.cohort.current_day,
            'syllabus': {
                'version': model.cohort.syllabus.version,
                'certificate': {
                    'id':
                    model.cohort.syllabus.certificate.id,
                    'slug':
                    model.cohort.syllabus.certificate.slug,
                    'name':
                    model.cohort.syllabus.certificate.name,
                    'duration_in_days':
                    model.cohort.syllabus.certificate.duration_in_days,
                }
            },
            'academy': {
                'id': model.cohort.academy.id,
                'slug': model.cohort.academy.slug,
                'name': model.cohort.academy.name,
                'country': {
                    'code': model.cohort.academy.country.code,
                    'name': model.cohort.academy.country.name,
                },
                'city': {
                    'name': model.cohort.academy.city.name,
                },
                'logo_url': model.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_upcoming_true_without_current_data(
            self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True)

        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?upcoming=true'
        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_upcoming_true_with_current_data(
            self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     impossible_kickoff_date=True,
                                     syllabus=True)
        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?upcoming=true'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model.cohort.id,
            'slug':
            model.cohort.slug,
            'name':
            model.cohort.name,
            'never_ends':
            model['cohort'].never_ends,
            'private':
            model['cohort'].private,
            'kickoff_date':
            self.datetime_to_iso(model['cohort'].kickoff_date),
            'ending_date':
            model.cohort.ending_date,
            'stage':
            model.cohort.stage,
            'language':
            model.cohort.language,
            'current_day':
            model.cohort.current_day,
            'syllabus': {
                'version': model.cohort.syllabus.version,
                'certificate': {
                    'id':
                    model.cohort.syllabus.certificate.id,
                    'slug':
                    model.cohort.syllabus.certificate.slug,
                    'name':
                    model.cohort.syllabus.certificate.name,
                    'duration_in_days':
                    model.cohort.syllabus.certificate.duration_in_days,
                }
            },
            'academy': {
                'id': model.cohort.academy.id,
                'slug': model.cohort.academy.slug,
                'name': model.cohort.academy.name,
                'country': {
                    'code': model.cohort.academy.country.code,
                    'name': model.cohort.academy.country.name,
                },
                'city': {
                    'name': model.cohort.academy.city.name,
                },
                'logo_url': model.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data(self):
        """Test /cohort/all without auth"""
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     syllabus=True)

        url = reverse_lazy('admissions:cohort_all')
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id':
            model.cohort.id,
            'slug':
            model.cohort.slug,
            'name':
            model.cohort.name,
            'never_ends':
            model['cohort'].never_ends,
            'private':
            model['cohort'].private,
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model.cohort.kickoff_date.isoformat()),
            'ending_date':
            model.cohort.ending_date,
            'stage':
            model.cohort.stage,
            'language':
            model.cohort.language,
            'current_day':
            model.cohort.current_day,
            'syllabus': {
                'version': model.cohort.syllabus.version,
                'certificate': {
                    'id':
                    model.cohort.syllabus.certificate.id,
                    'slug':
                    model.cohort.syllabus.certificate.slug,
                    'name':
                    model.cohort.syllabus.certificate.name,
                    'duration_in_days':
                    model.cohort.syllabus.certificate.duration_in_days,
                }
            },
            'academy': {
                'id': model.cohort.academy.id,
                'slug': model.cohort.academy.slug,
                'name': model.cohort.academy.name,
                'country': {
                    'code': model.cohort.academy.country.code,
                    'name': model.cohort.academy.country.name,
                },
                'city': {
                    'name': model.cohort.academy.city.name,
                },
                'logo_url': model.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_but_is_private(self):
        """Test /cohort/all without auth"""
        cohort_kwargs = {'private': True}
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     syllabus=True,
                                     cohort_kwargs=cohort_kwargs)

        url = reverse_lazy('admissions:cohort_all')
        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_cohort_dict(), [{
            **self.model_to_dict(model, 'cohort')
        }])
class AcademyCohortTestSuite(MonitoringTestCase):
    """
    🔽🔽🔽 With bad entity 🔽🔽🔽
    """
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def tests_send_survey_reminder_no_survey(self):

        monitor_script_kwargs = {"script_slug": "send_survey_reminder"}

        model = self.generate_models(academy=True, monitor_script=True,
                                     monitor_script_kwargs=monitor_script_kwargs
                                     )

        script = run_script(model.monitor_script)

        del script['slack_payload']
        del script['text']

        expected = {
            "severity_level": 5,
            "status": 'OPERATIONAL',
        }

        self.assertEqual(script, expected)

        self.assertEqual(self.all_monitor_script_dict(), [{
            **self.model_to_dict(model, 'monitor_script'),
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def tests_send_survey_ending_date_less_than_now(self):

        monitor_script_kwargs = {"script_slug": "send_survey_reminder"}
        ending_date = timezone.now() - timedelta(weeks=1)
        sent_at = timezone.now() - timedelta(weeks=5)
        model = self.generate_models(cohort=True, monitor_script=True,
                                     monitor_script_kwargs=monitor_script_kwargs,
                                     cohort_kwargs={
                                         'ending_date': ending_date},
                                     survey=True, survey_kwargs={'sent_at': sent_at})

        script = run_script(model.monitor_script)

        del script['slack_payload']
        del script['text']
        
        expected = {
            "severity_level": 5,
            "status": 'OPERATIONAL',
        }
        self.assertEqual(script, expected)

        self.assertEqual(self.all_monitor_script_dict(), [{
            **self.model_to_dict(model, 'monitor_script'),
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def tests_send_survey_kickoff_date_greater_than_now(self):

        monitor_script_kwargs = {"script_slug": "send_survey_reminder"}
        kickoff_date = timezone.now() + timedelta(weeks=1)
        sent_at = timezone.now() - timedelta(weeks=5)
        model = self.generate_models(cohort=True, monitor_script=True,
                                     monitor_script_kwargs=monitor_script_kwargs,
                                     cohort_kwargs={
                                         'kickoff_date': kickoff_date},
                                     survey=True, survey_kwargs={'sent_at': sent_at})

        script = run_script(model.monitor_script)

        del script['slack_payload']
        del script['text']

        expected = {
            "severity_level": 5,
            "status": 'OPERATIONAL'
        }
        self.assertEqual(script, expected)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def tests_send_survey_latest_survey_less_four_weeks(self):

        monitor_script_kwargs = {"script_slug": "send_survey_reminder"}
        ending_date = timezone.now() + timedelta(weeks=2)
        kickoff_date = timezone.now() - timedelta(weeks=12)

        base = self.generate_models(academy=True, cohort=True, monitor_script=True,
                                    monitor_script_kwargs=monitor_script_kwargs,
                                    cohort_kwargs={'ending_date': ending_date,
                                                   "kickoff_date": kickoff_date})
        sent_at = timezone.now() - timedelta(weeks=2)
        models = [self.generate_models(survey=True, survey_kwargs={'sent_at': sent_at},
                                       models=base)
                  for _ in range(0, 2)]

        script = run_script(models[1].monitor_script)

        del script['slack_payload']
        del script['text']

        expected = {
            "severity_level": 5,
            "status": 'OPERATIONAL',
        }
        self.assertEqual(script, expected)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def tests_send_survey_latest_survey_greater_four_weeks(self):

        monitor_script_kwargs = {"script_slug": "send_survey_reminder"}
        ending_date = timezone.now() + timedelta(days=2)
        kickoff_date = timezone.now() - timedelta(days=2)

        base = self.generate_models(academy=True, cohort=True, monitor_script=True,
                                    monitor_script_kwargs=monitor_script_kwargs,
                                    cohort_kwargs={'ending_date': ending_date,
                                                   "kickoff_date": kickoff_date})

        sent_at = timezone.now() - timedelta(weeks=6)

        models = [self.generate_models(survey=True, survey_kwargs={'sent_at': sent_at},
                                       models=base)
                  for _ in range(0, 2)]

        script = run_script(models[1].monitor_script)

        del script['slack_payload']
        del script['text']


        expected = {
                    'severity_level': 5,
                    'error_slug': None,
                    'status': 'MINOR',
                    }

        self.assertEqual(script, expected)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def tests_send_survey_latest_survey_greater_four_weeks_two_cohorts_two_survey(self):

        monitor_script_kwargs = {"script_slug": "send_survey_reminder"}
        ending_date = timezone.now() + timedelta(days=2)
        kickoff_date = timezone.now() - timedelta(days=2)

        base = self.generate_models(academy=True,  monitor_script=True,
                                    monitor_script_kwargs=monitor_script_kwargs,
                                    )

        sent_at = timezone.now() - timedelta(weeks=6)

        models = [self.generate_models(survey=True, cohort=True, survey_kwargs={'sent_at': sent_at},
                                       models=base, cohort_kwargs={'ending_date': ending_date,
                                                                   "kickoff_date": kickoff_date})
                  for _ in range(0, 2)]

        script = run_script(models[1].monitor_script)
        del script['slack_payload']
        del script['text']

        expected = {
                    'severity_level': 5,
                    'status': 'MINOR',
                    'error_slug': None,
                    }

        self.assertEqual(script, expected)
Exemple #12
0
class MediaTestSuite(MediaTestCase):
    """Test /answer"""

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_file_slug_without_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        models = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')
        url = reverse_lazy('media:file_slug', kwargs={'media_slug': 'they-killed-kenny'})
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': 'Resource not found',
            'status_code': 404
        })
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_media_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_file_slug_without_data_with_mask_true(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')
        url = reverse_lazy('media:file_slug', kwargs={'media_slug': 'they-killed-kenny'}) + '?mask=true'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': 'Resource not found',
            'status_code': 404
        })
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_media_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_file_slug(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True)
        url = reverse_lazy('media:file_slug', kwargs={'media_slug': model['media'].slug})
        response = self.client.get(url)

        self.assertEqual(response.url, model['media'].url)
        self.assertEqual(response.status_code, status.HTTP_301_MOVED_PERMANENTLY)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media'),
            'hits': model['media'].hits + 1,
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(REQUESTS_PATH['get'], apply_requests_get_mock([(200, 'https://potato.io', 'ok')]))
    def test_file_slug_with_mask_true(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        media_kwargs = {'url': 'https://potato.io'}
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True,
            media_kwargs=media_kwargs)
        url = reverse_lazy('media:file_slug', kwargs={'media_slug': model['media'].slug}) + '?mask=true'
        response = self.client.get(url)

        self.assertEqual(response.getvalue().decode("utf-8"), 'ok')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media'),
            'hits': model['media'].hits + 1,
        }])
class CohortUserTestSuite(MarketingTestCase):
    """Test /academy/lead"""

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_lead_without_auth(self):
        """Test /cohort/:id/user without auth"""
        url = reverse_lazy('marketing:academy_lead')
        response = self.client.get(url)
        json = response.json()
        expected = {
            'detail': 'Authentication credentials were not provided.',
            'status_code': 401
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(self.all_form_entry_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_lead_without_academy_header(self):
        """Test /cohort/:id/user without auth"""
        url = reverse_lazy('marketing:academy_lead')
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato')

        response = self.client.get(url)
        json = response.json()
        expected = {
            'detail': 'Missing academy_id parameter expected for the endpoint url or '
                "'Academy' header",
            'status_code': 403
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(self.all_form_entry_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_lead_without_data(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        url = reverse_lazy('marketing:academy_lead')
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato')

        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_lead(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        url = reverse_lazy('marketing:academy_lead')
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato', form_entry=True)

        response = self.client.get(url)
        json = response.json()

        self.assertDatetime(json[0]['created_at'])
        del json[0]['created_at']

        expected = [{
            'country': None,
            'course': None,
            'email': None,
            'first_name': '',
            'id': 1,
            'language': 'en',
            'last_name': '',
            'lead_type': None,
            'location': None,
            'storage_status': 'PENDING',
            'tags': '',
            'utm_campaign': None,
            'utm_medium': None,
            'utm_source': None,
            'utm_url': None,
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        }])

    # TODO: we need test get method with the querystring

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_lead_delete_without_auth(self):
        """Test /cohort/:id/user without auth"""
        url = reverse_lazy('marketing:academy_lead')
        response = self.client.delete(url)
        json = response.json()
        expected = {
            'detail': 'Authentication credentials were not provided.',
            'status_code': 401
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(self.all_form_entry_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_lead_without_args_in_url_or_bulk(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='crud_lead', role='potato')
        url = reverse_lazy('marketing:academy_lead')
        response = self.client.delete(url)
        json = response.json()
        expected = {
            'detail': "Missing parameters in the querystring",
            'status_code': 400
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(self.all_form_entry_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_lead_in_bulk_with_one(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        many_fields = ['id']

        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='crud_lead', role='potato', academy=True,
            active_campaign_academy=True)

        for field in many_fields:
            form_entry_kwargs = generate_form_entry_kwargs()
            model = self.generate_models(form_entry=True, contact=True,
                automation=True, form_entry_kwargs=form_entry_kwargs, models=base)

            url = (reverse_lazy('marketing:academy_lead') + f'?{field}=' +
                str(getattr(model['form_entry'], field)))
            response = self.client.delete(url)

            if response.status_code != 204:
                print(response.json())

            self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
            self.assertEqual(self.all_form_entry_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_lead_in_bulk_with_two(self):
        """Test /cohort/:id/user without auth"""
        self.headers(academy=1)
        many_fields = ['id']

        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='crud_lead', role='potato', academy=True,
            active_campaign_academy=True)

        for field in many_fields:
            form_entry_kwargs = generate_form_entry_kwargs()
            model1 = self.generate_models(form_entry=True, contact=True,
                automation=True, form_entry_kwargs=form_entry_kwargs, models=base)

            form_entry_kwargs = generate_form_entry_kwargs()
            model2 = self.generate_models(form_entry=True, contact=True,
                automation=True, form_entry_kwargs=form_entry_kwargs, models=base)

            url = (reverse_lazy('marketing:academy_lead') + f'?{field}=' +
                str(getattr(model1['form_entry'], field)) + ',' +
                str(getattr(model2['form_entry'], field)))
            response = self.client.delete(url)

            if response.status_code != 204:
                print(response.json())

            self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
            self.assertEqual(self.all_form_entry_dict(), [])


    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_cohort_with_ten_datas_with_location_with_comma_just_get_100(self):
        """Test /cohort without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato')

        models = [self.generate_models(form_entry=True, models=base) for _ in range(0, 105)]
        ordened_models = sorted(models, key=lambda x: x['form_entry'].created_at,
            reverse=True)

        url = reverse_lazy('marketing:academy_lead')
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'country': model['form_entry'].country,
            'course': model['form_entry'].course,
            'email': model['form_entry'].email,
            'first_name': model['form_entry'].first_name,
            'id': model['form_entry'].id,
            'language': model['form_entry'].language,
            'last_name': model['form_entry'].last_name,
            'lead_type': model['form_entry'].lead_type,
            'location': model['form_entry'].location,
            'storage_status': model['form_entry'].storage_status,
            'tags': model['form_entry'].tags,
            'utm_campaign': model['form_entry'].utm_campaign,
            'utm_medium': model['form_entry'].utm_medium,
            'utm_source': model['form_entry'].utm_source,
            'utm_url': model['form_entry'].utm_url,
            'created_at': self.datetime_to_iso(model['form_entry'].created_at),
        } for model in ordened_models][:100]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_cohort_with_ten_datas_with_location_with_comma_pagination_first_five(self):
        """Test /cohort without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato')

        models = [self.generate_models(form_entry=True, models=base) for _ in range(0, 10)]
        ordened_models = sorted(models, key=lambda x: x['form_entry'].created_at,
            reverse=True)

        url = reverse_lazy('marketing:academy_lead') + '?limit=5&offset=0'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': None,
            'next': 'http://testserver/v1/marketing/academy/lead?limit=5&'
                f'offset=5',
            'previous': None,
            'last': 'http://testserver/v1/marketing/academy/lead?limit=5&'
                f'offset=5',
            'results': [{
                'country': model['form_entry'].country,
                'course': model['form_entry'].course,
                'email': model['form_entry'].email,
                'first_name': model['form_entry'].first_name,
                'id': model['form_entry'].id,
                'language': model['form_entry'].language,
                'last_name': model['form_entry'].last_name,
                'lead_type': model['form_entry'].lead_type,
                'location': model['form_entry'].location,
                'storage_status': model['form_entry'].storage_status,
                'tags': model['form_entry'].tags,
                'utm_campaign': model['form_entry'].utm_campaign,
                'utm_medium': model['form_entry'].utm_medium,
                'utm_source': model['form_entry'].utm_source,
                'utm_url': model['form_entry'].utm_url,
                'created_at': self.datetime_to_iso(model['form_entry'].created_at),
            } for model in ordened_models][:5],
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_cohort_with_ten_datas_with_location_with_comma_pagination_last_five(self):
        """Test /cohort without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato')

        models = [self.generate_models(form_entry=True, models=base) for _ in range(0, 10)]
        ordened_models = sorted(models, key=lambda x: x['form_entry'].created_at,
            reverse=True)

        url = reverse_lazy('marketing:academy_lead') + '?limit=5&offset=5'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': 'http://testserver/v1/marketing/academy/lead?limit=5',
            'next': None,
            'previous': 'http://testserver/v1/marketing/academy/lead?limit=5',
            'last': None,
            'results': [{
                'country': model['form_entry'].country,
                'course': model['form_entry'].course,
                'email': model['form_entry'].email,
                'first_name': model['form_entry'].first_name,
                'id': model['form_entry'].id,
                'language': model['form_entry'].language,
                'last_name': model['form_entry'].last_name,
                'lead_type': model['form_entry'].lead_type,
                'location': model['form_entry'].location,
                'storage_status': model['form_entry'].storage_status,
                'tags': model['form_entry'].tags,
                'utm_campaign': model['form_entry'].utm_campaign,
                'utm_medium': model['form_entry'].utm_medium,
                'utm_source': model['form_entry'].utm_source,
                'utm_url': model['form_entry'].utm_url,
                'created_at': self.datetime_to_iso(model['form_entry'].created_at),
            } for model in ordened_models][5:],
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_cohort_with_ten_datas_with_location_with_comma_pagination_after_last_five(self):
        """Test /cohort without auth"""
        self.headers(academy=1)
        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_lead', role='potato')

        models = [self.generate_models(form_entry=True, models=base) for _ in range(0, 10)]

        url = reverse_lazy('marketing:academy_lead') + '?limit=5&offset=10'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': 'http://testserver/v1/marketing/academy/lead?limit=5',
            'next': None,
            'previous': 'http://testserver/v1/marketing/academy/lead?limit=5&'
                f'offset=5',
            'last': None,
            'results': [],
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_form_entry_dict(), [{
            **self.model_to_dict(model, 'form_entry')
        } for model in models])
Exemple #14
0
class SendSurveyTestSuite(FeedbackTestCase):
    """Test /answer"""
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_send_question_without_cohort(self):
        """Test /answer without auth"""
        model = self.generate_models(user=True)

        try:
            send_question(model['user'])
        except Exception as e:
            self.assertEquals(
                str(e),
                ('Impossible to determine the student cohort, maybe it has '
                 'more than one, or cero.'))

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(MAILGUN_PATH['post'], apply_requests_post_mock())
    def test_send_question_with_one_user_with_two_cohort(self):
        """Test /answer without auth"""
        model = self.generate_models(cohort_user=True, cohort_user_two=True)

        try:
            send_question(model['user'])
        except Exception as e:
            self.assertEquals(
                str(e),
                ('Impossible to determine the student cohort, maybe it has '
                 'more than one, or cero.'))

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(MAILGUN_PATH['post'], apply_requests_post_mock())
    def test_send_question_with_cohort_with_slack_user_with_slack_team(self):
        """Test /answer without auth"""
        mock_mailgun = MAILGUN_INSTANCES['post']
        mock_mailgun.call_args_list = []

        mock_slack = SLACK_INSTANCES['request']
        mock_slack.call_args_list = []

        model = self.generate_models(user=True,
                                     cohort_user=True,
                                     lang='en',
                                     slack_user=True,
                                     slack_team=True)
        academy = model['cohort'].academy.name
        certificate = model['cohort'].certificate.name

        send_question(model['user'])

        expected = [{
            'academy_id': None,
            'cohort_id': 1,
            'comment': None,
            'event_id': None,
            'highest': 'very good',
            'id': 1,
            'lang': 'en',
            'lowest': 'not good',
            'mentor_id': None,
            'opened_at': None,
            'score': None,
            'status': 'SENT',
            'survey_id': None,
            'title':
            f'How has been your experience studying {certificate} so far?',
            'token_id': 1,
            'user_id': 1,
        }]

        dicts = [
            answer for answer in self.all_answer_dict()
            if isinstance(answer['created_at'], datetime)
            and answer.pop('created_at')
        ]
        self.assertEqual(dicts, expected)

        # TODO: this function is broken, we have to fix it
        # self.check_email_contain_a_correct_token('en', academy, dicts, mock_mailgun, model)

        self.assertEqual(mock_slack.call_args_list, [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(MAILGUN_PATH['post'], apply_requests_post_mock())
    @patch(SLACK_PATH['request'], apply_slack_requests_request_mock())
    def test_send_question_with_cohort_with_slack_user_with_slack_team_with_credentials_slack(
            self):
        """Test /answer without auth"""
        mock_mailgun = MAILGUN_INSTANCES['post']
        mock_mailgun.call_args_list = []

        mock_slack = SLACK_INSTANCES['request']
        mock_slack.call_args_list = []

        model = self.generate_models(user=True,
                                     cohort_user=True,
                                     lang='en',
                                     slack_user=True,
                                     slack_team=True,
                                     credentials_slack=True,
                                     academy=True)
        academy = model['cohort'].academy.name
        certificate = model['cohort'].certificate.name

        try:
            send_question(model['user'])
        except Exception as e:
            self.assertEqual(str(e), f"Team owner not has slack credentials")

        expected = [{
            'id': 1,
            'title':
            f'How has been your experience studying {certificate} so far?',
            'lowest': 'not good',
            'highest': 'very good',
            'lang': 'en',
            'cohort_id': 1,
            'academy_id': None,
            'mentor_id': None,
            'event_id': None,
            'token_id': 1,
            'score': None,
            'comment': None,
            'survey_id': None,
            'status': 'PENDING',
            'user_id': 1,
            'opened_at': None,
        }]

        dicts = [
            answer for answer in self.all_answer_dict()
            if isinstance(answer['created_at'], datetime)
            and answer.pop('created_at')
        ]
        self.assertEqual(dicts, expected)

        # TODO: this function is broken, we have to fix it
        # self.check_email_contain_a_correct_token('en', academy, dicts, mock_mailgun, model)

        self.assertEqual(mock_slack.call_args_list, [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(MAILGUN_PATH['post'], apply_requests_post_mock())
    @patch(SLACK_PATH['request'], apply_slack_requests_request_mock())
    def test_send_question_with_cohort_lang_en(self):
        """Test /answer without auth"""
        mock_mailgun = MAILGUN_INSTANCES['post']
        mock_mailgun.call_args_list = []

        mock_slack = SLACK_INSTANCES['request']
        mock_slack.call_args_list = []

        model = self.generate_models(user=True,
                                     cohort_user=True,
                                     lang='en',
                                     slack_user=True,
                                     slack_team=True,
                                     credentials_slack=True,
                                     academy=True,
                                     slack_team_owner=True)
        academy = model['cohort'].academy.name
        certificate = model['cohort'].certificate.name

        try:
            send_question(model['user'])
        except Exception as e:
            self.assertEqual(str(e), f"Team owner not has slack credentials")

        expected = [{
            'id': 1,
            'title':
            f'How has been your experience studying {certificate} so far?',
            'lowest': 'not good',
            'highest': 'very good',
            'lang': 'en',
            'cohort_id': 1,
            'academy_id': None,
            'mentor_id': None,
            'event_id': None,
            'token_id': 1,
            'score': None,
            'comment': None,
            'status': 'SENT',
            'user_id': 1,
            'survey_id': None,
            'opened_at': None,
        }]

        print('asdasd', model['slack_team'].__dict__)
        dicts = [
            answer for answer in self.all_answer_dict()
            if isinstance(answer['created_at'], datetime)
            and answer.pop('created_at')
        ]
        self.assertEqual(dicts, expected)

        # TODO: this function is broken, we have to fix it
        # self.check_email_contain_a_correct_token('en', academy, dicts, mock_mailgun, model)

        # TODO: this function is broken, we have to fix it
        # self.check_stack_contain_a_correct_token('en', academy, mock_slack, model)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(MAILGUN_PATH['post'], apply_requests_post_mock())
    @patch(SLACK_PATH['request'], apply_slack_requests_request_mock())
    def test_send_question_with_cohort_lang_es(self):
        """Test /answer without auth"""
        mock_mailgun = MAILGUN_INSTANCES['post']
        mock_mailgun.call_args_list = []

        mock_slack = SLACK_INSTANCES['request']
        mock_slack.call_args_list = []

        model = self.generate_models(user=True,
                                     cohort_user=True,
                                     lang='es',
                                     slack_user=True,
                                     slack_team=True,
                                     credentials_slack=True,
                                     academy=True,
                                     slack_team_owner=True)
        academy = model['cohort'].academy.name
        certificate = model['cohort'].certificate.name

        send_question(model['user'])
        expected = [{
            'academy_id': None,
            'cohort_id': 1,
            'comment': None,
            'event_id': None,
            'highest': 'muy buena',
            'id': 1,
            'lang': 'es',
            'lowest': 'mala',
            'mentor_id': None,
            'opened_at': None,
            'score': None,
            'status': 'SENT',
            'survey_id': None,
            'title': f'¿Cómo ha sido tu experiencia estudiando {certificate}?',
            'token_id': 1,
            'user_id': 1,
        }]

        dicts = [
            answer for answer in self.all_answer_dict()
            if isinstance(answer['created_at'], datetime)
            and answer.pop('created_at')
        ]
        self.assertEqual(dicts, expected)
        self.assertEqual(self.count_token(), 1)
Exemple #15
0
class academyTestSuite(AdmissionsTestCase):
    """Test /academy"""

    def test_academy_without_auth(self):
        """Test /academy without auth"""
        url = reverse_lazy('admissions:academy')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': 'Authentication credentials were not provided.',
            'status_code': status.HTTP_401_UNAUTHORIZED
        })
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_academy_without_data(self):
        """Test /academy without auth"""
        url = reverse_lazy('admissions:academy')
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_academy(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_with_data(self):
        """Test /academy without auth"""
        self.generate_models(authenticate=True, academy=True)
        url = reverse_lazy('admissions:academy')
        model_dict = self.remove_dinamics_fields(self.academy.__dict__)

        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'id': self.academy.id,
            'name': self.academy.name,
            'slug': self.academy.slug,
            'street_address': self.academy.street_address,
            'country': self.academy.country.code,
            'city': self.academy.city.id,
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_academy(), 1)
        self.assertEqual(self.get_academy_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_new_without_require_fields(self):
        """Test /academy without auth"""
        url = reverse_lazy('admissions:academy')
        self.generate_models(authenticate=True, academy=True)
        data = {}
        response = self.client.post(url, data)
        json = response.json()

        self.assertEqual(json, {
            # 'city': ['This field is required.'],
            # 'country': ['This field is required.'],
            'slug': ['This field is required.'],
            'name': ['This field is required.'],
            'street_address': ['This field is required.']
        })
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_academy_new_element(self):
        """Test /academy without auth"""
        url = reverse_lazy('admissions:academy')
        self.generate_models(authenticate=True, country=True)
        data = {
            'slug': 'oh-my-god',
            'name': 'they killed kenny',
            'street_address': 'you bastards',
            'country': self.country.code,
            'city': self.city.id,
        }
        response = self.client.post(url, data)
        json = response.json()

        expected = {
            'id': 1,
        }
        expected.update(data)
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        model_dict = self.get_academy_dict(1)
        data['country_id'] = data['country']
        data['city_id'] = data['city']
        del data['country']
        del data['city']
        model_dict.update(data)

        self.assertEqual(self.count_academy(), 1)
        self.assertEqual(self.get_academy_dict(1), model_dict)
Exemple #16
0
class MediaTestSuite(MediaTestCase):
    """Test /answer"""
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_category_without_auth(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:category')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_category_wrong_academy(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:category')
        response = self.client.get(url, **{'HTTP_Academy': 1})
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_category_without_capability(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('media:category')
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(
            json, {
                'detail':
                "You (user: 1) don't have this capability: read_media for academy 1",
                'status_code': 403
            })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_category_without_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        models = self.generate_models(authenticate=True,
                                      profile_academy=True,
                                      capability='read_media',
                                      role='potato')
        url = reverse_lazy('media:category')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_category_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_category(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_media',
                                     role='potato',
                                     category=True)
        url = reverse_lazy('media:category')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'id': 1,
            'medias': 0,
            'name': model['category'].name,
            'slug': model['category'].slug,
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_category_dict(), [{
            **self.model_to_dict(model, 'category')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_category_with_media(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_media',
                                     role='potato',
                                     media=True,
                                     category=True)
        url = reverse_lazy('media:category')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'id': 1,
            'medias': 1,
            'name': model['category'].name,
            'slug': model['category'].slug,
        }])
        self.assertEqual(self.all_category_dict(), [{
            **self.model_to_dict(model, 'category')
        }])

    def test_category_pagination_with_105(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True,
                                    role=role,
                                    capability='read_media',
                                    profile_academy=True)

        models = [
            self.generate_models(category=True, models=base)
            for _ in range(0, 105)
        ]
        url = reverse_lazy('media:category')
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id': model['category'].id,
            'medias': 0,
            'name': model['category'].name,
            'slug': model['category'].slug,
        } for model in models if model['category'].id < 101]

        self.assertEqual(json, expected)
        self.assertEqual(self.all_category_dict(), [{
            **self.model_to_dict(model, 'category')
        } for model in models])

    def test_category_pagination_first_five(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True,
                                    role=role,
                                    capability='read_media',
                                    profile_academy=True)

        models = [
            self.generate_models(category=True, models=base)
            for _ in range(0, 10)
        ]
        url = reverse_lazy('media:category') + '?limit=5&offset=0'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count':
            10,
            'first':
            None,
            'last':
            'http://testserver/v1/media/category?limit=5&offset=5',
            'next':
            'http://testserver/v1/media/category?limit=5&offset=5',
            'previous':
            None,
            'results': [{
                'id': model['category'].id,
                'medias': 0,
                'name': model['category'].name,
                'slug': model['category'].slug,
            } for model in models if model['category'].id < 6]
        }

        self.assertEqual(json, expected)
        self.assertEqual(self.all_category_dict(), [{
            **self.model_to_dict(model, 'category')
        } for model in models])

    def test_category_pagination_last_five(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True,
                                    role=role,
                                    capability='read_media',
                                    profile_academy=True)

        models = [
            self.generate_models(category=True, models=base)
            for _ in range(0, 10)
        ]
        url = reverse_lazy('media:category') + '?limit=5&offset=5'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count':
            10,
            'first':
            'http://testserver/v1/media/category?limit=5',
            'last':
            None,
            'next':
            None,
            'previous':
            'http://testserver/v1/media/category?limit=5',
            'results': [{
                'id': model['category'].id,
                'medias': 0,
                'name': model['category'].name,
                'slug': model['category'].slug,
            } for model in models if model['category'].id > 5]
        }

        self.assertEqual(json, expected)
        self.assertEqual(self.all_category_dict(), [{
            **self.model_to_dict(model, 'category')
        } for model in models])

    def test_category_pagination_after_last_five(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True,
                                    role=role,
                                    capability='read_media',
                                    profile_academy=True)

        models = [
            self.generate_models(category=True, models=base)
            for _ in range(0, 10)
        ]
        url = reverse_lazy('media:category') + '?limit=5&offset=10'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': 'http://testserver/v1/media/category?limit=5',
            'last': None,
            'next': None,
            'previous': 'http://testserver/v1/media/category?limit=5&offset=5',
            'results': []
        }

        self.assertEqual(json, expected)
        self.assertEqual(self.all_category_dict(), [{
            **self.model_to_dict(model, 'category')
        } for model in models])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_category_post(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_media',
                                     role='potato')
        url = reverse_lazy('media:category')
        data = {
            'name': 'They killed kenny',
            'slug': 'they-killed-kenny',
        }
        response = self.client.post(url, data)
        json = response.json()
        expected = {
            'id': 1,
            **data,
        }

        self.assertDatetime(json['created_at'])
        self.assertDatetime(json['updated_at'])
        del json['created_at']
        del json['updated_at']

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(self.all_category_dict(), [expected])
Exemple #17
0
class CertificateTestSuite(CertificateTestCase):
    """Test /certificate"""
    """
    🔽🔽🔽 Auth
    """
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_cohort_user__without_auth(self):
        """Test /root without auth"""
        self.headers(academy=1)
        url = reverse_lazy('certificate:root')
        response = self.client.post(url, {})
        json = response.json()

        self.assertEqual(
            json, {
                'detail': 'Authentication credentials were not provided.',
                'status_code': status.HTTP_401_UNAUTHORIZED
            })
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    """
    🔽🔽🔽 Post method
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_re_attemps_without_capability(self):
        """Test /root with auth"""
        """ No capability for the request"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     user=True,
                                     profile_academy=True)

        url = reverse_lazy('certificate:root')
        data = [{
            'cohort_slug': model['cohort'].slug,
            'user_id': model['user'].id,
        }]
        response = self.client.post(url, data, format='json')
        json = response.json()
        expected = {
            'detail':
            "You (user: 1) don't have this capability: crud_certificate for academy 1",
            'status_code': 403
        }
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(self.all_user_specialty_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_re_attemps_without_cohort_user(self):
        """Test /root with auth"""
        """ No cohort_user for the request"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     user=True,
                                     profile_academy=True,
                                     role="STUDENT",
                                     capability='crud_certificate')

        url = reverse_lazy('certificate:root')
        data = [{
            'cohort_slug': model['cohort'].slug,
            'user_id': model['user'].id,
        }]
        response = self.client.post(url, data, format='json')
        json = response.json()
        expected = {
            'detail': 'student-not-found-in-cohort',
            'status_code': 404
        }
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 404)
        self.assertEqual(self.all_user_specialty_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_re_attemps_without_user_specialty(self):
        """Test /root with auth"""
        """ No user_specialty for the request"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     user=True,
                                     profile_academy=True,
                                     role="STUDENT",
                                     capability='crud_certificate',
                                     cohort_user=True)

        url = reverse_lazy('certificate:root')
        data = [{
            'cohort_slug': model['cohort'].slug,
            'user_id': model['user'].id,
        }]
        response = self.client.post(url, data, format='json')
        json = response.json()
        expected = {'detail': 'no-user-specialty', 'status_code': 404}
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 404)
        self.assertEqual(self.all_user_specialty_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_re_attemps(self):
        """Test /root with auth"""
        """ Good Request """
        self.headers(academy=1)

        model = self.generate_models(
            authenticate=True,
            cohort=True,
            user=True,
            profile_academy=True,
            capability='crud_certificate',
            role='STUDENT',
            cohort_user=True,
            syllabus=True,
            specialty=True,
            layout_design=True,
            cohort_stage="ENDED",
            cohort_user_finantial_status='UP_TO_DATE',
            cohort_user_educational_status='GRADUATED',
            user_specialty=True,
            cohort_finished=True)

        base = model.copy()
        del base['user']
        del base['cohort_user']

        teacher_model = self.generate_models(user=True,
                                             cohort_user=True,
                                             cohort_user_role='TEACHER',
                                             models=base)

        url = reverse_lazy('certificate:root')
        data = [{
            'cohort_slug': model['cohort'].slug,
            'user_id': model['user'].id,
        }]
        response = self.client.post(url, data, format='json')
        json = response.json()

        self.assertDatetime(json[0]['updated_at'])
        del json[0]['updated_at']
        del json[0]['signed_by']

        expected = [{
            'academy': {
                'id': 1,
                'logo_url': model['academy'].logo_url,
                'name': model['academy'].name,
                'slug': model['academy'].slug,
                'website_url': None
            },
            'cohort': {
                'id': 1,
                'name': model['cohort'].name,
                'slug': model['cohort'].slug,
                'syllabus': {
                    'certificate': {
                        'duration_in_hours':
                        model['certificate'].duration_in_hours
                    }
                }
            },
            'created_at':
            self.datetime_to_iso(model['user_specialty'].created_at),
            'expires_at':
            model['user_specialty'].expires_at,
            'id':
            1,
            'layout': {
                'name': model['layout_design'].name,
                'slug': model['layout_design'].slug
            },
            'preview_url':
            model['user_specialty'].preview_url,
            'signed_by_role':
            'Director',
            'specialty': {
                'created_at':
                self.datetime_to_iso(model['specialty'].created_at),
                'id': 1,
                'logo_url': None,
                'name': model['specialty'].name,
                'slug': model['specialty'].slug,
                'updated_at':
                self.datetime_to_iso(model['specialty'].updated_at),
            },
            'status':
            'PENDING',
            'status_text':
            None,
            'user': {
                'first_name': model['user'].first_name,
                'id': 1,
                'last_name': model['user'].last_name
            }
        }]
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_user_specialty_dict(), [{
            'academy_id':
            1,
            'cohort_id':
            1,
            'expires_at':
            None,
            'id':
            1,
            'layout_id':
            1,
            'preview_url':
            model['user_specialty'].preview_url,
            'signed_by':
            teacher_model['user'].first_name + " " +
            teacher_model['user'].last_name,
            'signed_by_role':
            'Director',
            'specialty_id':
            1,
            'status':
            'PERSISTED',
            'status_text':
            'Certificate successfully queued for PDF generation',
            'user_id':
            1,
            'token':
            "9e76a2ab3bd55454c384e0a5cdb5298d17285949"
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_re_attemps_two_certificates(self):
        """Test /root with auth"""
        """ Good Request """
        self.headers(academy=1)

        base = self.generate_models(authenticate=True,
                                    cohort=True,
                                    cohort_finished=True,
                                    capability='crud_certificate',
                                    role='STUDENT',
                                    profile_academy=True,
                                    syllabus=True,
                                    specialty=True,
                                    layout_design=True,
                                    cohort_stage="ENDED")

        del base['user']

        user_specialty_1_kwargs = {"token": "qwerrty"}
        user_specialty_2_kwargs = {"token": "huhuhuhuhu"}

        models = [
            self.generate_models(user=True,
                                 cohort_user=True,
                                 cohort_user_educational_status='GRADUATED',
                                 cohort_user_finantial_status='UP_TO_DATE',
                                 user_specialty=True,
                                 user_specialty_kwargs=user_specialty_2_kwargs,
                                 models=base),
            self.generate_models(user=True,
                                 cohort_user=True,
                                 cohort_user_educational_status='GRADUATED',
                                 cohort_user_finantial_status='UP_TO_DATE',
                                 user_specialty=True,
                                 user_specialty_kwargs=user_specialty_1_kwargs,
                                 models=base),
        ]

        teacher_model = self.generate_models(user=True,
                                             cohort_user=True,
                                             cohort_user_role='TEACHER',
                                             models=base)

        url = reverse_lazy('certificate:root')
        data = [
            {
                'cohort_slug': models[0].cohort.slug,
                'user_id': models[0].user.id,
            },
            {
                'cohort_slug': models[1].cohort.slug,
                'user_id': models[1].user.id,
            },
        ]
        response = self.client.post(url, data, format='json')
        json = response.json()

        self.assertDatetime(json[0]['updated_at'])
        del json[0]['updated_at']
        del json[0]['signed_by']

        self.assertDatetime(json[1]['updated_at'])
        del json[1]['updated_at']
        del json[1]['signed_by']

        expected = [{
            'academy': {
                'id': 1,
                'logo_url': models[0].academy.logo_url,
                'name': models[0].academy.name,
                'slug': models[0].academy.slug,
                'website_url': None
            },
            'cohort': {
                'id': 1,
                'name': models[0].cohort.name,
                'slug': models[0].cohort.slug,
                'syllabus': {
                    'certificate': {
                        'duration_in_hours':
                        models[0].certificate.duration_in_hours
                    }
                }
            },
            'created_at':
            self.datetime_to_iso(models[0].user_specialty.created_at),
            'expires_at':
            models[0].user_specialty.expires_at,
            'id':
            1,
            'layout': {
                'name': models[0].layout_design.name,
                'slug': models[0].layout_design.slug
            },
            'preview_url':
            models[0].user_specialty.preview_url,
            'signed_by_role':
            'Director',
            'specialty': {
                'created_at':
                self.datetime_to_iso(models[0].specialty.created_at),
                'id': 1,
                'logo_url': None,
                'name': models[0].specialty.name,
                'slug': models[0].specialty.slug,
                'updated_at':
                self.datetime_to_iso(models[0].specialty.updated_at),
            },
            'status':
            'PENDING',
            'status_text':
            None,
            'user': {
                'first_name': models[0].user.first_name,
                'id': 2,
                'last_name': models[0].user.last_name
            }
        }, {
            'academy': {
                'id': 1,
                'logo_url': models[1].academy.logo_url,
                'name': models[1].academy.name,
                'slug': models[1].academy.slug,
                'website_url': None
            },
            'cohort': {
                'id': 1,
                'name': models[1].cohort.name,
                'slug': models[1].cohort.slug,
                'syllabus': {
                    'certificate': {
                        'duration_in_hours':
                        models[1].certificate.duration_in_hours
                    }
                }
            },
            'created_at':
            self.datetime_to_iso(models[1].user_specialty.created_at),
            'expires_at':
            models[1].user_specialty.expires_at,
            'id':
            2,
            'layout': {
                'name': models[1].layout_design.name,
                'slug': models[1].layout_design.slug
            },
            'preview_url':
            models[1].user_specialty.preview_url,
            'signed_by_role':
            'Director',
            'specialty': {
                'created_at':
                self.datetime_to_iso(models[1].specialty.created_at),
                'id': 1,
                'logo_url': None,
                'name': models[1].specialty.name,
                'slug': models[1].specialty.slug,
                'updated_at':
                self.datetime_to_iso(models[1].specialty.updated_at),
            },
            'status':
            'PENDING',
            'status_text':
            None,
            'user': {
                'first_name': models[1].user.first_name,
                'id': 3,
                'last_name': models[1].user.last_name
            }
        }]
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_user_specialty_dict(), [
            {
                'academy_id':
                1,
                'cohort_id':
                1,
                'expires_at':
                None,
                'id':
                1,
                'layout_id':
                1,
                'preview_url':
                models[0].user_specialty.preview_url,
                'signed_by':
                teacher_model['user'].first_name + " " +
                teacher_model['user'].last_name,
                'signed_by_role':
                'Director',
                'specialty_id':
                1,
                'status':
                'PERSISTED',
                'status_text':
                'Certificate successfully queued for PDF generation',
                'user_id':
                2,
                'token':
                "huhuhuhuhu"
            },
            {
                'academy_id':
                1,
                'cohort_id':
                1,
                'expires_at':
                None,
                'id':
                2,
                'layout_id':
                1,
                'preview_url':
                models[1].user_specialty.preview_url,
                'signed_by':
                teacher_model['user'].first_name + " " +
                teacher_model['user'].last_name,
                'signed_by_role':
                'Director',
                'specialty_id':
                1,
                'status':
                'PERSISTED',
                'status_text':
                'Certificate successfully queued for PDF generation',
                'user_id':
                3,
                'token':
                "qwerrty"
            },
        ])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate__with_full_name_in_querystring(self):
        """Test /root """
        self.headers(academy=1)

        base = self.generate_models(authenticate=True,
                                    cohort=True,
                                    cohort_finished=True,
                                    capability='read_certificate',
                                    role='potato',
                                    academy=True,
                                    profile_academy=True,
                                    specialty=True)

        del base['user']

        user_kwargs = {
            'email': '*****@*****.**',
            'first_name': 'Rene',
            'last_name': 'Descartes',
        }
        user_kwargs_2 = {
            'email': '*****@*****.**',
            'first_name': 'Michael',
            'last_name': 'Jordan',
        }
        user_specialty_kwargs_1 = {"token": "123dfefef1123rerf346g"}
        user_specialty_kwargs_2 = {"token": "jojfsdknjbs1123rerf346g"}
        models = [
            self.generate_models(user=True,
                                 user_specialty=True,
                                 cohort_user=True,
                                 user_kwargs=user_kwargs,
                                 user_specialty_kwargs=user_specialty_kwargs_1,
                                 models=base),
            self.generate_models(user=True,
                                 user_specialty=True,
                                 cohort_user=True,
                                 user_kwargs=user_kwargs_2,
                                 user_specialty_kwargs=user_specialty_kwargs_2,
                                 models=base)
        ]

        base_url = reverse_lazy('certificate:root')
        url = f'{base_url}?like=Rene Descartes'

        response = self.client.get(url)
        json = response.json()

        expected = [{
            'academy': {
                'id': 1,
                'logo_url': models[0].academy.logo_url,
                'name': models[0].academy.name,
                'slug': models[0].academy.slug,
                'website_url': None
            },
            'cohort': {
                'id': 1,
                'name': models[0].cohort.name,
                'slug': models[0].cohort.slug,
                'syllabus': {}
            },
            'created_at':
            self.datetime_to_iso(models[0].user_specialty.created_at),
            'expires_at':
            models[0].user_specialty.expires_at,
            'id':
            1,
            'layout':
            None,
            'preview_url':
            models[0].user_specialty.preview_url,
            'signed_by':
            models[0].user_specialty.signed_by,
            'signed_by_role':
            'Director',
            'specialty': {
                'created_at':
                self.datetime_to_iso(models[0].specialty.created_at),
                'id': 1,
                'logo_url': None,
                'name': models[0].specialty.name,
                'slug': models[0].specialty.slug,
                'updated_at':
                self.datetime_to_iso(models[0].specialty.updated_at),
            },
            'status':
            'PENDING',
            'status_text':
            None,
            'updated_at':
            self.datetime_to_iso(models[0].user_specialty.updated_at),
            'user': {
                'first_name': models[0].user.first_name,
                'id': 2,
                'last_name': models[0].user.last_name
            }
        }]
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    """
    🔽🔽🔽 With full like querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate__with_first_name_in_querystring(self):
        """Test /root """
        self.headers(academy=1)
        base = self.generate_models(authenticate=True,
                                    cohort=True,
                                    cohort_finished=True,
                                    capability='read_certificate',
                                    role='potato',
                                    academy=True,
                                    profile_academy=True,
                                    specialty=True)

        del base['user']

        user_kwargs = {
            'email': '*****@*****.**',
            'first_name': 'Rene',
            'last_name': 'Descartes',
        }
        user_kwargs_2 = {
            'email': '*****@*****.**',
            'first_name': 'Michael',
            'last_name': 'Jordan',
        }
        user_specialty_kwargs_1 = {"token": "123dfefef1123rerf346g"}
        user_specialty_kwargs_2 = {"token": "jojfsdknjbs1123rerf346g"}
        models = [
            self.generate_models(user=True,
                                 user_specialty=True,
                                 cohort_user=True,
                                 user_kwargs=user_kwargs,
                                 user_specialty_kwargs=user_specialty_kwargs_1,
                                 models=base),
            self.generate_models(user=True,
                                 user_specialty=True,
                                 cohort_user=True,
                                 user_kwargs=user_kwargs_2,
                                 user_specialty_kwargs=user_specialty_kwargs_2,
                                 models=base)
        ]

        base_url = reverse_lazy('certificate:root')
        url = f'{base_url}?like=Rene'

        response = self.client.get(url)
        json = response.json()

        expected = [{
            'academy': {
                'id': 1,
                'logo_url': models[0].academy.logo_url,
                'name': models[0].academy.name,
                'slug': models[0].academy.slug,
                'website_url': None
            },
            'cohort': {
                'id': 1,
                'name': models[0].cohort.name,
                'slug': models[0].cohort.slug,
                'syllabus': {}
            },
            'created_at':
            self.datetime_to_iso(models[0].user_specialty.created_at),
            'expires_at':
            models[0].user_specialty.expires_at,
            'id':
            1,
            'layout':
            None,
            'preview_url':
            models[0].user_specialty.preview_url,
            'signed_by':
            models[0].user_specialty.signed_by,
            'signed_by_role':
            'Director',
            'specialty': {
                'created_at':
                self.datetime_to_iso(models[0].specialty.created_at),
                'id': 1,
                'logo_url': None,
                'name': models[0].specialty.name,
                'slug': models[0].specialty.slug,
                'updated_at':
                self.datetime_to_iso(models[0].specialty.updated_at),
            },
            'status':
            'PENDING',
            'status_text':
            None,
            'updated_at':
            self.datetime_to_iso(models[0].user_specialty.updated_at),
            'user': {
                'first_name': models[0].user.first_name,
                'id': 2,
                'last_name': models[0].user.last_name
            }
        }]
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate__with_last_name_in_querystring(self):
        """Test /root """
        self.headers(academy=1)
        base = self.generate_models(authenticate=True,
                                    cohort=True,
                                    cohort_finished=True,
                                    capability='read_certificate',
                                    role='potato',
                                    academy=True,
                                    profile_academy=True,
                                    specialty=True)

        del base['user']

        user_kwargs = {
            'email': '*****@*****.**',
            'first_name': 'Rene',
            'last_name': 'Descartes',
        }
        user_kwargs_2 = {
            'email': '*****@*****.**',
            'first_name': 'Michael',
            'last_name': 'Jordan',
        }
        user_specialty_kwargs_1 = {"token": "123dfefef1123rerf346g"}
        user_specialty_kwargs_2 = {"token": "jojfsdknjbs1123rerf346g"}
        models = [
            self.generate_models(user=True,
                                 user_specialty=True,
                                 cohort_user=True,
                                 user_kwargs=user_kwargs,
                                 user_specialty_kwargs=user_specialty_kwargs_1,
                                 models=base),
            self.generate_models(user=True,
                                 user_specialty=True,
                                 cohort_user=True,
                                 user_kwargs=user_kwargs_2,
                                 user_specialty_kwargs=user_specialty_kwargs_2,
                                 models=base)
        ]

        base_url = reverse_lazy('certificate:root')
        url = f'{base_url}?like=Descartes'

        response = self.client.get(url)
        json = response.json()

        expected = [{
            'academy': {
                'id': 1,
                'logo_url': models[0].academy.logo_url,
                'name': models[0].academy.name,
                'slug': models[0].academy.slug,
                'website_url': None
            },
            'cohort': {
                'id': 1,
                'name': models[0].cohort.name,
                'slug': models[0].cohort.slug,
                'syllabus': {}
            },
            'created_at':
            self.datetime_to_iso(models[0].user_specialty.created_at),
            'expires_at':
            models[0].user_specialty.expires_at,
            'id':
            1,
            'layout':
            None,
            'preview_url':
            models[0].user_specialty.preview_url,
            'signed_by':
            models[0].user_specialty.signed_by,
            'signed_by_role':
            'Director',
            'specialty': {
                'created_at':
                self.datetime_to_iso(models[0].specialty.created_at),
                'id': 1,
                'logo_url': None,
                'name': models[0].specialty.name,
                'slug': models[0].specialty.slug,
                'updated_at':
                self.datetime_to_iso(models[0].specialty.updated_at),
            },
            'status':
            'PENDING',
            'status_text':
            None,
            'updated_at':
            self.datetime_to_iso(models[0].user_specialty.updated_at),
            'user': {
                'first_name': models[0].user.first_name,
                'id': 2,
                'last_name': models[0].user.last_name
            }
        }]
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate__with_email_in_querystring(self):
        """Test /root """
        self.headers(academy=1)
        base = self.generate_models(authenticate=True,
                                    cohort=True,
                                    cohort_finished=True,
                                    capability='read_certificate',
                                    role='potato',
                                    academy=True,
                                    profile_academy=True,
                                    specialty=True)

        del base['user']

        user_kwargs = {
            'email': '*****@*****.**',
            'first_name': 'Rene',
            'last_name': 'Descartes',
        }
        user_kwargs_2 = {
            'email': '*****@*****.**',
            'first_name': 'Michael',
            'last_name': 'Jordan',
        }
        user_specialty_kwargs_1 = {"token": "123dfefef1123rerf346g"}
        user_specialty_kwargs_2 = {"token": "jojfsdknjbs1123rerf346g"}
        models = [
            self.generate_models(user=True,
                                 user_specialty=True,
                                 cohort_user=True,
                                 user_kwargs=user_kwargs,
                                 user_specialty_kwargs=user_specialty_kwargs_1,
                                 models=base),
            self.generate_models(user=True,
                                 user_specialty=True,
                                 cohort_user=True,
                                 user_kwargs=user_kwargs_2,
                                 user_specialty_kwargs=user_specialty_kwargs_2,
                                 models=base)
        ]

        base_url = reverse_lazy('certificate:root')
        url = f'{base_url}[email protected]'

        response = self.client.get(url)
        json = response.json()

        expected = [{
            'academy': {
                'id': 1,
                'logo_url': models[0].academy.logo_url,
                'name': models[0].academy.name,
                'slug': models[0].academy.slug,
                'website_url': None
            },
            'cohort': {
                'id': 1,
                'name': models[0].cohort.name,
                'slug': models[0].cohort.slug,
                'syllabus': {}
            },
            'created_at':
            self.datetime_to_iso(models[0].user_specialty.created_at),
            'expires_at':
            models[0].user_specialty.expires_at,
            'id':
            1,
            'layout':
            None,
            'preview_url':
            models[0].user_specialty.preview_url,
            'signed_by':
            models[0].user_specialty.signed_by,
            'signed_by_role':
            'Director',
            'specialty': {
                'created_at':
                self.datetime_to_iso(models[0].specialty.created_at),
                'id': 1,
                'logo_url': None,
                'name': models[0].specialty.name,
                'slug': models[0].specialty.slug,
                'updated_at':
                self.datetime_to_iso(models[0].specialty.updated_at),
            },
            'status':
            'PENDING',
            'status_text':
            None,
            'updated_at':
            self.datetime_to_iso(models[0].user_specialty.updated_at),
            'user': {
                'first_name': models[0].user.first_name,
                'id': 2,
                'last_name': models[0].user.last_name
            }
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Exemple #18
0
class EventbriteWebhookTestSuite(EventTestCase):
    """Test /eventbrite/webhook"""

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(EVENTBRITE_PATH['get'], apply_eventbrite_requests_post_mock())
    def test_eventbrite_webhook_without_data(self):
        """Test /eventbrite/webhook without auth"""
        # self.generate_models(authenticate=True)
        url = reverse_lazy('events:eventbrite_webhook_id', kwargs={'organization_id': 1})
        response = self.client.post(url, {}, headers=self.headers(), format='json')
        content = response.content

        self.assertEqual(content, b'ok')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_event_checkin_dict(), [])
        self.assertEqual(self.all_eventbrite_webhook_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(EVENTBRITE_PATH['get'], apply_eventbrite_requests_post_mock())
    def test_eventbrite_webhook_without_organization(self):
        """Test /eventbrite/webhook without auth"""
        # self.generate_models(authenticate=True)
        url = reverse_lazy('events:eventbrite_webhook_id', kwargs={'organization_id': 1})
        response = self.client.post(url, self.data('order.placed', EVENTBRITE_ORDER_URL),
            headers=self.headers('order.placed'), format='json')
        content = response.content

        self.assertEqual(content, b'ok')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_event_checkin_dict(), [])
        self.assertEqual(self.all_eventbrite_webhook_dict(), [{
            'action': 'order.placed',
            'api_url': 'https://www.eventbriteapi.com/v3/events/1/orders/1/',
            'endpoint_url': 'https://something.io/eventbrite/webhook',
            'id': 1,
            'organization_id': '1',
            'status': 'ERROR',
            'status_text': 'Organization 1 doesn\'t exist',
            'user_id': '123456789012',
            'webhook_id': '1234567'
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(EVENTBRITE_PATH['get'], apply_eventbrite_requests_post_mock())
    def test_eventbrite_webhook_without_event(self):
        """Test /eventbrite/webhook without auth"""
        # self.generate_models(authenticate=True)
        self.generate_models(organization=True)
        url = reverse_lazy('events:eventbrite_webhook_id', kwargs={'organization_id': 1})
        response = self.client.post(url, self.data('order.placed', EVENTBRITE_ORDER_URL),
            headers=self.headers('order.placed'), format='json')
        content = response.content

        self.assertEqual(content, b'ok')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_event_checkin_dict(), [])
        self.assertEqual(self.all_eventbrite_webhook_dict(), [{
            'action': 'order.placed',
            'api_url': 'https://www.eventbriteapi.com/v3/events/1/orders/1/',
            'endpoint_url': 'https://something.io/eventbrite/webhook',
            'id': 1,
            'organization_id': '1',
            'status': 'ERROR',
            'status_text': 'event doesn\'t exist',
            'user_id': '123456789012',
            'webhook_id': '1234567'
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(EVENTBRITE_PATH['get'], apply_eventbrite_requests_post_mock())
    def test_eventbrite_webhook_without_active_campaign_academy(self):
        """Test /eventbrite/webhook without auth"""
        self.generate_models(organization=True, event=True, eventbrite_event_id=1, attendee=True)
        url = reverse_lazy('events:eventbrite_webhook_id', kwargs={'organization_id': 1})
        response = self.client.post(url, self.data('order.placed', EVENTBRITE_ORDER_URL),
            headers=self.headers('order.placed'), format='json')
        content = response.content

        self.assertEqual(content, b'ok')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(self.all_eventbrite_webhook_dict(), [{
            'action': 'order.placed',
            'api_url': 'https://www.eventbriteapi.com/v3/events/1/orders/1/',
            'endpoint_url': 'https://something.io/eventbrite/webhook',
            'id': 1,
            'organization_id': '1',
            'status': 'ERROR',
            'status_text': 'ActiveCampaignAcademy doesn\'t exist',
            'user_id': '123456789012',
            'webhook_id': '1234567'
        }])

        self.assertEqual(self.all_event_checkin_dict(), [{
            'attendee_id': 1,
            'email': '*****@*****.**',
            'event_id': 1,
            'id': 1,
            'status': 'PENDING'
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(EVENTBRITE_PATH['get'], apply_eventbrite_requests_post_mock())
    @patch(OLD_BREATHECODE_PATH['request'], apply_old_breathecode_requests_request_mock())
    def test_eventbrite_webhook_without_automation(self):
        """Test /eventbrite/webhook without auth"""
        self.generate_models(organization=True, event=True, eventbrite_event_id=1, attendee=True,
            active_campaign_academy=True, in_miami=True)
        url = reverse_lazy('events:eventbrite_webhook_id', kwargs={'organization_id': 1})
        response = self.client.post(url, self.data('order.placed', EVENTBRITE_ORDER_URL),
            headers=self.headers('order.placed'), format='json')
        content = response.content

        self.assertEqual(content, b'ok')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_eventbrite_webhook_dict(), [{
            'action': 'order.placed',
            'api_url': 'https://www.eventbriteapi.com/v3/events/1/orders/1/',
            'endpoint_url': 'https://something.io/eventbrite/webhook',
            'id': 1,
            'organization_id': '1',
            'status': 'ERROR',
            'status_text': 'Automation for order_placed doesn\'t exist',
            'user_id': '123456789012',
            'webhook_id': '1234567'
        }])

        self.assertEqual(self.all_event_checkin_dict(), [{
            'attendee_id': 1,
            'email': '*****@*****.**',
            'event_id': 1,
            'id': 1,
            'status': 'PENDING'
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(EVENTBRITE_PATH['get'], apply_eventbrite_requests_post_mock())
    @patch(OLD_BREATHECODE_PATH['request'], apply_old_breathecode_requests_request_mock())
    def test_eventbrite_webhook(self):
        """Test /eventbrite/webhook without auth"""
        self.generate_models(organization=True, event=True, eventbrite_event_id=1, attendee=True,
            active_campaign_academy=True, in_miami=True, automation=True, with_event_attendancy_automation=True)
        url = reverse_lazy('events:eventbrite_webhook_id', kwargs={'organization_id': 1})
        response = self.client.post(url, self.data('order.placed', EVENTBRITE_ORDER_URL),
            headers=self.headers('order.placed'), format='json')
        content = response.content

        self.assertEqual(content, b'ok')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(self.all_eventbrite_webhook_dict(), [{
            'action': 'order.placed',
            'api_url': 'https://www.eventbriteapi.com/v3/events/1/orders/1/',
            'endpoint_url': 'https://something.io/eventbrite/webhook',
            'id': 1,
            'organization_id': '1',
            'status': 'DONE',
            'status_text': None,
            'user_id': '123456789012',
            'webhook_id': '1234567'
        }])

        self.assertEqual(self.all_event_checkin_dict(), [{
            'attendee_id': 1,
            'email': '*****@*****.**',
            'event_id': 1,
            'id': 1,
            'status': 'PENDING'
        }])
class MediaTestSuite(MediaTestCase):
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_resolution_without_auth(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:info_id_resolution', kwargs={'media_id': 1})
        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_resolution_wrong_academy(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:info_id_resolution', kwargs={'media_id': 1})
        response = self.client.get(url, **{'HTTP_Academy': 1 })

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_resolution_without_capability(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('media:info_id_resolution', kwargs={'media_id': 1})
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': "You (user: 1) don't have this capability: read_media_resolution for academy 1",
            'status_code': 403
        })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_without_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media_resolution', role='potato')
        url = reverse_lazy('media:info_id_resolution', kwargs={'media_id': 1})
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': 'media-not-found',
            'status_code': 404
        })
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_media_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_resolution_get_with_id(self):
        """Test /info/media:id/resolution"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, media_resolution=True, media=True,
            capability='read_media_resolution', role='potato', profile_academy=True, 
            media_kwargs={'hash': 'abc'}, media_resolution_kwargs={'hash' : 'abc'})
        model_dict = self.remove_dinamics_fields(model['media_resolution'].__dict__)
        url = reverse_lazy('media:info_id_resolution', kwargs={'media_id': model['media'].id})
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id': model['media_resolution'].id,
            'hash': model['media'].hash,
            'width': model['media_resolution'].width,
            'height': model['media_resolution'].height,
            'hits': model['media_resolution'].hits,
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_media_resolution(), 1)
        self.assertEqual(self.get_media_resolution_dict(1), model_dict)
Exemple #20
0
class CohortAllTestSuite(AdmissionsTestCase):
    """Test /cohort/all"""

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_without_auth(self):
        """Test /cohort/all without auth"""
        url = reverse_lazy('admissions:cohort_all')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_without_data(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True)
        url = reverse_lazy('admissions:cohort_all')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_cohort_but_without_profile_academy(self):
        """Test /cohort/all without auth"""
        url = reverse_lazy('admissions:cohort_all')
        self.generate_models(authenticate=True, cohort=True)
        model_dict = self.remove_dinamics_fields(self.cohort.__dict__)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_bad_get_academy(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True, cohort=True, profile_academy=True)
        model_dict = self.remove_dinamics_fields(self.cohort.__dict__)
        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?academy=they-killed-kenny'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_academy(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True, cohort=True, profile_academy=True)
        model_dict = self.remove_dinamics_fields(self.cohort.__dict__)
        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?academy={self.academy.slug}'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id': self.cohort.id,
            'slug': self.cohort.slug,
            'name': self.cohort.name,
            'kickoff_date': re.sub(r'\+00:00$', 'Z', self.cohort.kickoff_date.isoformat()),
            'ending_date': self.cohort.ending_date,
            'stage': self.cohort.stage,
            'language': self.cohort.language,
            'certificate': {
                'id': self.cohort.certificate.id,
                'slug': self.cohort.certificate.slug,
                'name': self.cohort.certificate.name,
                'description': self.cohort.certificate.description,
                'logo': self.cohort.certificate.logo,
            },
            'academy': {
                'id': self.cohort.academy.id,
                'slug': self.cohort.academy.slug,
                'name': self.cohort.academy.name,
                'country': {
                    'code': self.cohort.academy.country.code,
                    'name': self.cohort.academy.country.name,
                },
                'city': {
                    'name': self.cohort.academy.city.name,
                },
                'logo_url': self.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_bad_get_location(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True, cohort=True, profile_academy=True)
        model_dict = self.remove_dinamics_fields(self.cohort.__dict__)
        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?location=they-killed-kenny'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_location(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True, cohort=True, profile_academy=True)
        model_dict = self.remove_dinamics_fields(self.cohort.__dict__)
        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?location={self.academy.slug}'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id': self.cohort.id,
            'slug': self.cohort.slug,
            'name': self.cohort.name,
            'kickoff_date': re.sub(r'\+00:00$', 'Z', self.cohort.kickoff_date.isoformat()),
            'ending_date': self.cohort.ending_date,
            'stage': self.cohort.stage,
            'language': self.cohort.language,
            'certificate': {
                'id': self.cohort.certificate.id,
                'slug': self.cohort.certificate.slug,
                'name': self.cohort.certificate.name,
                'description': self.cohort.certificate.description,
                'logo': self.cohort.certificate.logo,
            },
            'academy': {
                'id': self.cohort.academy.id,
                'slug': self.cohort.academy.slug,
                'name': self.cohort.academy.name,
                'country': {
                    'code': self.cohort.academy.country.code,
                    'name': self.cohort.academy.country.name,
                },
                'city': {
                    'name': self.cohort.academy.city.name,
                },
                'logo_url': self.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_location_with_comma(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True, cohort=True, profile_academy=True)
        model_dict = self.remove_dinamics_fields(self.cohort.__dict__)
        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?location={self.academy.slug},they-killed-kenny'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id': self.cohort.id,
            'slug': self.cohort.slug,
            'name': self.cohort.name,
            'kickoff_date': re.sub(r'\+00:00$', 'Z', self.cohort.kickoff_date.isoformat()),
            'ending_date': self.cohort.ending_date,
            'stage': self.cohort.stage,
            'language': self.cohort.language,
            'certificate': {
                'id': self.cohort.certificate.id,
                'slug': self.cohort.certificate.slug,
                'name': self.cohort.certificate.name,
                'description': self.cohort.certificate.description,
                'logo': self.cohort.certificate.logo,
            },
            'academy': {
                'id': self.cohort.academy.id,
                'slug': self.cohort.academy.slug,
                'name': self.cohort.academy.name,
                'country': {
                    'code': self.cohort.academy.country.code,
                    'name': self.cohort.academy.country.name,
                },
                'city': {
                    'name': self.cohort.academy.city.name,
                },
                'logo_url': self.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_upcoming_false(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True, cohort=True, profile_academy=True)
        model_dict = self.remove_dinamics_fields(self.cohort.__dict__)
        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?upcoming=false'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id': self.cohort.id,
            'slug': self.cohort.slug,
            'name': self.cohort.name,
            'kickoff_date': re.sub(r'\+00:00$', 'Z', self.cohort.kickoff_date.isoformat()),
            'ending_date': self.cohort.ending_date,
            'stage': self.cohort.stage,
            'language': self.cohort.language,
            'certificate': {
                'id': self.cohort.certificate.id,
                'slug': self.cohort.certificate.slug,
                'name': self.cohort.certificate.name,
                'description': self.cohort.certificate.description,
                'logo': self.cohort.certificate.logo,
            },
            'academy': {
                'id': self.cohort.academy.id,
                'slug': self.cohort.academy.slug,
                'name': self.cohort.academy.name,
                'country': {
                    'code': self.cohort.academy.country.code,
                    'name': self.cohort.academy.country.name,
                },
                'city': {
                    'name': self.cohort.academy.city.name,
                },
                'logo_url': self.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_upcoming_true_without_current_data(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True, cohort=True, profile_academy=True)
        model_dict = self.remove_dinamics_fields(self.cohort.__dict__)
        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?upcoming=true'
        response = self.client.get(url)
        json = response.json()
        expected = []

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data_with_get_upcoming_true_with_current_data(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True, cohort=True, profile_academy=True,
            impossible_kickoff_date=True)
        model_dict = self.get_cohort_dict(1)
        base_url = reverse_lazy('admissions:cohort_all')
        url = f'{base_url}?upcoming=true'
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id': self.cohort.id,
            'slug': self.cohort.slug,
            'name': self.cohort.name,
            'kickoff_date': f'{self.cohort.kickoff_date.isoformat()}Z',
            'ending_date': self.cohort.ending_date,
            'stage': self.cohort.stage,
            'language': self.cohort.language,
            'certificate': {
                'id': self.cohort.certificate.id,
                'slug': self.cohort.certificate.slug,
                'name': self.cohort.certificate.name,
                'description': self.cohort.certificate.description,
                'logo': self.cohort.certificate.logo,
            },
            'academy': {
                'id': self.cohort.academy.id,
                'slug': self.cohort.academy.slug,
                'name': self.cohort.academy.name,
                'country': {
                    'code': self.cohort.academy.country.code,
                    'name': self.cohort.academy.country.name,
                },
                'city': {
                    'name': self.cohort.academy.city.name,
                },
                'logo_url': self.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_all_with_data(self):
        """Test /cohort/all without auth"""
        self.generate_models(authenticate=True, cohort=True, profile_academy=True)
        model_dict = self.remove_dinamics_fields(self.cohort.__dict__)
        url = reverse_lazy('admissions:cohort_all')
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'id': self.cohort.id,
            'slug': self.cohort.slug,
            'name': self.cohort.name,
            'kickoff_date': re.sub(r'\+00:00$', 'Z', self.cohort.kickoff_date.isoformat()),
            'ending_date': self.cohort.ending_date,
            'stage': self.cohort.stage,
            'language': self.cohort.language,
            'certificate': {
                'id': self.cohort.certificate.id,
                'slug': self.cohort.certificate.slug,
                'name': self.cohort.certificate.name,
                'description': self.cohort.certificate.description,
                'logo': self.cohort.certificate.logo,
            },
            'academy': {
                'id': self.cohort.academy.id,
                'slug': self.cohort.academy.slug,
                'name': self.cohort.academy.name,
                'country': {
                    'code': self.cohort.academy.country.code,
                    'name': self.cohort.academy.country.name,
                },
                'city': {
                    'name': self.cohort.academy.city.name,
                },
                'logo_url': self.cohort.academy.logo_url,
            },
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)
class SendSurveyTestSuite(FeedbackTestCase):
    """Test /answer"""
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(DJANGO_CONTRIB_PATH['messages'],
           apply_django_contrib_messages_mock())
    def test_send_bulk_cohort_user_survey__without_cohort(self):
        """Test /answer without auth"""
        request = HttpRequest()
        mock = DJANGO_CONTRIB_INSTANCES['messages']
        mock.success.call_args_list = []
        mock.error.call_args_list = []

        self.assertEqual(
            send_bulk_cohort_user_survey(None, request,
                                         CohortUser.objects.all()), None)
        self.assertEqual(
            mock.success.call_args_list,
            [call(request, message='Survey was '
                  'successfully sent')])
        self.assertEqual(mock.error.call_args_list, [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    @patch(DJANGO_CONTRIB_PATH['messages'],
           apply_django_contrib_messages_mock())
    def test_send_bulk_cohort_user_survey_with_success_models(self):
        """Test /answer without auth"""
        request = HttpRequest()
        mock = DJANGO_CONTRIB_INSTANCES['messages']
        mock.success.call_args_list = []
        mock.error.call_args_list = []

        models = [
            self.generate_models(user=True, cohort_user=True, lang='en')
            for _ in range(0, 3)
        ]
        academies = [(models[key]['cohort'].academy.name, key + 1)
                     for key in range(0, 3)]
        _cohorts = [(models[key]['cohort'].certificate.name, key + 1)
                    for key in range(0, 3)]
        self.assertEqual(
            send_bulk_cohort_user_survey(None, request,
                                         CohortUser.objects.all()), None)
        self.assertEqual(
            mock.success.call_args_list,
            [call(request, message='Survey was '
                  'successfully sent')])
        self.assertEqual(mock.error.call_args_list, [])
        expected = [{
            'academy_id': None,
            'cohort_id': key,
            'comment': None,
            'event_id': None,
            'highest': 'very good',
            'id': key,
            'lang': 'en',
            'lowest': 'not good',
            'mentor_id': None,
            'opened_at': None,
            'score': None,
            'status': 'SENT',
            'survey_id': None,
            'title': f'How has been your experience studying {c} so far?',
            'token_id': key,
            'user_id': key,
        } for c, key in _cohorts]

        dicts = [
            answer for answer in self.all_answer_dict()
            if isinstance(answer['created_at'], datetime)
            and answer.pop('created_at')
        ]
        self.assertEqual(dicts, expected)
class AuthenticateTestSuite(AuthTestCase):
    """Authentication test suite"""
    def test_resend_invite_no_auth(self):
        """Test """
        self.headers(academy=1)
        url = reverse_lazy('authenticate:academy_resent_invite',
                           kwargs={"pa_id": 1})

        response = self.client.put(url)
        json = response.json()
        expected = {
            'detail': 'Authentication credentials were not provided.',
            'status_code': 401
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 401)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_resend_invite_no_capability(self):
        """Test """
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_cohort',
                                     role='potato',
                                     syllabus=True)
        url = reverse_lazy('authenticate:academy_resent_invite',
                           kwargs={"pa_id": 1})

        response = self.client.put(url)
        json = response.json()
        expected = {
            'detail':
            "You (user: 1) don't have this capability: crud_member for "
            'academy 1',
            'status_code': 403
        }
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 403)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_resend_invite_with_capability(self):
        """Test """
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_member',
                                     role='potato',
                                     syllabus=True)

        url = reverse_lazy('authenticate:academy_resent_invite',
                           kwargs={"pa_id": 1359})

        response = self.client.put(url)
        json = response.json()
        expected = {'detail': 'Member not found', 'status_code': 400}
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 400)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_resend_invite_no_invitation(self):
        """Test """
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_member',
                                     role='potato',
                                     syllabus=True)
        url = reverse_lazy('authenticate:academy_resent_invite',
                           kwargs={"pa_id": 1})

        response = self.client.put(url)
        json = response.json()
        expected = {'detail': 'Invite not found', 'status_code': 400}
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 400)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_resend_invite_with_invitation(self):
        """Test """
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_member',
                                     role='potato',
                                     syllabus=True,
                                     user_invite=True)
        url = reverse_lazy('authenticate:academy_resent_invite',
                           kwargs={"pa_id": 1})
        response = self.client.put(url)
        json = response.json()
        token = json['token']
        created = json['created_at']
        sent = json['sent_at']
        del json['sent_at']
        del json['created_at']
        self.assertToken(json['token'])
        del json['token']
        expected = {
            'status': 'PENDING',
            'email': None,
            'first_name': None,
            'last_name': None
        }
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 200)
        all_user_invite = [
            x for x in self.all_user_invite_dict() if x.pop('sent_at')
        ]
        self.assertEqual(all_user_invite, [{
            'id': model['user_invite'].id,
            'email': model['user_invite'].email,
            'academy_id': model['user_invite'].academy_id,
            'cohort_id': model['user_invite'].cohort_id,
            'role_id': model['user_invite'].role_id,
            'first_name': model['user_invite'].first_name,
            'last_name': model['user_invite'].last_name,
            'token': token,
            'author_id': model['user_invite'].author_id,
            'status': model['user_invite'].status,
            'phone': model['user_invite'].phone,
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_resend_invite_recently(self):
        """Test """
        self.headers(academy=1)
        past_time = timezone.now() - timedelta(seconds=100)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_member',
                                     role='potato',
                                     syllabus=True,
                                     user_invite=True,
                                     token=True,
                                     user_invite_kwargs={'sent_at': past_time})
        url = reverse_lazy('authenticate:academy_resent_invite',
                           kwargs={"pa_id": 1})
        response = self.client.put(url)
        json = response.json()
        expected = {
            'detail': 'Imposible to resend invitation',
            'status_code': 400
        }
        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, 400)

        self.assertEqual(
            self.all_user_invite_dict(),
            [{
                **self.model_to_dict(model, 'user_invite'),
                'sent_at': past_time,
            }])
class CohortUserTestSuite(AdmissionsTestCase):
    """Test /cohort/user"""
    """
    🔽🔽🔽 Auth
    """
    def test_certificate_time_slot__without_auth(self):
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(
            json, {
                'detail': 'Authentication credentials were not provided.',
                'status_code': status.HTTP_401_UNAUTHORIZED
            })
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_certificate_time_slot__without_academy_header(self):
        model = self.generate_models(authenticate=True)
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(
            json, {
                'detail':
                "Missing academy_id parameter expected for the endpoint url or 'Academy' header",
                'status_code': 403,
            })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(self.all_certificate_time_slot_dict(), [])

    def test_certificate_time_slot__without_capabilities(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True)
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(
            json, {
                'detail':
                "You (user: 1) don't have this capability: read_certificate for academy 1",
                'status_code': 403,
            })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(self.all_certificate_time_slot_dict(), [])

    """
    🔽🔽🔽 Without data
    """

    def test_certificate_time_slot__without_data(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_certificate',
                                     role='potato')
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        response = self.client.get(url)
        json = response.json()
        expected = {
            'detail': 'time-slot-not-found',
            'status_code': 404,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_certificate_time_slot_dict(), [])

    """
    🔽🔽🔽 With data
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_time_slot__with_data(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_certificate',
                                     role='potato',
                                     certificate_time_slot=True)
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        response = self.client.get(url)
        json = response.json()
        expected = {
            'id':
            model.certificate_time_slot.id,
            'academy':
            model.certificate_time_slot.academy.id,
            'certificate':
            model.certificate_time_slot.certificate.id,
            'starting_at':
            self.datetime_to_iso(model.certificate_time_slot.starting_at),
            'ending_at':
            self.datetime_to_iso(model.certificate_time_slot.ending_at),
            'recurrent':
            model.certificate_time_slot.recurrent,
            'recurrency_type':
            model.certificate_time_slot.recurrency_type,
            'created_at':
            self.datetime_to_iso(model.certificate_time_slot.created_at),
            'updated_at':
            self.datetime_to_iso(model.certificate_time_slot.updated_at),
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_certificate_time_slot_dict(), [{
            **self.model_to_dict(model, 'certificate_time_slot'),
        }])

    """
    🔽🔽🔽 Put
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_time_slot__put__without_academy_certificate(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_certificate',
                                     role='potato')
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        data = {}
        response = self.client.put(url, data, format='json')
        json = response.json()
        expected = {
            'detail': 'certificate-not-found',
            'status_code': 404,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_certificate_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_time_slot__put__without_time_slot(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_certificate',
                                     role='potato',
                                     academy_certificate=True)
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        data = {}
        response = self.client.put(url, data, format='json')
        json = response.json()
        expected = {
            'detail': 'time-slot-not-found',
            'status_code': 404,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_certificate_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_time_slot__put__without_ending_at_and_starting_at(
            self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_certificate',
                                     role='potato',
                                     certificate_time_slot=True,
                                     academy_certificate=True)
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        data = {}
        response = self.client.put(url, data, format='json')
        json = response.json()
        expected = {
            'ending_at': ['This field is required.'],
            'starting_at': ['This field is required.'],
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(self.all_certificate_time_slot_dict(), [{
            **self.model_to_dict(model, 'certificate_time_slot'),
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_time_slot__put(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_certificate',
                                     role='potato',
                                     certificate_time_slot=True,
                                     academy_certificate=True)
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })

        starting_at = self.datetime_now()
        ending_at = self.datetime_now()
        data = {
            'ending_at': self.datetime_to_iso(ending_at),
            'starting_at': self.datetime_to_iso(starting_at),
        }
        response = self.client.put(url, data, format='json')
        json = response.json()
        expected = {
            'academy': 1,
            'certificate': 1,
            'id': 1,
            'recurrency_type': 'WEEKLY',
            'recurrent': True,
            **data,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_certificate_time_slot_dict(), [{
            **self.model_to_dict(model, 'certificate_time_slot'),
            'ending_at':
            ending_at,
            'starting_at':
            starting_at,
        }])

    """
    🔽🔽🔽 Delete
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_time_slot__delete__without_time_slot(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_certificate',
                                     role='potato')
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        response = self.client.delete(url)
        json = response.json()
        expected = {
            'detail': 'time-slot-not-found',
            'status_code': 404,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_certificate_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_time_slot__delete(self):
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_certificate',
                                     role='potato',
                                     certificate_time_slot=True)
        url = reverse_lazy('admissions:academy_certificate_id_timeslot_id',
                           kwargs={
                               'certificate_id': 1,
                               'timeslot_id': 1
                           })
        response = self.client.delete(url)

        if response.status_code != 204:
            print(response.json())

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(self.all_certificate_time_slot_dict(), [])
Exemple #24
0
class MediaTestSuite(MediaTestCase):
    """Test /answer"""

    """
    🔽🔽🔽 Auth
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__without_auth(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__wrong_academy(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:root')
        response = self.client.get(url, **{'HTTP_Academy': 1 })
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__without_capability(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('media:root')
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': "You (user: 1) don't have this capability: read_media for academy 1",
            'status_code': 403
        })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    """
    🔽🔽🔽 Without data
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__without_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        models = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [])

    """
    🔽🔽🔽 With data
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True)
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    """
    🔽🔽🔽 Academy in querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_bad_academy_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?academy=0'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_academy_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?academy=1'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_two_academy_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)

        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')

        del base['academy']

        models = [self.generate_models(academy=True, media=True, category=True, models=base)
            for _ in range(0, 2)]

        url = (reverse_lazy('media:root') + '?academy=' +
            str(models[0]['media'].academy.id) + ',' + str(models[1]['media'].academy.id))
        response = self.client.get(url)
        json = response.json()
        self.assertEqual(json, [{
            'categories': [{
                'id': model['category'].id,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        } for model in models])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    """
    🔽🔽🔽 Mime in querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_bad_mime_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?mime=application/hitman'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_mime_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?mime=' + model['media'].mime
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_two_mime_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)

        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')

        models = [self.generate_models(media=True, category=True, models=base)
            for _ in range(0, 2)]

        url = reverse_lazy('media:root') + '?mime=' + models[0]['media'].mime + ',' + models[1]['media'].mime
        response = self.client.get(url)
        json = response.json()
        self.assertEqual(json, [{
            'categories': [{
                'id': model['category'].id,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        } for model in models])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    """
    🔽🔽🔽 Name in querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_bad_name_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?name=hitman'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_name_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?name=' + model['media'].name
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_two_name_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)

        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')

        models = [self.generate_models(media=True, category=True, models=base)
            for _ in range(0, 2)]

        url = (reverse_lazy('media:root') + '?name=' + models[0]['media'].name +
            ',' + models[1]['media'].name)
        response = self.client.get(url)
        json = response.json()
        self.assertEqual(json, [{
            'categories': [{
                'id': model['category'].id,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        } for model in models])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    """
    🔽🔽🔽 Slug in querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_bad_slug_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?slug=hitman'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_slug_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?slug=' + model['media'].slug
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_two_slug_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)

        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')

        models = [self.generate_models(media=True, category=True, models=base)
            for _ in range(0, 2)]

        url = (reverse_lazy('media:root') + '?slug=' + models[0]['media'].slug +
            ',' + models[1]['media'].slug)
        response = self.client.get(url)
        json = response.json()
        self.assertEqual(json, [{
            'categories': [{
                'id': model['category'].id,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        } for model in models])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    """
    🔽🔽🔽 Id in querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_bad_id_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?id=0'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_id_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?id=' + str(model['media'].id)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_two_id_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)

        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')

        models = [self.generate_models(media=True, category=True, models=base)
            for _ in range(0, 2)]

        url = (reverse_lazy('media:root') + '?id=' + str(models[0]['media'].id) +
            ',' + str(models[1]['media'].id))
        response = self.client.get(url)
        json = response.json()
        self.assertEqual(json, [{
            'categories': [{
                'id': model['category'].id,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        } for model in models])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    """
    🔽🔽🔽 Categories in querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_bad_categories_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?categories=0'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_categories_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?categories=1'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_two_categories_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)

        base = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')

        models = [self.generate_models(media=True, category=True, models=base)
            for _ in range(0, 2)]

        url = (reverse_lazy('media:root') + '?categories=1,2')
        response = self.client.get(url)
        json = response.json()
        self.assertEqual(json, [{
            'categories': [{
                'id': model['category'].id,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        } for model in models])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    """
    🔽🔽🔽 Type in querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_bad_type_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?type=freyja'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_type_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        media_kwargs = {'mime': 'application/pdf'}
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True,
            media_kwargs=media_kwargs)
        url = reverse_lazy('media:root') + '?type=pdf'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    """
    🔽🔽🔽 Like in querystring
    """

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_bad_like_in_querystring(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:root') + '?like=freyja'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_like_in_querystring__like_match_name(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        media_kwargs = {'name': 'Freyja'}
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True,
            media_kwargs=media_kwargs)
        url = reverse_lazy('media:root') + '?like=fre'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root__with_category__with_like_in_querystring__like_match_slug(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        media_kwargs = {'slug': 'freyja'}
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True,
            media_kwargs=media_kwargs)
        url = reverse_lazy('media:root') + '?like=Fre'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    """
    🔽🔽🔽 Pagination tests
    """

    def test_root__pagination__with_105(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True, role=role,
            capability='read_media', profile_academy=True)

        models = [self.generate_models(media=True, models=base)
            for _ in range(0, 105)]
        url = reverse_lazy('media:root')
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'categories': [],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        } for model in models if model['media'].id < 101]

        self.assertEqual(json, expected)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    def test_root__pagination__first_five(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True, role=role,
            capability='read_media', profile_academy=True)

        models = [self.generate_models(media=True, models=base)
            for _ in range(0, 10)]
        url = reverse_lazy('media:root') + '?limit=5&offset=0'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': None,
            'last': 'http://testserver/v1/media/?limit=5&offset=5',
            'next': 'http://testserver/v1/media/?limit=5&offset=5',
            'previous': None,
            'results': [{
                'categories': [],
                'hash': model['media'].hash,
                'hits': model['media'].hits,
                'id': model['media'].id,
                'mime': model['media'].mime,
                'name': model['media'].name,
                'slug': model['media'].slug,
                'url': model['media'].url
            } for model in models if model['media'].id < 6]
        }

        self.assertEqual(json, expected)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    def test_root__pagination__last_five(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True, role=role,
            capability='read_media', profile_academy=True)

        models = [self.generate_models(media=True, models=base)
            for _ in range(0, 10)]
        url = reverse_lazy('media:root') + '?limit=5&offset=5'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': 'http://testserver/v1/media/?limit=5',
            'last': None,
            'next': None,
            'previous': 'http://testserver/v1/media/?limit=5',
            'results': [{
                'categories': [],
                'hash': model['media'].hash,
                'hits': model['media'].hits,
                'id': model['media'].id,
                'mime': model['media'].mime,
                'name': model['media'].name,
                'slug': model['media'].slug,
                'url': model['media'].url
            } for model in models if model['media'].id > 5]
        }

        self.assertEqual(json, expected)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])

    def test_root__pagination__after_last_five(self):
        """Test /academy/student"""
        self.headers(academy=1)
        role = 'student'
        base = self.generate_models(authenticate=True, role=role,
            capability='read_media', profile_academy=True)

        models = [self.generate_models(media=True, models=base)
            for _ in range(0, 10)]
        url = reverse_lazy('media:root') + '?limit=5&offset=10'
        response = self.client.get(url)
        json = response.json()
        expected = {
            'count': 10,
            'first': 'http://testserver/v1/media/?limit=5',
            'last': None,
            'next': None,
            'previous': 'http://testserver/v1/media/?limit=5&offset=5',
            'results': []
        }

        self.assertEqual(json, expected)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        } for model in models])
Exemple #25
0
class MediaTestSuite(MediaTestCase):
    """Test /answer"""

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_without_auth(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:info_name', kwargs={'media_name': 'they-killed-kenny.exe'})
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_wrong_academy(self):
        """Test /answer without auth"""
        url = reverse_lazy('media:info_name', kwargs={'media_name': 'they-killed-kenny.exe'})
        response = self.client.get(url, **{'HTTP_Academy': 1 })
        json = response.json()

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_without_capability(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('media:info_name', kwargs={'media_name': 'they-killed-kenny.exe'})
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': "You (user: 1) don't have this capability: read_media for academy 1",
            'status_code': 403
        })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_without_data(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        models = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato')
        url = reverse_lazy('media:info_name', kwargs={'media_name': 'they-killed-kenny.exe'})
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': 'Media not found',
            'status_code': 404
        })
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_media_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_root(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True)
        url = reverse_lazy('media:info_name', kwargs={'media_name': model['media'].name})
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'categories': [],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        })
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_info_id_with_category(self):
        """Test /answer without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_media', role='potato', media=True, category=True)
        url = reverse_lazy('media:info_name', kwargs={'media_name': model['media'].name})
        response = self.client.get(url)
        json = response.json()
        self.print_model(model, 'media')
        self.print_model(model, 'category')

        self.assertEqual(json, {
            'categories': [{
                'id': 1,
                'medias': 1,
                'name': model['category'].name,
                'slug': model['category'].slug,
            }],
            'hash': model['media'].hash,
            'hits': model['media'].hits,
            'id': model['media'].id,
            'mime': model['media'].mime,
            'name': model['media'].name,
            'slug': model['media'].slug,
            'url': model['media'].url
        })
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_media_dict(), [{
            **self.model_to_dict(model, 'media')
        }])
class CertificateTestSuite(AdmissionsTestCase):
    """Test /certificate"""

    def test_certificate_slug_academy_id_syllabus_without_auth(self):
        """Test /certificate without auth"""
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': 'they-killed-kenny', 'academy_id': 1})
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, {
            'detail': 'Authentication credentials were not provided.',
            'status_code': status.HTTP_401_UNAUTHORIZED
        })
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(self.all_certificate_dict(), [])

    def test_certificate_slug_academy_id_syllabus_without_capability(self):
        """Test /certificate without auth"""
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': 'they-killed-kenny', 'academy_id': 1})
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()
        expected = {
            'status_code': 403,
            'detail': "You (user: 1) don't have this capability: read_syllabus for academy 1"
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(self.all_certificate_dict(), [])

    def test_certificate_slug_academy_id_syllabus_without_data(self):
        """Test /certificate without auth"""
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': 'they-killed-kenny', 'academy_id': 1})
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='read_syllabus', role='potato')
        response = self.client.get(url)
        json = response.json()
        expected = {
            'status_code': 404,
            'detail': 'Certificate slug not found'
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_certificate_dict(), [{
            **self.model_to_dict(model, 'certificate'),
        }])


    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_without_syllabus(self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True, certificate=True, profile_academy=True,
            capability='read_syllabus', role='potato')
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': model['certificate'].slug, 'academy_id': 1})
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(self.all_syllabus_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus(self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True, certificate=True, profile_academy=True,
            capability='read_syllabus', role='potato', syllabus=True)
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': model['certificate'].slug, 'academy_id': 1})
        response = self.client.get(url)
        json = response.json()
        expected = [{
            'certificate': {
                'id': model['certificate'].id,
                'name': model['certificate'].name,
                'slug': model['certificate'].slug,
                'duration_in_days': model['cohort'].syllabus.certificate.duration_in_days,
            },
            'version': model['syllabus'].version,
        }]

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(self.all_syllabus_dict(), [{
            'academy_owner_id': model['syllabus'].academy_owner_id,
            'certificate_id': model['syllabus'].certificate_id,
            'github_url': model['syllabus'].github_url,
            'id': model['syllabus'].id,
            'json': model['syllabus'].json,
            'private': model['syllabus'].private,
            'version': model['syllabus'].version
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_post_without_capabilities(self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True)
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': 'they-killed-kenny', 'academy_id': 1})
        data = {}
        response = self.client.post(url, data)
        json = response.json()
        expected = {
            'detail': "You (user: 1) don't have this capability: crud_syllabus "
                'for academy 1',
            'status_code': 403
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(self.all_syllabus_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_post_with_bad_slug(self):
        """Test /certificate without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='crud_syllabus', role='potato')
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': 'they-killed-kenny', 'academy_id': 1})
        data = {}
        response = self.client.post(url, data)
        json = response.json()
        expected = {
            'detail': 'Invalid certificates slug they-killed-kenny',
            'status_code': 404
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_syllabus_dict(), [])

    # @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    # @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    # @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    # def test_certificate_slug_academy_id_syllabus__post__without_time_slot(self):
    #     """Test /certificate without auth"""
    #     self.headers(academy=1)
    #     model = self.generate_models(authenticate=True, profile_academy=True,
    #         capability='crud_syllabus', role='potato', certificate=True)
    #     url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
    #         'certificate_slug': model['certificate'].slug, 'academy_id': 1})
    #     data = {}
    #     response = self.client.post(url, data)
    #     json = response.json()
    #     expected = {
    #         'detail': 'certificate-not-have-time-slots',
    #         'status_code': 400,
    #     }

    #     self.assertEqual(json, expected)
    #     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    #     self.assertEqual(self.all_syllabus_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_post_without_required_fields(self):
        """Test /certificate without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='crud_syllabus', role='potato', certificate=True,
            certificate_time_slot=True)
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': model['certificate'].slug, 'academy_id': 1})
        data = {}
        response = self.client.post(url, data)
        json = response.json()
        expected = {
            'json': ['This field is required.']
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(self.all_syllabus_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_post(self):
        """Test /certificate without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='crud_syllabus', role='potato', certificate=True,
            certificate_time_slot=True)
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': model['certificate'].slug, 'academy_id': 1})
        data = {
            'certificate': model['certificate'].id,
            'json': {'slug': 'they-killed-kenny'}
        }
        response = self.client.post(url, data, format='json')
        json = response.json()

        self.assertDatetime(json['created_at'])
        self.assertDatetime(json['updated_at'])
        del json['created_at']
        del json['updated_at']

        expected = {
            'academy_owner': 1,
            'certificate': 1,
            'github_url': None,
            'id': 1,
            'json': data['json'],
            'private': False,
            'version': 1,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(self.all_syllabus_dict(), [{
            'academy_owner_id': 1,
            'certificate_id': 1,
            'github_url': None,
            'id': 1,
            'json': {'slug': 'they-killed-kenny'},
            'private': False,
            'version': 1,
        }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus__post__with_cohort_and_syllabus(self):
        """Test /certificate without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True, profile_academy=True,
            capability='crud_syllabus', role='potato', certificate=True,
            certificate_time_slot=True, cohort=True, syllabus=True)
        url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus', kwargs={
            'certificate_slug': model['certificate'].slug, 'academy_id': 1})
        data = {
            'certificate': model['certificate'].id,
            'json': {'slug': 'they-killed-kenny'}
        }
        response = self.client.post(url, data, format='json')
        json = response.json()

        self.assertDatetime(json['created_at'])
        self.assertDatetime(json['updated_at'])
        del json['created_at']
        del json['updated_at']

        expected = {
            'academy_owner': 1,
            'certificate': 1,
            'github_url': None,
            'id': 2,
            'json': data['json'],
            'private': False,
            'version': model.syllabus.version + 1,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(self.all_syllabus_dict(), [{
            **self.model_to_dict(model, 'syllabus')
        } , {
            'academy_owner_id': 1,
            'certificate_id': 1,
            'github_url': None,
            'id': 2,
            'json': {'slug': 'they-killed-kenny'},
            'private': False,
            'version': model.syllabus.version + 1,
        }])
Exemple #27
0
class AnswerIdTestSuite(FeedbackTestCase):
    """Test /answer/:id"""
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_without_auth(self):
        """Test /answer/:id without auth"""
        url = reverse_lazy('feedback:answer_id', kwargs={'answer_id': 9999})
        response = self.client.get(url)
        json = response.json()
        expected = {
            'detail': 'Authentication credentials were not provided.',
            'status_code': 401
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(self.count_answer(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_without_data(self):
        """Test /answer/:id without auth"""
        self.generate_models(authenticate=True)
        url = reverse_lazy('feedback:answer_id', kwargs={'answer_id': 9999})
        response = self.client.get(url)
        json = response.json()
        expected = {
            'detail': 'This survey does not exist for this user',
            'status_code': 404
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.count_answer(), 0)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_with_data_without_user(self):
        """Test /answer/:id without auth"""
        model = self.generate_models(authenticate=True, answer=True)
        db = self.model_to_dict(model, 'answer')
        url = reverse_lazy('feedback:answer_id',
                           kwargs={'answer_id': model['answer'].id})
        response = self.client.get(url)
        json = response.json()
        expected = {
            'detail': 'This survey does not exist for this user',
            'status_code': 404
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_with_data(self):
        """Test /answer/:id without auth"""
        model = self.generate_models(authenticate=True,
                                     answer=True,
                                     user=True,
                                     answer_status='SENT')
        db = self.model_to_dict(model, 'answer')
        url = reverse_lazy('feedback:answer_id',
                           kwargs={'answer_id': model['answer'].id})
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(
            json, {
                'id': model['answer'].id,
                'title': model['answer'].title,
                'lowest': model['answer'].lowest,
                'highest': model['answer'].highest,
                'lang': model['answer'].lang,
                'score': model['answer'].score,
                'comment': model['answer'].comment,
                'status': model['answer'].status,
                'opened_at': model['answer'].opened_at,
                'created_at': datetime_to_iso_format(
                    model['answer'].created_at),
                'updated_at': datetime_to_iso_format(
                    model['answer'].updated_at),
                'cohort': model['answer'].cohort,
                'survey': None,
                'academy': model['answer'].academy,
                'mentor': model['answer'].mentor,
                'event': model['answer'].event,
                'user': model['answer'].user.id,
            })

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_put_with_bad_id(self):
        """Test /answer/:id without auth"""
        self.generate_models(authenticate=True)
        url = reverse_lazy('feedback:answer_id', kwargs={'answer_id': 9999})
        response = self.client.put(url, {})
        json = response.json()
        expected = {
            'detail': 'This survey does not exist for this user',
            'status_code': 404,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_put_without_score(self):
        """Test /answer/:id without auth"""
        model = self.generate_models(authenticate=True,
                                     answer=True,
                                     user=True,
                                     answer_status='SENT')
        db = self.model_to_dict(model, 'answer')
        data = {
            'comment': 'They killed kenny',
        }
        url = reverse_lazy('feedback:answer_id',
                           kwargs={'answer_id': model['answer'].id})
        response = self.client.put(url, data)
        json = response.json()

        self.assertEqual(
            json, {'non_field_errors': ['Score must be between 1 and 10']})
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_put_with_score_less_of_1(self):
        """Test /answer/:id without auth"""
        model = self.generate_models(authenticate=True,
                                     answer=True,
                                     user=True,
                                     answer_status='SENT')
        db = self.model_to_dict(model, 'answer')
        url = reverse_lazy('feedback:answer_id',
                           kwargs={'answer_id': model['answer'].id})
        data = {
            'comment': 'They killed kenny',
            'score': 0,
        }
        response = self.client.put(url, data)
        json = response.json()

        self.assertEqual(
            json, {'non_field_errors': ['Score must be between 1 and 10']})
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_put_with_score_more_of_10(self):
        """Test /answer/:id without auth"""
        model = self.generate_models(authenticate=True,
                                     answer=True,
                                     user=True,
                                     answer_status='SENT')
        db = self.model_to_dict(model, 'answer')
        url = reverse_lazy('feedback:answer_id',
                           kwargs={'answer_id': model['answer'].id})
        data = {
            'comment': 'They killed kenny',
            'score': 11,
        }
        response = self.client.put(url, data)
        json = response.json()

        self.assertEqual(
            json, {'non_field_errors': ['Score must be between 1 and 10']})
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(self.all_answer_dict(), [db])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_put_with_all_valid_scores(self):
        """Test /answer/:id without auth"""
        for number in range(1, 10):
            self.remove_all_answer()
            model = self.generate_models(authenticate=True,
                                         answer=True,
                                         user=True,
                                         answer_status='SENT')
            db = self.model_to_dict(model, 'answer')
            url = reverse_lazy('feedback:answer_id',
                               kwargs={'answer_id': model['answer'].id})

            score = str(number)
            data = {
                'comment': 'They killed kenny',
                'score': score,
            }
            response = self.client.put(url, data)
            json = response.json()

            expected = {
                'id': model['answer'].id,
                'title': model['answer'].title,
                'lowest': model['answer'].lowest,
                'highest': model['answer'].highest,
                'lang': model['answer'].lang,
                'score': score,
                'comment': data['comment'],
                'status': 'ANSWERED',
                'opened_at': model['answer'].opened_at,
                'created_at':
                datetime_to_iso_format(model['answer'].created_at),
                'cohort': model['answer'].cohort,
                'academy': model['answer'].academy,
                'survey': None,
                'mentor': model['answer'].mentor,
                'event': model['answer'].event,
                'user': model['answer'].user.id,
            }

            del json['updated_at']

            self.assertEqual(json, expected)

            dicts = [
                answer for answer in self.all_answer_dict()
                if not 'updated_at' in answer
                or isinstance(answer['updated_at'], datetime)
                and answer.pop('updated_at')
            ]

            self.assertEqual(response.status_code, status.HTTP_200_OK)

            db['score'] = score
            db['status'] = 'ANSWERED'
            db['comment'] = data['comment']

            self.assertEqual(dicts, [db])

    # TODO: this test should return 400 but its returning 200, why? If needs to return 400 because you cannot change your score in the answer once you already answered

    # @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    # @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    # @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    # def test_answer_id_put_twice_different_score(self):
    #     """Test /answer/:id without auth"""
    #     model = self.generate_models(manual_authenticate=True, answer=True, user=True,answer_score=7,
    #         answer_status='SENT')
    #     db = self.model_to_dict(model, 'answer')
    #     url = reverse_lazy('feedback:answer_id', kwargs={'answer_id': model['answer'].id})
    #     data = {
    #         'comment': 'They killed kenny',
    #         'score': 1,
    #     }
    #     self.client.put(url, data)

    #     self.auth_with_token(model['user'])
    #     response = self.client.put(url, data)
    #     json = response.json()

    #     # assert False
    #     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_answer_id_put_twice_same_score(self):
        """Test /answer/:id without auth"""
        model = self.generate_models(manual_authenticate=True,
                                     answer=True,
                                     user=True,
                                     answer_score=3,
                                     answer_status='SENT')
        db = self.model_to_dict(model, 'answer')
        url = reverse_lazy('feedback:answer_id',
                           kwargs={'answer_id': model['answer'].id})
        data = {
            'comment': 'They killed kenny',
            'score': '3',
        }
        self.client.put(url, data)

        self.auth_with_token(model['user'])
        response = self.client.put(url, data)
        json = response.json()

        # assert False
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        db['score'] = data['score']
        db['status'] = 'ANSWERED'
        db['comment'] = data['comment']

        self.assertEqual(self.all_answer_dict(), [db])
Exemple #28
0
class CertificateTestSuite(AdmissionsTestCase):
    """Test /certificate"""
    def test_certificate_slug_academy_id_syllabus_version_without_auth(self):
        """Test /certificate without auth"""
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': 'they-killed-kenny',
                'academy_id': 1,
                'version': '1'
            })
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(
            json, {
                'detail': 'Authentication credentials were not provided.',
                'status_code': status.HTTP_401_UNAUTHORIZED
            })
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(self.all_certificate_dict(), [])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    def test_certificate_slug_academy_id_syllabus_version_without_capability(
            self):
        """Test /certificate without auth"""
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': 'they-killed-kenny',
                'academy_id': 1,
                'version': '1'
            })
        self.generate_models(authenticate=True)
        response = self.client.get(url)
        json = response.json()
        expected = {
            'status_code':
            403,
            'detail':
            'You (user: 1) don\'t have this capability: read_syllabus '
            'for academy 1'
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(self.all_certificate_dict(), [])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    def test_certificate_slug_academy_id_syllabus_version_without_data(self):
        """Test /certificate without auth"""
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': 'they-killed-kenny',
                'academy_id': 1,
                'version': '1'
            })
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='read_syllabus',
                                     role='potato')
        response = self.client.get(url)
        json = response.json()
        expected = {'status_code': 404, 'detail': 'Certificate slug not found'}

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_certificate_dict(), [{
            **self.model_to_dict(model, 'certificate'),
        }])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version_without_syllabus(
            self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True,
                                     certificate=True,
                                     profile_academy=True,
                                     capability='read_syllabus',
                                     role='potato')
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': model['certificate'].slug,
                'academy_id': 1,
                'version': '1'
            })
        response = self.client.get(url)
        json = response.json()
        expected = {'detail': 'Syllabus not found', 'status_code': 404}

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_syllabus_dict(), [])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version_with_bad_version(
            self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True,
                                     certificate=True,
                                     profile_academy=True,
                                     capability='read_syllabus',
                                     role='potato',
                                     syllabus=True)
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': model['certificate'].slug,
                'academy_id': 1,
                'version': '1'
            })
        response = self.client.get(url)
        json = response.json()
        expected = {'detail': 'Syllabus not found', 'status_code': 404}

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

        self.assertEqual(
            self.all_syllabus_dict(), [{
                'academy_owner_id': model['syllabus'].academy_owner_id,
                'certificate_id': model['syllabus'].certificate_id,
                'github_url': model['syllabus'].github_url,
                'id': model['syllabus'].id,
                'json': model['syllabus'].json,
                'private': model['syllabus'].private,
                'version': model['syllabus'].version
            }])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version(self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True,
                                     certificate=True,
                                     profile_academy=True,
                                     capability='read_syllabus',
                                     role='potato',
                                     syllabus=True)
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': model['certificate'].slug,
                'academy_id': 1,
                'version': model['syllabus'].version
            })
        response = self.client.get(url)
        json = response.json()
        expected = {
            'certificate': model['certificate'].slug,
            'json': model['syllabus'].json,
            'updated_at': datetime_to_iso_format(model['syllabus'].updated_at),
            'version': model['syllabus'].version,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(
            self.all_syllabus_dict(), [{
                'academy_owner_id': model['syllabus'].academy_owner_id,
                'certificate_id': model['syllabus'].certificate_id,
                'github_url': model['syllabus'].github_url,
                'id': model['syllabus'].id,
                'json': model['syllabus'].json,
                'private': model['syllabus'].private,
                'version': model['syllabus'].version
            }])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version_put_without_auth(
            self):
        """Test /certificate without auth"""
        model = self.generate_models()
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': 'they-killed-kenny',
                'academy_id': 1,
                'version': 1
            })
        data = {}
        response = self.client.put(url, data)
        json = response.json()
        expected = {
            'detail': 'Authentication credentials were not provided.',
            'status_code': 401
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(self.all_syllabus_dict(), [])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version_put_without_capability(
            self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True)
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': 'they-killed-kenny',
                'academy_id': 1,
                'version': 1
            })
        data = {}
        response = self.client.put(url, data)
        json = response.json()
        expected = {
            'detail':
            "You (user: 1) don't have this capability: crud_syllabus "
            "for academy 1",
            'status_code': 403
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(self.all_syllabus_dict(), [])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version_put_without_syllabus(
            self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_syllabus',
                                     role='potato')
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': 'they-killed-kenny',
                'academy_id': 1,
                'version': 1
            })
        data = {}
        response = self.client.put(url, data)
        json = response.json()
        expected = {
            'detail': 'Syllabus version not found for this academy',
            'status_code': 404
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(self.all_syllabus_dict(), [])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version_put_without_bad_version(
            self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_syllabus',
                                     role='potato',
                                     syllabus=True)
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': 'they-killed-kenny',
                'academy_id': 1,
                'version': 1
            })
        data = {}
        response = self.client.put(url, data)
        json = response.json()
        expected = {
            'detail': 'Syllabus version not found for this academy',
            'status_code': 404
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(
            self.all_syllabus_dict(), [{
                'academy_owner_id': model['syllabus'].academy_owner_id,
                'certificate_id': model['syllabus'].certificate_id,
                'github_url': model['syllabus'].github_url,
                'id': model['syllabus'].id,
                'json': model['syllabus'].json,
                'private': model['syllabus'].private,
                'version': model['syllabus'].version
            }])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version_put_without_bad_slug(
            self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_syllabus',
                                     role='potato',
                                     syllabus=True)
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': 'they-killed-kenny',
                'academy_id': 1,
                'version': model['syllabus'].version
            })
        data = {}
        response = self.client.put(url, data)
        json = response.json()
        expected = {
            'detail': 'Syllabus version not found for this academy',
            'status_code': 404
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(
            self.all_syllabus_dict(), [{
                'academy_owner_id': model['syllabus'].academy_owner_id,
                'certificate_id': model['syllabus'].certificate_id,
                'github_url': model['syllabus'].github_url,
                'id': model['syllabus'].id,
                'json': model['syllabus'].json,
                'private': model['syllabus'].private,
                'version': model['syllabus'].version
            }])
        self.assertEqual(self.all_cohort_time_slot_dict(), [])

    # @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    # @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    # @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    # def test_certificate_slug_academy_id_syllabus_version__put__without_time_slot(self):
    #     """Test /certificate without auth"""
    #     model = self.generate_models(authenticate=True, profile_academy=True,
    #         capability='crud_syllabus', role='potato', syllabus=True,
    #         certificate=True)
    #     url = reverse_lazy('admissions:certificate_slug_academy_id_syllabus_version',
    #         kwargs={'certificate_slug': model['certificate'].slug, 'academy_id': 1,
    #         'version': model['syllabus'].version})
    #     data = {}
    #     response = self.client.put(url, data)
    #     json = response.json()
    #     expected = {
    #         'detail': 'certificate-not-have-time-slots',
    #         'status_code': 400,
    #     }

    #     self.assertEqual(json, expected)
    #     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    #     self.assertEqual(self.all_syllabus_dict(), [{
    #         'academy_owner_id': model['syllabus'].academy_owner_id,
    #         'certificate_id': model['syllabus'].certificate_id,
    #         'github_url': model['syllabus'].github_url,
    #         'id': model['syllabus'].id,
    #         'json': model['syllabus'].json,
    #         'private': model['syllabus'].private,
    #         'version': model['syllabus'].version
    #     }])
    #     self.assertEqual(self.all_cohort_time_slot_dict(), [])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version_put_without_json_field(
            self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_syllabus',
                                     role='potato',
                                     syllabus=True,
                                     certificate=True,
                                     certificate_time_slot=True)
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': model['certificate'].slug,
                'academy_id': 1,
                'version': model['syllabus'].version
            })
        data = {}
        response = self.client.put(url, data)
        json = response.json()
        expected = {'json': ['This field is required.']}

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(
            self.all_syllabus_dict(), [{
                'academy_owner_id': model['syllabus'].academy_owner_id,
                'certificate_id': model['syllabus'].certificate_id,
                'github_url': model['syllabus'].github_url,
                'id': model['syllabus'].id,
                'json': model['syllabus'].json,
                'private': model['syllabus'].private,
                'version': model['syllabus'].version
            }])

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_certificate_slug_academy_id_syllabus_version_put(self):
        """Test /certificate without auth"""
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_syllabus',
                                     role='potato',
                                     syllabus=True,
                                     certificate=True,
                                     certificate_time_slot=True)
        url = reverse_lazy(
            'admissions:certificate_slug_academy_id_syllabus_version',
            kwargs={
                'certificate_slug': model['certificate'].slug,
                'academy_id': 1,
                'version': model['syllabus'].version
            })
        data = {'json': {'ova': 'thus spoke kishibe rohan'}}
        response = self.client.put(url, data, format='json')
        json = response.json()

        self.assertDatetime(json['created_at'])
        self.assertDatetime(json['updated_at'])
        del json['updated_at']

        expected = {
            'academy_owner': model['syllabus'].academy_owner_id,
            'certificate': model['syllabus'].certificate_id,
            'created_at': self.datetime_to_iso(model['syllabus'].created_at),
            'github_url': model['syllabus'].github_url,
            'id': model['syllabus'].id,
            'json': data['json'],
            'private': model['syllabus'].private,
            'version': model['syllabus'].version
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            self.all_syllabus_dict(), [{
                'academy_owner_id': model['syllabus'].academy_owner_id,
                'certificate_id': model['syllabus'].certificate_id,
                'github_url': model['syllabus'].github_url,
                'id': model['syllabus'].id,
                'json': data['json'],
                'private': model['syllabus'].private,
                'version': model['syllabus'].version
            }])
Exemple #29
0
class SendSurveyTestSuite(FeedbackTestCase):
    """Test /answer"""

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_send_cohort_bulk_survey_without_cohort(self):
        """Test /answer without auth"""
        request = HttpRequest()

        self.assertEqual(send_cohort_bulk_survey(None, request, Cohort.objects.all()), None)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_send_cohort_bulk_survey_with_educational_status_active(self):
        """Test /answer without auth"""
        request = HttpRequest()

        models = [self.generate_models(user=True, cohort_user=True, profile_academy=True,
            cohort_user_role='STUDENT', educational_status='ACTIVE', lang='en') for _ in range(0, 3)]
        academies = [(models[key]['cohort'].academy.name, key + 1) for key in range(0, 3)]
        _cohorts = [(models[key]['cohort'].certificate.name, key + 1) for key in range(0, 3)]
        self.assertEqual(send_cohort_bulk_survey(None, request, Cohort.objects.all()), None)
        expected = [{
            'academy_id': None,
            'cohort_id': key,
            'comment': None,
            'event_id': None,
            'highest': 'very good',
            'id': key,
            'lang': 'en',
            'lowest': 'not good',
            'mentor_id': None,
            'opened_at': None,
            'score': None,
            'status': 'SENT',
            'survey_id': None,
            'title': f'How has been your experience studying {c} so far?',
            'token_id': key,
            'user_id': key,
        } for c, key in _cohorts]

        dicts = [answer for answer in self.all_answer_dict() if isinstance(answer['created_at'],
            datetime) and answer.pop('created_at')]
        self.assertEqual(dicts, expected)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_send_cohort_bulk_survey_with_educational_status_graduated(self):
        """Test /answer without auth"""
        request = HttpRequest()

        models = [self.generate_models(user=True, cohort_user=True, profile_academy=True,
            cohort_user_role='STUDENT', educational_status='GRADUATED', lang='en') for _ in range(0, 3)]
        academies = [(models[key]['cohort'].academy.name, key + 1) for key in range(0, 3)]
        cohorts = Cohort.objects.all()
        self.assertEqual(send_cohort_bulk_survey(None, request, cohorts), None)
        _cohorts = [(models[key]['cohort'].certificate.name, key + 1) for key in range(0, 3)]
        expected = [{
            'academy_id': None,
            'cohort_id': key,
            'comment': None,
            'event_id': None,
            'highest': 'very good',
            'id': key,
            'lang': 'en',
            'lowest': 'not good',
            'mentor_id': None,
            'opened_at': None,
            'score': None,
            'survey_id': None,
            'status': 'SENT',
            'title': f'How has been your experience studying {cohort} so far?',
            'token_id': key,
            'user_id': key,
        } for cohort, key in _cohorts]

        dicts = [answer for answer in self.all_answer_dict() if isinstance(answer['created_at'],
            datetime) and answer.pop('created_at')]
        self.assertEqual(dicts, expected)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_send_cohort_bulk_survey_with_educational_status_postponed(self):
        """Test /answer without auth"""
        request = HttpRequest()

        models = [self.generate_models(user=True, cohort_user=True, profile_academy=True,
            cohort_user_role='STUDENT', educational_status='POSTPONED', lang='en') for _ in range(0, 3)]
        academies = [(models[key]['cohort'].academy.name, key + 1) for key in range(0, 3)]
        
        self.assertEqual(send_cohort_bulk_survey(None, request, Cohort.objects.all()), None)
        expected = []

        dicts = [answer for answer in self.all_answer_dict() if isinstance(answer['created_at'],
            datetime) and answer.pop('created_at')]
        self.assertEqual(dicts, expected)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_send_cohort_bulk_survey_with_educational_status_suspended(self):
        """Test /answer without auth"""
        request = HttpRequest()

        models = [self.generate_models(user=True, cohort_user=True, profile_academy=True,
            cohort_user_role='STUDENT', educational_status='SUSPENDED', lang='en') for _ in range(0, 3)]
        academies = [(models[key]['cohort'].academy.name, key + 1) for key in range(0, 3)]
        
        self.assertEqual(send_cohort_bulk_survey(None, request, Cohort.objects.all()), None)
        expected = []

        dicts = [answer for answer in self.all_answer_dict() if isinstance(answer['created_at'],
            datetime) and answer.pop('created_at')]
        self.assertEqual(dicts, expected)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_send_cohort_bulk_survey_with_educational_status_dropped(self):
        """Test /answer without auth"""
        request = HttpRequest()

        models = [self.generate_models(user=True, cohort_user=True, profile_academy=True,
            cohort_user_role='STUDENT', educational_status='DROPPED', lang='en') for _ in range(0, 3)]
        academies = [(models[key]['cohort'].academy.name, key + 1) for key in range(0, 3)]
        
        self.assertEqual(send_cohort_bulk_survey(None, request, Cohort.objects.all()), None)
        expected = []

        dicts = [answer for answer in self.all_answer_dict() if isinstance(answer['created_at'],
            datetime) and answer.pop('created_at')]
        self.assertEqual(dicts, expected)
Exemple #30
0
class AcademyCohortTestSuite(AdmissionsTestCase):
    """Test /cohort"""
    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_without_auth(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': 1})
        response = self.client.put(url, {})
        json = response.json()

        self.assertEqual(
            json, {
                'detail': 'Authentication credentials were not provided.',
                'status_code': status.HTTP_401_UNAUTHORIZED
            })
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_put_without_capability(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': 1})
        self.generate_models(authenticate=True)
        data = {}
        response = self.client.put(url, data)
        json = response.json()

        self.assertEqual(
            json, {
                'detail':
                "You (user: 1) don't have this capability: crud_cohort for academy 1",
                'status_code': 403
            })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_put_with_id_without_certificate(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     capability='crud_cohort',
                                     role='potato')
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': model['cohort'].id})
        data = {}
        response = self.client.put(url, data)
        json = response.json()

        self.assertEqual(json, {'certificate': ['This field is required.']})
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_put_without_cohort(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': 99999})
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_cohort',
                                     role='potato',
                                     certificate=True)
        data = {'certificate': model['certificate'].id}
        response = self.client.put(url, data)
        json = response.json()

        self.assertEqual(json, {
            'status_code': 400,
            'detail': 'Specified cohort not be found'
        })
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1),
                         self.remove_dinamics_fields(model['cohort'].__dict__))

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_put(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': 1})
        model = self.generate_models(authenticate=True,
                                     profile_academy=True,
                                     capability='crud_cohort',
                                     role='potato',
                                     certificate=True)
        data = {'certificate': model['certificate'].id}
        response = self.client.put(url, data)
        json = response.json()

        expected = {
            'id':
            model['cohort'].id,
            'slug':
            model['cohort'].slug,
            'name':
            model['cohort'].name,
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model['cohort'].kickoff_date.isoformat()),
            'ending_date':
            model['cohort'].ending_date,
            'current_day':
            model['cohort'].current_day,
            'stage':
            model['cohort'].stage,
            'language':
            model['cohort'].language,
            'certificate':
            model['cohort'].certificate.id,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1),
                         self.remove_dinamics_fields(model['cohort'].__dict__))

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_put_with_id_with_data_in_body(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     capability='crud_cohort',
                                     role='potato',
                                     certificate=True)
        model_dict = self.get_cohort_dict(1)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': model['cohort'].id})
        data = {
            'certificate': model['certificate'].id,
            'slug': 'they-killed-kenny',
            'name': 'They killed kenny',
            'current_day': model['cohort'].current_day + 1,
            'language': 'es',
        }
        model_dict.update(data)
        model_dict['certificate_id'] = model_dict['certificate']
        del model_dict['certificate']
        response = self.client.put(url, data)
        json = response.json()
        expected = {
            'id':
            model['cohort'].id,
            'slug':
            data['slug'],
            'name':
            data['name'],
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model['cohort'].kickoff_date.isoformat()),
            'ending_date':
            model['cohort'].ending_date,
            'current_day':
            data['current_day'],
            'stage':
            model['cohort'].stage,
            'language':
            data['language'],
            'certificate':
            model['cohort'].certificate.id,
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_get_with_id(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     capability='read_cohort',
                                     role='potato',
                                     certificate=True)
        model_dict = self.remove_dinamics_fields(model['cohort'].__dict__)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': model['cohort'].id})
        response = self.client.get(url)
        json = response.json()
        expected = {
            'id':
            model['cohort'].id,
            'slug':
            model['cohort'].slug,
            'name':
            model['cohort'].name,
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model['cohort'].kickoff_date.isoformat()),
            'ending_date':
            model['cohort'].ending_date,
            'stage':
            model['cohort'].stage,
            'language':
            model['cohort'].language,
            'certificate': {
                'id': model['cohort'].certificate.id,
                'slug': model['cohort'].certificate.slug,
                'name': model['cohort'].certificate.name,
                'description': model['cohort'].certificate.description,
                'logo': model['cohort'].certificate.logo,
            },
            'academy': {
                'id': model['cohort'].academy.id,
                'slug': model['cohort'].academy.slug,
                'name': model['cohort'].academy.name,
                'country': {
                    'code': model['cohort'].academy.country.code,
                    'name': model['cohort'].academy.country.name,
                },
                'city': {
                    'name': model['cohort'].academy.city.name,
                },
                'logo_url': model['cohort'].academy.logo_url,
            },
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_get_with_bad_slug(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        self.generate_models(authenticate=True,
                             cohort=True,
                             profile_academy=True,
                             capability='read_cohort',
                             role='potato',
                             certificate=True)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': 'they-killed-kenny'})
        response = self.client.get(url)

        self.assertEqual(response.data, None)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_get_with_slug(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     profile_academy=True,
                                     capability='read_cohort',
                                     role='potato',
                                     certificate=True)
        model_dict = self.remove_dinamics_fields(model['cohort'].__dict__)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': model['cohort'].slug})
        response = self.client.get(url)
        json = response.json()
        expected = {
            'id':
            model['cohort'].id,
            'slug':
            model['cohort'].slug,
            'name':
            model['cohort'].name,
            'kickoff_date':
            re.sub(r'\+00:00$', 'Z', model['cohort'].kickoff_date.isoformat()),
            'ending_date':
            model['cohort'].ending_date,
            'language':
            model['cohort'].language,
            'stage':
            model['cohort'].stage,
            'certificate': {
                'id': model['cohort'].certificate.id,
                'slug': model['cohort'].certificate.slug,
                'name': model['cohort'].certificate.name,
                'description': model['cohort'].certificate.description,
                'logo': model['cohort'].certificate.logo,
            },
            'academy': {
                'id': model['cohort'].academy.id,
                'slug': model['cohort'].academy.slug,
                'name': model['cohort'].academy.name,
                'country': model['cohort'].academy.country,
                'city': model['cohort'].academy.city,
                'logo_url': model['cohort'].academy.logo_url,
                'country': {
                    'code': model['cohort'].academy.country.code,
                    'name': model['cohort'].academy.country.name,
                },
                'city': {
                    'name': model['cohort'].academy.city.name,
                },
            },
        }

        self.assertEqual(json, expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.count_cohort(), 1)
        self.assertEqual(self.get_cohort_dict(1), model_dict)

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_delete_with_bad_id(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     user=True,
                                     profile_academy=True,
                                     capability='read_cohort',
                                     role='potato',
                                     certificate=True,
                                     cohort_user=True)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': 0})
        self.assertEqual(self.count_cohort_user(), 1)
        response = self.client.delete(url)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(self.count_cohort_user(), 1)
        self.assertEqual(self.count_cohort_stage(model['cohort'].id),
                         'INACTIVE')

    @patch(GOOGLE_CLOUD_PATH['client'], apply_google_cloud_client_mock())
    @patch(GOOGLE_CLOUD_PATH['bucket'], apply_google_cloud_bucket_mock())
    @patch(GOOGLE_CLOUD_PATH['blob'], apply_google_cloud_blob_mock())
    def test_cohort_id_delete_with_id(self):
        """Test /cohort/:id without auth"""
        self.headers(academy=1)
        model = self.generate_models(authenticate=True,
                                     cohort=True,
                                     user=True,
                                     profile_academy=True,
                                     capability='crud_cohort',
                                     role='potato',
                                     certificate=True,
                                     cohort_user=True)
        url = reverse_lazy('admissions:academy_cohort_id',
                           kwargs={'cohort_id': model['cohort'].id})
        self.assertEqual(self.count_cohort_user(), 1)
        self.assertEqual(self.count_cohort_stage(model['cohort'].id),
                         'INACTIVE')
        response = self.client.delete(url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(self.count_cohort_user(), 0)
        self.assertEqual(self.count_cohort_stage(model['cohort'].id),
                         'DELETED')