test_aggregators.py 2.3 KB

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