test_video_events.py 13.6 KB
Newer Older
1 2 3 4
"""Ensure videos emit proper events"""

import datetime
import json
Alexander Kryklia committed
5
import ddt
6
import unittest
7 8 9

from ..helpers import EventsTestMixin
from .test_video_module import VideoBaseTest
Alexander Kryklia committed
10
from ...pages.lms.video.video import _parse_time_str
11 12 13 14 15

from openedx.core.lib.tests.assertions.events import assert_event_matches, assert_events_equal
from opaque_keys.edx.keys import UsageKey, CourseKey


Alexander Kryklia committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
class VideoEventsTestMixin(EventsTestMixin, VideoBaseTest):
    """
    Useful helper methods to test video player event emission.
    """
    def assert_payload_contains_ids(self, video_event):
        """
        Video events should all contain "id" and "code" attributes in their payload.

        This function asserts that those fields are present and have correct values.
        """
        video_descriptors = self.course_fixture.get_nested_xblocks(category='video')
        video_desc = video_descriptors[0]
        video_locator = UsageKey.from_string(video_desc.locator)

        expected_event = {
            'event': {
                'id': video_locator.html_id(),
                'code': '3_yD_cEKoCk'
            }
        }
        self.assert_events_match([expected_event], [video_event])

    def assert_valid_control_event_at_time(self, video_event, time_in_seconds):
        """
        Video control events should contain valid ID fields and a valid "currentTime" field.

        This function asserts that those fields are present and have correct values.
        """
        current_time = json.loads(video_event['event'])['currentTime']
        self.assertAlmostEqual(current_time, time_in_seconds, delta=1)

    def assert_field_type(self, event_dict, field, field_type):
        """Assert that a particular `field` in the `event_dict` has a particular type"""
        self.assertIn(field, event_dict, '{0} not found in the root of the event'.format(field))
        self.assertTrue(
            isinstance(event_dict[field], field_type),
            'Expected "{key}" to be a "{field_type}", but it has the value "{value}" of type "{t}"'.format(
                key=field,
                value=event_dict[field],
                t=type(event_dict[field]),
                field_type=field_type,
            )
        )


class VideoEventsTest(VideoEventsTestMixin):
62 63
    """ Test video player event emission """

64
    @unittest.skip('AN-5867')
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    def test_video_control_events(self):
        """
        Scenario: Video component is rendered in the LMS in Youtube mode without HTML5 sources
        Given the course has a Video component in "Youtube" mode
        And I play the video
        And I watch 5 seconds of it
        And I pause the video
        Then a "load_video" event is emitted
        And a "play_video" event is emitted
        And a "pause_video" event is emitted
        """

        def is_video_event(event):
            """Filter out anything other than the video events of interest"""
            return event['event_type'] in ('load_video', 'play_video', 'pause_video')

        captured_events = []
        with self.capture_events(is_video_event, number_of_matches=3, captured_events=captured_events):
            self.navigate_to_video()
            self.video.click_player_button('play')
            self.video.wait_for_position('0:05')
            self.video.click_player_button('pause')

        for idx, video_event in enumerate(captured_events):
            self.assert_payload_contains_ids(video_event)
            if idx == 0:
                assert_event_matches({'event_type': 'load_video'}, video_event)
            elif idx == 1:
                assert_event_matches({'event_type': 'play_video'}, video_event)
                self.assert_valid_control_event_at_time(video_event, 0)
            elif idx == 2:
                assert_event_matches({'event_type': 'pause_video'}, video_event)
                self.assert_valid_control_event_at_time(video_event, self.video.seconds)

Alexander Kryklia committed
99
    def test_strict_event_format(self):
100
        """
Alexander Kryklia committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
        This test makes a very strong assertion about the fields present in events. The goal of it is to ensure that new
        fields are not added to all events mistakenly. It should be the only existing test that is updated when new top
        level fields are added to all events.
        """

        captured_events = []
        with self.capture_events(lambda e: e['event_type'] == 'load_video', captured_events=captured_events):
            self.navigate_to_video()

        load_video_event = captured_events[0]

        # Validate the event payload
        self.assert_payload_contains_ids(load_video_event)

        # We cannot predict the value of these fields so we make weaker assertions about them
        dynamic_string_fields = (
            'accept_language',
            'agent',
            'host',
            'ip',
            'event',
            'session'
        )
        for field in dynamic_string_fields:
            self.assert_field_type(load_video_event, field, basestring)
            self.assertIn(field, load_video_event, '{0} not found in the root of the event'.format(field))
            del load_video_event[field]

        # A weak assertion for the timestamp as well
        self.assert_field_type(load_video_event, 'time', datetime.datetime)
        del load_video_event['time']

        # Note that all unpredictable fields have been deleted from the event at this point

        course_key = CourseKey.from_string(self.course_id)
        static_fields_pattern = {
            'context': {
                'course_id': unicode(course_key),
                'org_id': course_key.org,
                'path': '/event',
                'user_id': self.user_info['user_id']
            },
            'event_source': 'browser',
            'event_type': 'load_video',
            'username': self.user_info['username'],
            'page': self.browser.current_url,
            'referer': self.browser.current_url,
            'name': 'load_video',
        }
        assert_events_equal(static_fields_pattern, load_video_event)


@ddt.ddt
class VideoBumperEventsTest(VideoEventsTestMixin):
    """ Test bumper video event emission """

    # helper methods
    def watch_video_and_skip(self):
        """
        Wait 5 seconds and press "skip" button.
        """
        self.video.wait_for_position('0:05')
        self.video.click_player_button('skip_bumper')

    def watch_video_and_dismiss(self):
        """
        Wait 5 seconds and press "do not show again" button.
        """
        self.video.wait_for_position('0:05')
        self.video.click_player_button('do_not_show_again')

    def wait_for_state(self, state='finished'):
        """
        Wait until video will be in given state.

        Finished state means that video is played to the end.
        """
        self.video.wait_for_state(state)

    def add_bumper(self):
        """
        Add video bumper to the course.
        """
        additional_data = {
            u'video_bumper': {
                u'value': {
                    "transcripts": {},
188
                    "video_id": "video_001"
Alexander Kryklia committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
                }
            }
        }
        self.course_fixture.add_advanced_settings(additional_data)

    @ddt.data(
        ('edx.video.bumper.skipped', watch_video_and_skip),
        ('edx.video.bumper.dismissed', watch_video_and_dismiss),
        ('edx.video.bumper.stopped', wait_for_state)
    )
    @ddt.unpack
    def test_video_control_events(self, event_type, action):
        """
        Scenario: Video component with pre-roll emits events correctly
        Given the course has a Video component in "Youtube" mode with pre-roll enabled
        And I click on the video poster
        And the pre-roll video start playing
        And I watch (5 seconds/5 seconds/to the end of) it
        And I click (skip/do not show again) video button

        Then a "edx.video.bumper.loaded" event is emitted
        And a "edx.video.bumper.played" event is emitted
        And a "edx.video.bumper.skipped/dismissed/stopped" event is emitted
        And a "load_video" event is emitted
        And a "play_video" event is emitted
        """

        def is_video_event(event):
            """Filter out anything other than the video events of interest"""
            return event['event_type'] in (
                'edx.video.bumper.loaded',
                'edx.video.bumper.played',
                'edx.video.bumper.skipped',
                'edx.video.bumper.dismissed',
                'edx.video.bumper.stopped',
                'load_video',
                'play_video',
                'pause_video'
            ) and self.video.state != 'buffering'

        captured_events = []
        self.add_bumper()
        with self.capture_events(is_video_event, number_of_matches=5, captured_events=captured_events):
            self.navigate_to_video_no_render()
            self.video.click_on_poster()
            self.video.wait_for_video_bumper_render()
            sources, duration = self.video.sources[0], self.video.duration
            action(self)

        # Filter subsequent events that appear due to bufferisation: edx.video.bumper.played
        # As bumper does not emit pause event, we filter subsequent edx.video.bumper.played events from
        # the list, except first.
        filtered_events = []
        for video_event in captured_events:
            is_played_event = video_event['event_type'] == 'edx.video.bumper.played'
            appears_again = filtered_events and video_event['event_type'] == filtered_events[-1]['event_type']
            if is_played_event and appears_again:
                continue
            filtered_events.append(video_event)

        for idx, video_event in enumerate(filtered_events):
            if idx < 3:
                self.assert_bumper_payload_contains_ids(video_event, sources, duration)
            else:
                self.assert_payload_contains_ids(video_event)

            if idx == 0:
                assert_event_matches({'event_type': 'edx.video.bumper.loaded'}, video_event)
            elif idx == 1:
                assert_event_matches({'event_type': 'edx.video.bumper.played'}, video_event)
                self.assert_valid_control_event_at_time(video_event, 0)
            elif idx == 2:
                assert_event_matches({'event_type': event_type}, video_event)
            elif idx == 3:
                assert_event_matches({'event_type': 'load_video'}, video_event)
            elif idx == 4:
                assert_event_matches({'event_type': 'play_video'}, video_event)
                self.assert_valid_control_event_at_time(video_event, 0)

    def assert_bumper_payload_contains_ids(self, video_event, sources, duration):
        """
        Bumper video events should all contain "host_component_id", "bumper_id",
        "duration", "code" attributes in their payload.
272 273 274

        This function asserts that those fields are present and have correct values.
        """
Alexander Kryklia committed
275
        self.add_bumper()
276 277 278 279 280 281
        video_descriptors = self.course_fixture.get_nested_xblocks(category='video')
        video_desc = video_descriptors[0]
        video_locator = UsageKey.from_string(video_desc.locator)

        expected_event = {
            'event': {
Alexander Kryklia committed
282 283 284 285
                'host_component_id': video_locator.html_id(),
                'bumper_id': sources,
                'duration': _parse_time_str(duration),
                'code': 'html5'
286 287 288 289 290 291 292 293 294 295 296 297
            }
        }
        self.assert_events_match([expected_event], [video_event])

    def test_strict_event_format(self):
        """
        This test makes a very strong assertion about the fields present in events. The goal of it is to ensure that new
        fields are not added to all events mistakenly. It should be the only existing test that is updated when new top
        level fields are added to all events.
        """

        captured_events = []
Alexander Kryklia committed
298 299 300 301 302
        self.add_bumper()
        filter_event = lambda e: e['event_type'] == 'edx.video.bumper.loaded'
        with self.capture_events(filter_event, captured_events=captured_events):
            self.navigate_to_video_no_render()
            self.video.click_on_poster()
303 304 305 306

        load_video_event = captured_events[0]

        # Validate the event payload
Alexander Kryklia committed
307 308
        sources, duration = self.video.sources[0], self.video.duration
        self.assert_bumper_payload_contains_ids(load_video_event, sources, duration)
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338

        # We cannot predict the value of these fields so we make weaker assertions about them
        dynamic_string_fields = (
            'accept_language',
            'agent',
            'host',
            'ip',
            'event',
            'session'
        )
        for field in dynamic_string_fields:
            self.assert_field_type(load_video_event, field, basestring)
            self.assertIn(field, load_video_event, '{0} not found in the root of the event'.format(field))
            del load_video_event[field]

        # A weak assertion for the timestamp as well
        self.assert_field_type(load_video_event, 'time', datetime.datetime)
        del load_video_event['time']

        # Note that all unpredictable fields have been deleted from the event at this point

        course_key = CourseKey.from_string(self.course_id)
        static_fields_pattern = {
            'context': {
                'course_id': unicode(course_key),
                'org_id': course_key.org,
                'path': '/event',
                'user_id': self.user_info['user_id']
            },
            'event_source': 'browser',
Alexander Kryklia committed
339
            'event_type': 'edx.video.bumper.loaded',
340 341 342
            'username': self.user_info['username'],
            'page': self.browser.current_url,
            'referer': self.browser.current_url,
Alexander Kryklia committed
343
            'name': 'edx.video.bumper.loaded',
344 345
        }
        assert_events_equal(static_fields_pattern, load_video_event)