test_aggregators.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. user.profile.timezone = "US/Eastern"
  17. user.profile.save()
  18. for i in range(num):
  19. client.post(url, request_data, content_type="application/json")
  20. s = Scrobble.objects.last()
  21. s.user = user
  22. s.timestamp = timezone.now() - timedelta(days=i * spacing)
  23. s.played_to_completion = True
  24. s.save()
  25. @pytest.mark.django_db
  26. @time_machine.travel(datetime(2022, 3, 4, 1, 24))
  27. def test_scrobble_counts_data(client, mopidy_track_request_data):
  28. build_scrobbles(client, mopidy_track_request_data)
  29. user = get_user_model().objects.first()
  30. count_dict = scrobble_counts(user)
  31. assert count_dict == {
  32. "alltime": 7,
  33. "month": 2,
  34. "today": 1,
  35. "week": 3,
  36. "year": 7,
  37. }
  38. @pytest.mark.django_db
  39. @time_machine.travel(datetime(2022, 3, 4, 1, 24))
  40. def test_live_charts(client, mopidy_track_request_data):
  41. build_scrobbles(client, mopidy_track_request_data, 7, 1)
  42. user = get_user_model().objects.first()
  43. week = week_of_scrobbles(user)
  44. assert list(week.values()) == [1, 1, 1, 1, 1, 1, 1]
  45. tops = live_charts(user)
  46. assert tops[0].title == "Same in the End"
  47. tops = live_charts(user, chart_period="week")
  48. assert tops[0].title == "Same in the End"
  49. tops = live_charts(user, chart_period="month")
  50. assert tops[0].title == "Same in the End"
  51. tops = live_charts(user, chart_period="year")
  52. assert tops[0].title == "Same in the End"
  53. tops = live_charts(user, chart_period="week", media_type="Artist")
  54. assert tops[0].name == "Sublime"
  55. tops = live_charts(user, chart_period="month", media_type="Artist")
  56. assert tops[0].name == "Sublime"
  57. tops = live_charts(user, chart_period="year", media_type="Artist")
  58. assert tops[0].name == "Sublime"