diff --git a/completion/test_utils.py b/completion/test_utils.py index e110c53d..0f9a5ef4 100644 --- a/completion/test_utils.py +++ b/completion/test_utils.py @@ -7,7 +7,11 @@ from datetime import datetime from django.contrib import auth +from django.test.utils import override_settings from edx_toggles.toggles.testutils import override_waffle_switch +from eventtracking import tracker +from django.test import TestCase +from eventtracking.django import DjangoTracker import factory from factory.django import DjangoModelFactory from opaque_keys.edx.keys import UsageKey @@ -120,3 +124,50 @@ def override_completion_switch(self, enabled): """ with override_waffle_switch(waffle.ENABLE_COMPLETION_TRACKING_SWITCH, enabled): yield + + +IN_MEMORY_BACKEND_CONFIG = { + 'mem': { + 'ENGINE': 'completion.test_utils.InMemoryBackend' + } +} + + +class InMemoryBackend: + """A backend that simply stores all events in memory""" + + def __init__(self): + super().__init__() # lint-amnesty, pylint: disable=super-with-arguments + self.events = [] + + def send(self, event): + """Store the event in a list""" + self.events.append(event) + + +@override_settings( + EVENT_TRACKING_BACKENDS=IN_MEMORY_BACKEND_CONFIG +) +class EventTrackingTestCase(TestCase): + """ + Supports capturing of emitted events in memory and inspecting them. + + Each test gets a "clean slate" and can retrieve any events emitted during their execution. + + """ + + # Make this more robust to the addition of new events that the test doesn't care about. + + def setUp(self): + super().setUp() # lint-amnesty, pylint: disable=super-with-arguments + + self.recreate_tracker() + + def recreate_tracker(self): + """ + Re-initialize the tracking system using updated django settings. + + Use this if you make use of the @override_settings decorator to customize the tracker configuration. + """ + self.tracker = DjangoTracker() + tracker.register_tracker(self.tracker) diff --git a/completion/tests/test_models.py b/completion/tests/test_models.py index 3269217b..624f2fe6 100644 --- a/completion/tests/test_models.py +++ b/completion/tests/test_models.py @@ -12,7 +12,7 @@ from opaque_keys.edx.keys import CourseKey, UsageKey from .. import models -from ..test_utils import CompletionSetUpMixin, UserFactory, submit_completions_for_testing +from ..test_utils import CompletionSetUpMixin, EventTrackingTestCase, UserFactory, submit_completions_for_testing class PercentValidatorTestCase(TestCase): @@ -29,7 +29,7 @@ def test_invalid_percent(self): self.assertRaises(ValidationError, models.validate_percent, value) -class SubmitCompletionTestCase(CompletionSetUpMixin, TestCase): +class SubmitCompletionTestCase(CompletionSetUpMixin, EventTrackingTestCase, TestCase): """ Test that BlockCompletion.objects.submit_completion has the desired semantics.