test_aggregators.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from datetime import datetime, timedelta
  2. from unittest import mock
  3. from unittest.mock import patch
  4. import pytest
  5. import time_machine
  6. from django.contrib.auth import get_user_model
  7. from django.urls import reverse
  8. from django.utils import timezone
  9. from music.aggregators import live_charts, scrobble_counts, week_of_scrobbles
  10. from music.models import Album, Artist
  11. from profiles.models import UserProfile
  12. from scrobbles.models import Scrobble
  13. def build_scrobbles(client, request_data, num=7, spacing=2):
  14. url = reverse("scrobbles:mopidy-webhook")
  15. user = get_user_model().objects.create(username="Test User")
  16. UserProfile.objects.create(user=user, timezone="US/Eastern")
  17. for i in range(num):
  18. client.post(url, request_data, content_type="application/json")
  19. s = Scrobble.objects.last()
  20. s.user = user
  21. s.timestamp = timezone.now() - timedelta(days=i * spacing)
  22. s.played_to_completion = True
  23. s.save()
  24. @pytest.mark.django_db
  25. @time_machine.travel(datetime(2022, 3, 4, 1, 24))
  26. def test_scrobble_counts_data(client, mopidy_track_request_data):
  27. build_scrobbles(client, mopidy_track_request_data)
  28. user = get_user_model().objects.first()
  29. count_dict = scrobble_counts(user)
  30. assert count_dict == {
  31. "alltime": 7,
  32. "month": 2,
  33. "today": 1,
  34. "week": 3,
  35. "year": 7,
  36. }
  37. @pytest.mark.django_db
  38. @time_machine.travel(datetime(2022, 3, 4, 1, 24))
  39. def test_live_charts(client, mopidy_track_request_data):
  40. build_scrobbles(client, mopidy_track_request_data, 7, 1)
  41. user = get_user_model().objects.first()
  42. week = week_of_scrobbles(user)
  43. assert list(week.values()) == [1, 1, 1, 1, 1, 1, 1]
  44. tops = live_charts(user)
  45. assert tops[0].title == "Same in the End"
  46. tops = live_charts(user, chart_period="week")
  47. assert tops[0].title == "Same in the End"
  48. tops = live_charts(user, chart_period="month")
  49. assert tops[0].title == "Same in the End"
  50. tops = live_charts(user, chart_period="year")
  51. assert tops[0].title == "Same in the End"
  52. tops = live_charts(user, chart_period="week", media_type="Artist")
  53. assert tops[0].name == "Sublime"
  54. tops = live_charts(user, chart_period="month", media_type="Artist")
  55. assert tops[0].name == "Sublime"
  56. tops = live_charts(user, chart_period="year", media_type="Artist")
  57. assert tops[0].name == "Sublime"