예제 #1
0
    def test_get_template_empty_repsonce_similar_artist(
            self, mock_get_recommendations, mock_get_rec):
        user = _get_user('vansika_1')

        mock_get_rec.return_value = UserRecommendationsData(
            **{
                'recording_mbid': {
                    'similar_artist': [{
                        'recording_mbid':
                        "9f5a56f4-1f83-4681-b319-70a734d0d047",
                        'score': 0.9
                    }]
                },
                'created': datetime.utcnow(),
                'user_id': 1
            })
        mock_get_recommendations.return_value = []

        recommendations_cf_recording._get_template(
            active_section='similar_artist', user=user)
        self.assertTemplateUsed(
            'recommendations_cf_recording/similar_artist.html')
        self.assert_context('active_section', 'similar_artist')
        self.assert_context('user', user)
        error_msg = "An error occurred while processing your request. Check back later!"
        self.assert_context('error_msg', error_msg)
예제 #2
0
def get_user_recommendation(user_id):
    """ Get recommendations for a user with the given row ID.

        Args:
            user_id (int): the row ID of the user in the DB

        Returns:
            A dict of the following format
            {
                'user_id' (int): the row ID of the user in the DB,
                'recording_mbid'  (dict): recommended recording mbids
                'created' (datetime): datetime object representing when
                                      the recommendation for this user was last updated.
            }

            recording_mbid = {
                'top_artist_recording': [],
                'similar_artist_recording': []
            }
    """
    with db.engine.connect() as connection:
        result = connection.execute(
            sqlalchemy.text("""
            SELECT user_id, recording_mbid, created
              FROM recommendation.cf_recording
             WHERE user_id = :user_id
            """), {'user_id': user_id})
        row = result.fetchone()

    try:
        return UserRecommendationsData(**dict(row)) if row else None
    except ValidationError:
        current_app.logger.error(
            """ValidationError when getting recommendations for user with user_id: {user_id}. Data: {data}"""
            .format(user_id=user_id,
                    data=ujson.dumps(dict(row)['recording_mbid'], indent=4)),
            exc_info=True)
        return None
예제 #3
0
    def test_get_template(self, mock_get_recommendations, mock_get_rec, mock_curr_user):
        # active_section = 'top_artist'
        user = _get_user('vansika_1')
        created = datetime.utcnow()

        mock_get_rec.return_value = UserRecommendationsData(**{
            'recording_mbid': {
                'top_artist': [{
                    'recording_mbid': "9f5a56f4-1f83-4681-b319-70a734d0d047",
                    'score': 0.9
                }]
            },
            'created': datetime.utcnow(),
            'user_id': 1
        })

        recommendations = [{
            'listened_at': 0,
            'track_metadata': {
                'artist_name': "Ultravox",
                'track_name': "Serenade (special remix)",
                'release_name': "Quartet",
                'additional_info': {
                    'recording_mbid': "af5a56f4-1f83-4681-b319-70a734d0d047",
                    'artist_mbids': ["6a70b322-9aa9-41b3-9dce-824733633a1c"]
                }
            }
        }]
        mock_get_recommendations.return_value = recommendations

        mock_curr_user.id = 10
        mock_curr_user.musicbrainz_id = 'vansika'
        mock_curr_user.auth_token = 'yyyy'

        recommendations_cf_recording._get_template(active_section='top_artist', user=user)
        mock_get_rec.assert_called_with(user.id)
        mock_get_recommendations.assert_called_once()
        self.assertTemplateUsed('recommendations_cf_recording/top_artist.html')
        self.assert_context('active_section', 'top_artist')
        self.assert_context('user', user)
        self.assert_context('last_updated', created.strftime('%d %b %Y'))

        expected_props = {
            "user": {
                "id": 2,
                "name": 'vansika_1',
            },
            "current_user": {
                "id": 10,
                "name": 'vansika',
                "auth_token": 'yyyy',
            },
            "spotify": {},
            "youtube": {},
            "api_url": current_app.config["API_URL"],
            "web_sockets_server_url": current_app.config['WEBSOCKETS_SERVER_URL'],
            "recommendations": recommendations,
            "sentry_dsn": current_app.config.get("LOG_SENTRY", {}).get("dsn")
        }
        received_props = ujson.loads(self.get_context_variable('props'))
        self.assertEqual(expected_props, received_props)

        # only assert fields that should change with 'active_section'
        # here active_section = 'similar_artist'
        mock_get_rec.return_value = UserRecommendationsData(**{
            'recording_mbid': {
                'similar_artist': [{
                    'recording_mbid': "9f5a56f4-1f83-4681-b319-70a734d0d047",
                    'score': 0.9
                }]
            },
            'created': datetime.utcnow(),
            'user_id': 1
        })

        recommendations_cf_recording._get_template(active_section='similar_artist', user=user)
        self.assertTemplateUsed('recommendations_cf_recording/similar_artist.html')
        self.assert_context('active_section', 'similar_artist')
        received_props = ujson.loads(self.get_context_variable('props'))
        self.assertEqual(expected_props, received_props)