test_video_mongo.py 46.4 KB
Newer Older
1 2
# -*- coding: utf-8 -*-
"""Video xmodule tests in mongo."""
3 4
import ddt
import itertools
5 6
import json
from collections import OrderedDict
7 8 9

from lxml import etree
from mock import patch, MagicMock, Mock
10
from nose.plugins.attrib import attr
11 12

from django.conf import settings
13
from django.test import TestCase
Alexander Kryklia committed
14
from django.test.utils import override_settings
15

Alexander Kryklia committed
16
from xmodule.video_module import VideoDescriptor, bumper_utils, video_utils
17
from xmodule.x_module import STUDENT_VIEW
18
from xmodule.tests.test_video import VideoDescriptorTestBase, instantiate_descriptor
19
from xmodule.tests.test_import import DummySystem
20

21 22 23
from edxval.api import (
    create_profile, create_video, get_video_info, ValCannotCreateError, ValVideoNotFoundError
)
24

25
from . import BaseTestXmodule
26
from .test_video_xml import SOURCE_XML
27
from .test_video_handlers import TestVideo
28 29


30
@attr('shard_1')
31 32 33
class TestVideoYouTube(TestVideo):
    METADATA = {}

34
    def test_video_constructor(self):
35
        """Make sure that all parameters extracted correctly from xml"""
36
        context = self.item_descriptor.render(STUDENT_VIEW).content
Alexander Kryklia committed
37
        sources = [u'example.mp4', u'example.webm']
38

39
        expected_context = {
40
            'branding_info': None,
41
            'license': None,
Alexander Kryklia committed
42
            'bumper_metadata': 'null',
43 44
            'cdn_eval': False,
            'cdn_exp_group': None,
45
            'display_name': u'A Name',
46
            'download_video_link': u'example.mp4',
Alexander Kryklia committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
            'metadata': json.dumps(OrderedDict({
                "saveStateUrl": self.item_descriptor.xmodule_runtime.ajax_url + "/save_user_state",
                "autoplay": False,
                "streams": "0.75:jNCf2gIqpeE,1.00:ZwkTiUPN0mg,1.25:rsq9auxASqI,1.50:kMyNdzVHHgg",
                "sub": "a_sub_file.srt.sjson",
                "sources": sources,
                "captionDataDir": None,
                "showCaptions": "true",
                "generalSpeed": 1.0,
                "speed": None,
                "savedVideoPosition": 0.0,
                "start": 3603.0,
                "end": 3610.0,
                "transcriptLanguage": "en",
                "transcriptLanguages": OrderedDict({"en": "English", "uk": u"Українська"}),
                "ytTestTimeout": 1500,
65 66 67
                "ytApiUrl": "https://www.youtube.com/iframe_api",
                "ytMetadataUrl": "https://www.googleapis.com/youtube/v3/videos/",
                "ytKey": None,
Alexander Kryklia committed
68 69 70 71 72 73 74 75
                "transcriptTranslationUrl": self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'translation/__lang__'
                ).rstrip('/?'),
                "transcriptAvailableTranslationsUrl": self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
                "autohideHtml5": False,
            })),
76
            'track': None,
77
            'transcript_download_format': 'srt',
Alexander Kryklia committed
78 79 80 81 82
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
83
        }
84

85 86
        self.assertEqual(
            context,
87
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),
88
        )
89 90


91
@attr('shard_1')
92 93 94
class TestVideoNonYouTube(TestVideo):
    """Integration tests: web client + mongo."""
    DATA = """
95
        <video show_captions="true"
96 97
        display_name="A Name"
        sub="a_sub_file.srt.sjson"
98
        download_video="true"
99 100
        start_time="01:00:03" end_time="01:00:10"
        >
101 102
            <source src="example.mp4"/>
            <source src="example.webm"/>
103
        </video>
104 105
    """
    MODEL_DATA = {
106
        'data': DATA,
107
    }
108
    METADATA = {}
109

110
    def test_video_constructor(self):
111 112 113
        """Make sure that if the 'youtube' attribute is omitted in XML, then
            the template generates an empty string for the YouTube streams.
        """
114
        context = self.item_descriptor.render(STUDENT_VIEW).content
Alexander Kryklia committed
115
        sources = [u'example.mp4', u'example.webm']
116

117
        expected_context = {
118
            'branding_info': None,
119
            'license': None,
Alexander Kryklia committed
120
            'bumper_metadata': 'null',
121 122
            'cdn_eval': False,
            'cdn_exp_group': None,
123
            'display_name': u'A Name',
124
            'download_video_link': u'example.mp4',
Alexander Kryklia committed
125
            'handout': None,
126
            'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
            'metadata': json.dumps(OrderedDict({
                "saveStateUrl": self.item_descriptor.xmodule_runtime.ajax_url + "/save_user_state",
                "autoplay": False,
                "streams": "1.00:3_yD_cEKoCk",
                "sub": "a_sub_file.srt.sjson",
                "sources": sources,
                "captionDataDir": None,
                "showCaptions": "true",
                "generalSpeed": 1.0,
                "speed": None,
                "savedVideoPosition": 0.0,
                "start": 3603.0,
                "end": 3610.0,
                "transcriptLanguage": "en",
                "transcriptLanguages": OrderedDict({"en": "English"}),
                "ytTestTimeout": 1500,
143 144 145
                "ytApiUrl": "https://www.youtube.com/iframe_api",
                "ytMetadataUrl": "https://www.googleapis.com/youtube/v3/videos/",
                "ytKey": None,
Alexander Kryklia committed
146 147 148 149 150 151 152 153
                "transcriptTranslationUrl": self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'translation/__lang__'
                ).rstrip('/?'),
                "transcriptAvailableTranslationsUrl": self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
                "autohideHtml5": False,
            })),
154
            'track': None,
155
            'transcript_download_format': 'srt',
Alexander Kryklia committed
156 157 158 159 160
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
161
        }
162

163 164
        self.assertEqual(
            context,
165
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),
166
        )
167 168


169
@attr('shard_1')
170
class TestGetHtmlMethod(BaseTestXmodule):
171
    '''
172
    Make sure that `get_html` works correctly.
173
    '''
174 175 176 177 178
    CATEGORY = "video"
    DATA = SOURCE_XML
    METADATA = {}

    def setUp(self):
179
        super(TestGetHtmlMethod, self).setUp()
180
        self.setup_course()
Alexander Kryklia committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
        self.default_metadata_dict = OrderedDict({
            "saveStateUrl": "",
            "autoplay": settings.FEATURES.get('AUTOPLAY_VIDEOS', True),
            "streams": "1.00:3_yD_cEKoCk",
            "sub": "a_sub_file.srt.sjson",
            "sources": '[]',
            "captionDataDir": None,
            "showCaptions": "true",
            "generalSpeed": 1.0,
            "speed": None,
            "savedVideoPosition": 0.0,
            "start": 3603.0,
            "end": 3610.0,
            "transcriptLanguage": "en",
            "transcriptLanguages": OrderedDict({"en": "English"}),
            "ytTestTimeout": 1500,
197 198 199
            "ytApiUrl": "https://www.youtube.com/iframe_api",
            "ytMetadataUrl": "https://www.googleapis.com/youtube/v3/videos/",
            "ytKey": None,
Alexander Kryklia committed
200 201 202 203 204 205 206 207
            "transcriptTranslationUrl": self.item_descriptor.xmodule_runtime.handler_url(
                self.item_descriptor, 'transcript', 'translation/__lang__'
            ).rstrip('/?'),
            "transcriptAvailableTranslationsUrl": self.item_descriptor.xmodule_runtime.handler_url(
                self.item_descriptor, 'transcript', 'available_translations'
            ).rstrip('/?'),
            "autohideHtml5": False,
        })
208 209 210 211 212 213

    def test_get_html_track(self):
        SOURCE_XML = """
            <video show_captions="true"
            display_name="A Name"
                sub="{sub}" download_track="{download_track}"
214
            start_time="01:00:03" end_time="01:00:10" download_video="true"
215 216 217 218
            >
                <source src="example.mp4"/>
                <source src="example.webm"/>
                {track}
219
                {transcripts}
220 221 222 223 224 225 226 227 228
            </video>
        """

        cases = [
            {
                'download_track': u'true',
                'track': u'<track src="http://www.example.com/track"/>',
                'sub': u'a_sub_file.srt.sjson',
                'expected_track_url': u'http://www.example.com/track',
229
                'transcripts': '',
230 231 232 233 234 235
            },
            {
                'download_track': u'true',
                'track': u'',
                'sub': u'a_sub_file.srt.sjson',
                'expected_track_url': u'a_sub_file.srt.sjson',
236
                'transcripts': '',
237 238 239 240 241
            },
            {
                'download_track': u'true',
                'track': u'',
                'sub': u'',
242 243
                'expected_track_url': None,
                'transcripts': '',
244 245 246 247 248 249
            },
            {
                'download_track': u'false',
                'track': u'<track src="http://www.example.com/track"/>',
                'sub': u'a_sub_file.srt.sjson',
                'expected_track_url': None,
250 251 252 253 254 255 256 257
                'transcripts': '',
            },
            {
                'download_track': u'true',
                'track': u'',
                'sub': u'',
                'expected_track_url': u'a_sub_file.srt.sjson',
                'transcripts': '<transcript language="uk" src="ukrainian.srt" />',
258
            },
259
        ]
Alexander Kryklia committed
260
        sources = [u'example.mp4', u'example.webm']
261 262

        expected_context = {
263
            'branding_info': None,
264
            'license': None,
Alexander Kryklia committed
265
            'bumper_metadata': 'null',
266 267
            'cdn_eval': False,
            'cdn_exp_group': None,
268
            'display_name': u'A Name',
269
            'download_video_link': u'example.mp4',
Alexander Kryklia committed
270 271 272 273 274 275 276 277 278 279
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
            'metadata': '',
            'track': None,
            'transcript_download_format': 'srt',
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
280 281 282
        }

        for data in cases:
Alexander Kryklia committed
283 284
            metadata = self.default_metadata_dict
            metadata['sources'] = sources
285 286 287
            DATA = SOURCE_XML.format(
                download_track=data['download_track'],
                track=data['track'],
288 289
                sub=data['sub'],
                transcripts=data['transcripts'],
290 291 292
            )

            self.initialize_module(data=DATA)
293
            track_url = self.item_descriptor.xmodule_runtime.handler_url(
294 295
                self.item_descriptor, 'transcript', 'download'
            ).rstrip('/?')
296

297
            context = self.item_descriptor.render(STUDENT_VIEW).content
Alexander Kryklia committed
298 299 300 301 302
            metadata.update({
                'transcriptLanguages': {"en": "English"} if not data['transcripts'] else {"uk": u'Українська'},
                'transcriptLanguage': u'en' if not data['transcripts'] or data.get('sub') else u'uk',
                'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'translation/__lang__'
303
                ).rstrip('/?'),
Alexander Kryklia committed
304
                'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
305 306
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
Alexander Kryklia committed
307
                'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
308
                'sub': data['sub'],
Alexander Kryklia committed
309 310 311 312 313 314 315 316
            })
            expected_context.update({
                'transcript_download_format': (
                    None if self.item_descriptor.track and self.item_descriptor.download_track else 'srt'
                ),
                'track': (
                    track_url if data['expected_track_url'] == u'a_sub_file.srt.sjson' else data['expected_track_url']
                ),
317
                'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
318
                'metadata': json.dumps(metadata)
319
            })
Alexander Kryklia committed
320

321 322
            self.assertEqual(
                context,
323
                self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),
324 325
            )

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    def test_get_html_source(self):
        SOURCE_XML = """
            <video show_captions="true"
            display_name="A Name"
            sub="a_sub_file.srt.sjson" source="{source}"
            download_video="{download_video}"
            start_time="01:00:03" end_time="01:00:10"
            >
                {sources}
            </video>
        """
        cases = [
            # self.download_video == True
            {
                'download_video': 'true',
                'source': 'example_source.mp4',
                'sources': """
                    <source src="example.mp4"/>
                    <source src="example.webm"/>
                """,
                'result': {
347
                    'download_video_link': u'example_source.mp4',
Alexander Kryklia committed
348
                    'sources': [u'example.mp4', u'example.webm'],
349 350 351 352 353 354 355 356 357 358
                },
            },
            {
                'download_video': 'true',
                'source': '',
                'sources': """
                    <source src="example.mp4"/>
                    <source src="example.webm"/>
                """,
                'result': {
359
                    'download_video_link': u'example.mp4',
Alexander Kryklia committed
360
                    'sources': [u'example.mp4', u'example.webm'],
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
                },
            },
            {
                'download_video': 'true',
                'source': '',
                'sources': [],
                'result': {},
            },

            # self.download_video == False
            {
                'download_video': 'false',
                'source': 'example_source.mp4',
                'sources': """
                    <source src="example.mp4"/>
                    <source src="example.webm"/>
                """,
                'result': {
Alexander Kryklia committed
379
                    'sources': [u'example.mp4', u'example.webm'],
380 381 382 383
                },
            },
        ]

384
        initial_context = {
385
            'branding_info': None,
386
            'license': None,
Alexander Kryklia committed
387
            'bumper_metadata': 'null',
388 389
            'cdn_eval': False,
            'cdn_exp_group': None,
390
            'display_name': u'A Name',
Alexander Kryklia committed
391 392 393 394
            'download_video_link': u'example.mp4',
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
            'metadata': self.default_metadata_dict,
395
            'track': None,
396
            'transcript_download_format': 'srt',
Alexander Kryklia committed
397 398 399 400 401
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
402 403 404 405 406 407 408 409 410
        }

        for data in cases:
            DATA = SOURCE_XML.format(
                download_video=data['download_video'],
                source=data['source'],
                sources=data['sources']
            )
            self.initialize_module(data=DATA)
411
            context = self.item_descriptor.render(STUDENT_VIEW).content
412

413
            expected_context = dict(initial_context)
Alexander Kryklia committed
414 415 416
            expected_context['metadata'].update({
                'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'translation/__lang__'
417
                ).rstrip('/?'),
Alexander Kryklia committed
418
                'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
419 420
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
Alexander Kryklia committed
421 422 423 424
                'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
                'sources': data['result'].get('sources', []),
            })
            expected_context.update({
425
                'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
426 427
                'download_video_link': data['result'].get('download_video_link'),
                'metadata': json.dumps(expected_context['metadata'])
428 429 430 431
            })

            self.assertEqual(
                context,
432
                self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context)
433 434
            )

435
    def test_get_html_with_non_existent_edx_video_id(self):
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
        """
        Tests the VideoModule get_html where a edx_video_id is given but a video is not found
        """
        SOURCE_XML = """
            <video show_captions="true"
            display_name="A Name"
            sub="a_sub_file.srt.sjson" source="{source}"
            download_video="{download_video}"
            start_time="01:00:03" end_time="01:00:10"
            edx_video_id="{edx_video_id}"
            >
                {sources}
            </video>
        """
        no_video_data = {
            'download_video': 'true',
            'source': 'example_source.mp4',
            'sources': """
            <source src="example.mp4"/>
            <source src="example.webm"/>
            """,
457
            'edx_video_id': "meow",
458 459
            'result': {
                'download_video_link': u'example_source.mp4',
Alexander Kryklia committed
460
                'sources': [u'example.mp4', u'example.webm'],
461 462 463 464 465 466 467 468 469 470 471 472 473 474
            }
        }
        DATA = SOURCE_XML.format(
            download_video=no_video_data['download_video'],
            source=no_video_data['source'],
            sources=no_video_data['sources'],
            edx_video_id=no_video_data['edx_video_id']
        )
        self.initialize_module(data=DATA)

        # Referencing a non-existent VAL ID in courseware won't cause an error --
        # it'll just fall back to the values in the VideoDescriptor.
        self.assertIn("example_source.mp4", self.item_descriptor.render(STUDENT_VIEW).content)

475
    @patch('edxval.api.get_video_info')
476 477
    def test_get_html_with_mocked_edx_video_id(self, mock_get_video_info):
        mock_get_video_info.return_value = {
478
            'url': '/edxval/video/example',
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
            'edx_video_id': u'example',
            'duration': 111.0,
            'client_video_id': u'The example video',
            'encoded_videos': [
                {
                    'url': u'http://www.meowmix.com',
                    'file_size': 25556,
                    'bitrate': 9600,
                    'profile': u'desktop_mp4'
                }
            ]
        }

        SOURCE_XML = """
            <video show_captions="true"
            display_name="A Name"
            sub="a_sub_file.srt.sjson" source="{source}"
            download_video="{download_video}"
            start_time="01:00:03" end_time="01:00:10"
            edx_video_id="{edx_video_id}"
            >
                {sources}
            </video>
        """
503

504
        data = {
505 506
            # test with download_video set to false and make sure download_video_link is not set (is None)
            'download_video': 'false',
507 508 509 510 511 512 513
            'source': 'example_source.mp4',
            'sources': """
                <source src="example.mp4"/>
                <source src="example.webm"/>
            """,
            'edx_video_id': "mock item",
            'result': {
514
                'download_video_link': None,
515
                # make sure the desktop_mp4 url is included as part of the alternative sources.
Alexander Kryklia committed
516
                'sources': [u'example.mp4', u'example.webm', u'http://www.meowmix.com'],
517 518 519 520
            }
        }

        # Video found for edx_video_id
Alexander Kryklia committed
521 522 523
        metadata = self.default_metadata_dict
        metadata['autoplay'] = False
        metadata['sources'] = ""
524
        initial_context = {
525
            'branding_info': None,
526
            'license': None,
Alexander Kryklia committed
527
            'bumper_metadata': 'null',
528 529
            'cdn_eval': False,
            'cdn_exp_group': None,
530
            'display_name': u'A Name',
Alexander Kryklia committed
531 532 533
            'download_video_link': u'example.mp4',
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
534 535
            'track': None,
            'transcript_download_format': 'srt',
Alexander Kryklia committed
536 537 538 539 540 541
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
            'metadata': metadata
542 543 544 545 546 547 548 549 550 551 552 553
        }

        DATA = SOURCE_XML.format(
            download_video=data['download_video'],
            source=data['source'],
            sources=data['sources'],
            edx_video_id=data['edx_video_id']
        )
        self.initialize_module(data=DATA)
        context = self.item_descriptor.render(STUDENT_VIEW).content

        expected_context = dict(initial_context)
Alexander Kryklia committed
554 555 556
        expected_context['metadata'].update({
            'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
                self.item_descriptor, 'transcript', 'translation/__lang__'
557
            ).rstrip('/?'),
Alexander Kryklia committed
558
            'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
559 560
                self.item_descriptor, 'transcript', 'available_translations'
            ).rstrip('/?'),
Alexander Kryklia committed
561 562 563 564
            'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
            'sources': data['result']['sources'],
        })
        expected_context.update({
565
            'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
566 567
            'download_video_link': data['result']['download_video_link'],
            'metadata': json.dumps(expected_context['metadata'])
568 569 570 571 572 573 574 575
        })

        self.assertEqual(
            context,
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context)
        )

    def test_get_html_with_existing_edx_video_id(self):
576 577 578
        # create test profiles and their encodings
        encoded_videos = []
        for profile, extension in [("desktop_webm", "webm"), ("desktop_mp4", "mp4")]:
579
            create_profile(profile)
580 581 582 583 584 585 586 587 588
            encoded_videos.append(
                dict(
                    url=u"http://fake-video.edx.org/thundercats.{}".format(extension),
                    file_size=9000,
                    bitrate=42,
                    profile=profile,
                )
            )

589 590 591 592 593
        result = create_video(
            dict(
                client_video_id="Thunder Cats",
                duration=111,
                edx_video_id="thundercats",
594
                status='test',
595
                encoded_videos=encoded_videos
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
            )
        )
        self.assertEqual(result, "thundercats")

        SOURCE_XML = """
            <video show_captions="true"
            display_name="A Name"
            sub="a_sub_file.srt.sjson" source="{source}"
            download_video="{download_video}"
            start_time="01:00:03" end_time="01:00:10"
            edx_video_id="{edx_video_id}"
            >
                {sources}
            </video>
        """
611

612 613 614 615 616 617 618
        data = {
            'download_video': 'true',
            'source': 'example_source.mp4',
            'sources': """
                <source src="example.mp4"/>
                <source src="example.webm"/>
            """,
619
            'edx_video_id': "thundercats",
620 621
            'result': {
                'download_video_link': u'http://fake-video.edx.org/thundercats.mp4',
622
                # make sure the urls for the various encodings are included as part of the alternative sources.
Alexander Kryklia committed
623 624
                'sources': [u'example.mp4', u'example.webm'] +
                           [video['url'] for video in encoded_videos],
625 626 627 628
            }
        }

        # Video found for edx_video_id
Alexander Kryklia committed
629 630
        metadata = self.default_metadata_dict
        metadata['sources'] = ""
631
        initial_context = {
632
            'branding_info': None,
633
            'license': None,
Alexander Kryklia committed
634
            'bumper_metadata': 'null',
635 636
            'cdn_eval': False,
            'cdn_exp_group': None,
637
            'display_name': u'A Name',
Alexander Kryklia committed
638 639 640
            'download_video_link': u'example.mp4',
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
641 642
            'track': None,
            'transcript_download_format': 'srt',
Alexander Kryklia committed
643 644 645 646 647 648
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
            'metadata': metadata,
649 650 651 652 653 654 655 656 657 658 659 660
        }

        DATA = SOURCE_XML.format(
            download_video=data['download_video'],
            source=data['source'],
            sources=data['sources'],
            edx_video_id=data['edx_video_id']
        )
        self.initialize_module(data=DATA)
        context = self.item_descriptor.render(STUDENT_VIEW).content

        expected_context = dict(initial_context)
Alexander Kryklia committed
661 662 663
        expected_context['metadata'].update({
            'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
                self.item_descriptor, 'transcript', 'translation/__lang__'
664
            ).rstrip('/?'),
Alexander Kryklia committed
665
            'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
666 667
                self.item_descriptor, 'transcript', 'available_translations'
            ).rstrip('/?'),
Alexander Kryklia committed
668 669 670 671
            'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
            'sources': data['result']['sources'],
        })
        expected_context.update({
672
            'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
673 674
            'download_video_link': data['result']['download_video_link'],
            'metadata': json.dumps(expected_context['metadata'])
675 676 677 678 679 680 681
        })

        self.assertEqual(
            context,
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context)
        )

682 683
    # pylint: disable=invalid-name
    @patch('xmodule.video_module.video_module.BrandingInfoConfig')
684
    @patch('xmodule.video_module.video_module.get_video_from_cdn')
685
    def test_get_html_cdn_source(self, mocked_get_video, mock_BrandingInfoConfig):
686 687 688
        """
        Test if sources got from CDN.
        """
689 690 691 692 693 694 695 696 697

        mock_BrandingInfoConfig.get_config.return_value = {
            "CN": {
                'url': 'http://www.xuetangx.com',
                'logo_src': 'http://www.xuetangx.com/static/images/logo.png',
                'logo_tag': 'Video hosted by XuetangX.com'
            }
        }

698 699
        def side_effect(*args, **kwargs):
            cdn = {
700 701
                'http://example.com/example.mp4': 'http://cdn_example.com/example.mp4',
                'http://example.com/example.webm': 'http://cdn_example.com/example.webm',
702 703 704 705 706 707 708 709 710 711
            }
            return cdn.get(args[1])

        mocked_get_video.side_effect = side_effect

        SOURCE_XML = """
            <video show_captions="true"
            display_name="A Name"
            sub="a_sub_file.srt.sjson" source="{source}"
            download_video="{download_video}"
712
            edx_video_id="{edx_video_id}"
713 714 715 716 717 718
            start_time="01:00:03" end_time="01:00:10"
            >
                {sources}
            </video>
        """

719 720 721 722 723 724 725 726 727
        case_data = {
            'download_video': 'true',
            'source': 'example_source.mp4',
            'sources': """
                <source src="http://example.com/example.mp4"/>
                <source src="http://example.com/example.webm"/>
            """,
            'result': {
                'download_video_link': u'example_source.mp4',
Alexander Kryklia committed
728 729 730 731
                'sources': [
                    u'http://cdn_example.com/example.mp4',
                    u'http://cdn_example.com/example.webm'
                ],
732
            },
733 734
        }

735
        # test with and without edx_video_id specified.
736
        cases = [
737 738
            dict(case_data, edx_video_id=""),
            dict(case_data, edx_video_id="vid-v1:12345"),
739 740 741
        ]

        initial_context = {
742 743 744 745 746
            'branding_info': {
                'logo_src': 'http://www.xuetangx.com/static/images/logo.png',
                'logo_tag': 'Video hosted by XuetangX.com',
                'url': 'http://www.xuetangx.com'
            },
747
            'license': None,
Alexander Kryklia committed
748
            'bumper_metadata': 'null',
749 750
            'cdn_eval': False,
            'cdn_exp_group': None,
751 752
            'display_name': u'A Name',
            'download_video_link': None,
Alexander Kryklia committed
753
            'handout': None,
754
            'id': None,
Alexander Kryklia committed
755
            'metadata': self.default_metadata_dict,
756 757
            'track': None,
            'transcript_download_format': 'srt',
Alexander Kryklia committed
758 759 760 761 762
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
763 764 765 766 767 768
        }

        for data in cases:
            DATA = SOURCE_XML.format(
                download_video=data['download_video'],
                source=data['source'],
769 770
                sources=data['sources'],
                edx_video_id=data['edx_video_id'],
771 772 773 774 775
            )
            self.initialize_module(data=DATA)
            self.item_descriptor.xmodule_runtime.user_location = 'CN'
            context = self.item_descriptor.render('student_view').content
            expected_context = dict(initial_context)
Alexander Kryklia committed
776 777 778
            expected_context['metadata'].update({
                'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'translation/__lang__'
779
                ).rstrip('/?'),
Alexander Kryklia committed
780
                'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
781 782
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
Alexander Kryklia committed
783 784 785 786
                'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
                'sources': data['result'].get('sources', []),
            })
            expected_context.update({
787
                'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
788 789
                'download_video_link': data['result'].get('download_video_link'),
                'metadata': json.dumps(expected_context['metadata'])
790 791 792 793 794 795 796 797
            })

            self.assertEqual(
                context,
                self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context)
            )


798
@attr('shard_1')
799 800 801 802 803 804 805 806 807
class TestVideoDescriptorInitialization(BaseTestXmodule):
    """
    Make sure that module initialization works correctly.
    """
    CATEGORY = "video"
    DATA = SOURCE_XML
    METADATA = {}

    def setUp(self):
808
        super(TestVideoDescriptorInitialization, self).setUp()
809
        self.setup_course()
810

811 812 813
    def test_source_not_in_html5sources(self):
        metadata = {
            'source': 'http://example.org/video.mp4',
814
            'html5_sources': ['http://youtu.be/3_yD_cEKoCk.mp4'],
815 816 817 818 819 820
        }

        self.initialize_module(metadata=metadata)
        fields = self.item_descriptor.editable_metadata_fields

        self.assertIn('source', fields)
821 822 823
        self.assertEqual(self.item_descriptor.source, 'http://example.org/video.mp4')
        self.assertTrue(self.item_descriptor.download_video)
        self.assertTrue(self.item_descriptor.source_visible)
824 825 826 827 828 829 830 831 832 833 834

    def test_source_in_html5sources(self):
        metadata = {
            'source': 'http://example.org/video.mp4',
            'html5_sources': ['http://example.org/video.mp4'],
        }

        self.initialize_module(metadata=metadata)
        fields = self.item_descriptor.editable_metadata_fields

        self.assertNotIn('source', fields)
835 836
        self.assertTrue(self.item_descriptor.download_video)
        self.assertFalse(self.item_descriptor.source_visible)
837

838
    def test_download_video_is_explicitly_set(self):
839 840 841 842 843 844
        metadata = {
            'track': u'http://some_track.srt',
            'source': 'http://example.org/video.mp4',
            'html5_sources': ['http://youtu.be/3_yD_cEKoCk.mp4'],
            'download_video': False,
        }
845

846
        self.initialize_module(metadata=metadata)
847

848 849 850
        fields = self.item_descriptor.editable_metadata_fields
        self.assertIn('source', fields)
        self.assertIn('download_video', fields)
851

852 853 854
        self.assertFalse(self.item_descriptor.download_video)
        self.assertTrue(self.item_descriptor.source_visible)
        self.assertTrue(self.item_descriptor.download_track)
855 856 857 858

    def test_source_is_empty(self):
        metadata = {
            'source': '',
859
            'html5_sources': ['http://youtu.be/3_yD_cEKoCk.mp4'],
860 861 862 863 864 865
        }

        self.initialize_module(metadata=metadata)
        fields = self.item_descriptor.editable_metadata_fields

        self.assertNotIn('source', fields)
866
        self.assertFalse(self.item_descriptor.download_video)
867 868


869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
@ddt.ddt
class TestVideoDescriptorStudentViewJson(TestCase):
    """
    Tests for the student_view_json method on VideoDescriptor.
    """
    TEST_DURATION = 111.0
    TEST_PROFILE = "mobile"
    TEST_SOURCE_URL = "http://www.example.com/source.mp4"
    TEST_LANGUAGE = "ge"
    TEST_ENCODED_VIDEO = {
        'profile': TEST_PROFILE,
        'bitrate': 333,
        'url': 'http://example.com/video',
        'file_size': 222,
    }
    TEST_EDX_VIDEO_ID = 'test_edx_video_id'

    def setUp(self):
        super(TestVideoDescriptorStudentViewJson, self).setUp()
        sample_xml = (
            "<video display_name='Test Video'> " +
            "<source src='" + self.TEST_SOURCE_URL + "'/> " +
            "<transcript language='" + self.TEST_LANGUAGE + "' src='german_translation.srt' /> " +
            "</video>"
        )
        self.transcript_url = "transcript_url"
        self.video = instantiate_descriptor(data=sample_xml)
        self.video.runtime.handler_url = Mock(return_value=self.transcript_url)

    def setup_val_video(self, associate_course_in_val=False):
        """
        Creates a video entry in VAL.
        Arguments:
            associate_course - If True, associates the test course with the video in VAL.
        """
        create_profile('mobile')
        create_video({
            'edx_video_id': self.TEST_EDX_VIDEO_ID,
            'client_video_id': 'test_client_video_id',
            'duration': self.TEST_DURATION,
            'status': 'dummy',
            'encoded_videos': [self.TEST_ENCODED_VIDEO],
            'courses': [self.video.location.course_key] if associate_course_in_val else [],
        })
        self.val_video = get_video_info(self.TEST_EDX_VIDEO_ID)  # pylint: disable=attribute-defined-outside-init

    def get_result(self, allow_cache_miss=True):
        """
        Returns the result from calling the video's student_view_json method.
        Arguments:
            allow_cache_miss is passed in the context to the student_view_json method.
        """
        context = {
            "profiles": [self.TEST_PROFILE],
            "allow_cache_miss": "True" if allow_cache_miss else "False"
        }
        return self.video.student_view_json(context)

    def verify_result_with_fallback_url(self, result):
        """
        Verifies the result is as expected when returning "fallback" video data (not from VAL).
        """
        self.assertDictEqual(
            result,
            {
                "only_on_web": False,
                "duration": None,
                "transcripts": {self.TEST_LANGUAGE: self.transcript_url},
                "encoded_videos": {"fallback": {"url": self.TEST_SOURCE_URL, "file_size": 0}},
            }
        )

    def verify_result_with_val_profile(self, result):
        """
        Verifies the result is as expected when returning video data from VAL.
        """
        self.assertDictContainsSubset(
            result.pop("encoded_videos")[self.TEST_PROFILE],
            self.TEST_ENCODED_VIDEO,
        )
        self.assertDictEqual(
            result,
            {
                "only_on_web": False,
                "duration": self.TEST_DURATION,
                "transcripts": {self.TEST_LANGUAGE: self.transcript_url},
            }
        )

    def test_only_on_web(self):
        self.video.only_on_web = True
        result = self.get_result()
        self.assertDictEqual(result, {"only_on_web": True})

    def test_no_edx_video_id(self):
        result = self.get_result()
        self.verify_result_with_fallback_url(result)

    @ddt.data(
        *itertools.product([True, False], [True, False], [True, False])
    )
    @ddt.unpack
    def test_with_edx_video_id(self, allow_cache_miss, video_exists_in_val, associate_course_in_val):
        self.video.edx_video_id = self.TEST_EDX_VIDEO_ID
        if video_exists_in_val:
            self.setup_val_video(associate_course_in_val)
        result = self.get_result(allow_cache_miss)
        if video_exists_in_val and (associate_course_in_val or allow_cache_miss):
            self.verify_result_with_val_profile(result)
        else:
            self.verify_result_with_fallback_url(result)


982
@attr('shard_1')
983
class VideoDescriptorTest(TestCase, VideoDescriptorTestBase):
984 985 986 987
    """
    Tests for video descriptor that requires access to django settings.
    """
    def setUp(self):
988
        super(VideoDescriptorTest, self).setUp()
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
        self.descriptor.runtime.handler_url = MagicMock()

    def test_get_context(self):
        """"
        Test get_context.

        This test is located here and not in xmodule.tests because get_context calls editable_metadata_fields.
        Which, in turn, uses settings.LANGUAGES from django setttings.
        """
        correct_tabs = [
            {
                'name': "Basic",
                'template': "video/transcripts.html",
                'current': True
            },
            {
                'name': 'Advanced',
                'template': 'tabs/metadata-edit-tab.html'
            }
        ]
        rendered_context = self.descriptor.get_context()
        self.assertListEqual(rendered_context['tabs'], correct_tabs)
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058

    def test_export_val_data(self):
        self.descriptor.edx_video_id = 'test_edx_video_id'
        create_profile('mobile')
        create_video({
            'edx_video_id': self.descriptor.edx_video_id,
            'client_video_id': 'test_client_video_id',
            'duration': 111,
            'status': 'dummy',
            'encoded_videos': [{
                'profile': 'mobile',
                'url': 'http://example.com/video',
                'file_size': 222,
                'bitrate': 333,
            }],
        })

        actual = self.descriptor.definition_to_xml(resource_fs=None)
        expected_str = """
            <video download_video="false" url_name="SampleProblem">
                <video_asset client_video_id="test_client_video_id" duration="111.0">
                    <encoded_video profile="mobile" url="http://example.com/video" file_size="222" bitrate="333"/>
                </video_asset>
            </video>
        """
        parser = etree.XMLParser(remove_blank_text=True)
        expected = etree.XML(expected_str, parser=parser)
        self.assertXmlEqual(expected, actual)

    def test_export_val_data_not_found(self):
        self.descriptor.edx_video_id = 'nonexistent'
        actual = self.descriptor.definition_to_xml(resource_fs=None)
        expected_str = """<video download_video="false" url_name="SampleProblem"/>"""
        parser = etree.XMLParser(remove_blank_text=True)
        expected = etree.XML(expected_str, parser=parser)
        self.assertXmlEqual(expected, actual)

    def test_import_val_data(self):
        create_profile('mobile')
        module_system = DummySystem(load_error_modules=True)

        xml_data = """
            <video edx_video_id="test_edx_video_id">
                <video_asset client_video_id="test_client_video_id" duration="111.0">
                    <encoded_video profile="mobile" url="http://example.com/video" file_size="222" bitrate="333"/>
                </video_asset>
            </video>
        """
1059 1060 1061
        id_generator = Mock()
        id_generator.target_course_id = "test_course_id"
        video = VideoDescriptor.from_xml(xml_data, module_system, id_generator)
1062 1063 1064 1065 1066
        self.assertEqual(video.edx_video_id, 'test_edx_video_id')
        video_data = get_video_info(video.edx_video_id)
        self.assertEqual(video_data['client_video_id'], 'test_client_video_id')
        self.assertEqual(video_data['duration'], 111)
        self.assertEqual(video_data['status'], 'imported')
1067
        self.assertEqual(video_data['courses'], [id_generator.target_course_id])
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        self.assertEqual(video_data['encoded_videos'][0]['profile'], 'mobile')
        self.assertEqual(video_data['encoded_videos'][0]['url'], 'http://example.com/video')
        self.assertEqual(video_data['encoded_videos'][0]['file_size'], 222)
        self.assertEqual(video_data['encoded_videos'][0]['bitrate'], 333)

    def test_import_val_data_invalid(self):
        create_profile('mobile')
        module_system = DummySystem(load_error_modules=True)

        # Negative file_size is invalid
        xml_data = """
            <video edx_video_id="test_edx_video_id">
                <video_asset client_video_id="test_client_video_id" duration="111.0">
                    <encoded_video profile="mobile" url="http://example.com/video" file_size="-222" bitrate="333"/>
                </video_asset>
            </video>
        """
        with self.assertRaises(ValCannotCreateError):
            VideoDescriptor.from_xml(xml_data, module_system, id_generator=Mock())
        with self.assertRaises(ValVideoNotFoundError):
            get_video_info("test_edx_video_id")
Alexander Kryklia committed
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186


class TestVideoWithBumper(TestVideo):
    """
    Tests rendered content in presence of video bumper.
    """
    CATEGORY = "video"
    METADATA = {}
    FEATURES = settings.FEATURES

    @patch('xmodule.video_module.bumper_utils.get_bumper_settings')
    def test_is_bumper_enabled(self, get_bumper_settings):
        """
        Check that bumper is (not)shown if ENABLE_VIDEO_BUMPER is (False)True

        Assume that bumper settings are correct.
        """
        self.FEATURES.update({
            "SHOW_BUMPER_PERIODICITY": 1,
            "ENABLE_VIDEO_BUMPER": True,
        })

        get_bumper_settings.return_value = {
            "video_id": "edx_video_id",
            "transcripts": {},
        }
        with override_settings(FEATURES=self.FEATURES):
            self.assertTrue(bumper_utils.is_bumper_enabled(self.item_descriptor))

        self.FEATURES.update({"ENABLE_VIDEO_BUMPER": False})

        with override_settings(FEATURES=self.FEATURES):
            self.assertFalse(bumper_utils.is_bumper_enabled(self.item_descriptor))

    @patch('xmodule.video_module.bumper_utils.is_bumper_enabled')
    @patch('xmodule.video_module.bumper_utils.get_bumper_settings')
    @patch('edxval.api.get_urls_for_profiles')
    def test_bumper_metadata(self, get_url_for_profiles, get_bumper_settings, is_bumper_enabled):
        """
        Test content with rendered bumper metadata.
        """
        get_url_for_profiles.return_value = {
            "desktop_mp4": "http://test_bumper.mp4",
            "desktop_webm": "",
        }

        get_bumper_settings.return_value = {
            "video_id": "edx_video_id",
            "transcripts": {},
        }

        is_bumper_enabled.return_value = True

        content = self.item_descriptor.render(STUDENT_VIEW).content
        sources = [u'example.mp4', u'example.webm']
        expected_context = {
            'branding_info': None,
            'license': None,
            'bumper_metadata': json.dumps(OrderedDict({
                'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
                "showCaptions": "true",
                "sources": ["http://test_bumper.mp4"],
                'streams': '',
                "transcriptLanguage": "en",
                "transcriptLanguages": {"en": "English"},
                "transcriptTranslationUrl": video_utils.set_query_parameter(
                    self.item_descriptor.xmodule_runtime.handler_url(
                        self.item_descriptor, 'transcript', 'translation/__lang__'
                    ).rstrip('/?'), 'is_bumper', 1
                ),
                "transcriptAvailableTranslationsUrl": video_utils.set_query_parameter(
                    self.item_descriptor.xmodule_runtime.handler_url(
                        self.item_descriptor, 'transcript', 'available_translations'
                    ).rstrip('/?'), 'is_bumper', 1
                ),
            })),
            'cdn_eval': False,
            'cdn_exp_group': None,
            'display_name': u'A Name',
            'download_video_link': u'example.mp4',
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
            'metadata': json.dumps(OrderedDict({
                "saveStateUrl": self.item_descriptor.xmodule_runtime.ajax_url + "/save_user_state",
                "autoplay": False,
                "streams": "0.75:jNCf2gIqpeE,1.00:ZwkTiUPN0mg,1.25:rsq9auxASqI,1.50:kMyNdzVHHgg",
                "sub": "a_sub_file.srt.sjson",
                "sources": sources,
                "captionDataDir": None,
                "showCaptions": "true",
                "generalSpeed": 1.0,
                "speed": None,
                "savedVideoPosition": 0.0,
                "start": 3603.0,
                "end": 3610.0,
                "transcriptLanguage": "en",
                "transcriptLanguages": OrderedDict({"en": "English", "uk": u"Українська"}),
                "ytTestTimeout": 1500,
1187 1188 1189
                "ytApiUrl": "https://www.youtube.com/iframe_api",
                "ytMetadataUrl": "https://www.googleapis.com/youtube/v3/videos/",
                "ytKey": None,
Alexander Kryklia committed
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
                "transcriptTranslationUrl": self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'translation/__lang__'
                ).rstrip('/?'),
                "transcriptAvailableTranslationsUrl": self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
                "autohideHtml5": False,
            })),
            'track': None,
            'transcript_download_format': 'srt',
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': json.dumps(OrderedDict({
                "url": "http://img.youtube.com/vi/ZwkTiUPN0mg/0.jpg",
                "type": "youtube"
            }))
        }

        expected_content = self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context)
        self.assertEqual(content, expected_content)