test_video_mongo.py 60 KB
Newer Older
1 2
# -*- coding: utf-8 -*-
"""Video xmodule tests in mongo."""
Ned Batchelder committed
3

4
import ddt
5 6
import json
from collections import OrderedDict
7
from path import Path as path
8 9 10

from lxml import etree
from mock import patch, MagicMock, Mock
11
from nose.plugins.attrib import attr
12
from uuid import uuid4
13 14

from django.conf import settings
15
from django.test import TestCase
Alexander Kryklia committed
16
from django.test.utils import override_settings
17

Edward Zarecor committed
18
from xmodule.video_module import VideoDescriptor, bumper_utils, video_utils, rewrite_video_url
19
from xmodule.x_module import STUDENT_VIEW
20
from xmodule.tests.test_video import VideoDescriptorTestBase, instantiate_descriptor
21
from xmodule.tests.test_import import DummySystem
22 23 24 25 26 27 28
from xmodule.video_module.transcripts_utils import save_to_store, Transcript
from xmodule.modulestore.inheritance import own_metadata
from xmodule.contentstore.content import StaticContent
from xmodule.exceptions import NotFoundError
from xmodule.modulestore.tests.django_utils import (
    TEST_DATA_MONGO_MODULESTORE, TEST_DATA_SPLIT_MODULESTORE
)
29 30 31
from edxval.api import (
    create_profile, create_video, get_video_info, ValCannotCreateError, ValVideoNotFoundError
)
32

33
from . import BaseTestXmodule
34
from .test_video_xml import SOURCE_XML
35
from .test_video_handlers import TestVideo
36 37


38
@attr(shard=1)
39 40 41
class TestVideoYouTube(TestVideo):
    METADATA = {}

42
    def test_video_constructor(self):
43
        """Make sure that all parameters extracted correctly from xml"""
44
        context = self.item_descriptor.render(STUDENT_VIEW).content
Alexander Kryklia committed
45
        sources = [u'example.mp4', u'example.webm']
46

47
        expected_context = {
48
            'branding_info': None,
49
            'license': None,
Alexander Kryklia committed
50
            'bumper_metadata': 'null',
51 52
            'cdn_eval': False,
            'cdn_exp_group': None,
53
            'display_name': u'A Name',
54
            'download_video_link': u'example.mp4',
Alexander Kryklia committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
            '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,
73 74 75
                "ytApiUrl": "https://www.youtube.com/iframe_api",
                "ytMetadataUrl": "https://www.googleapis.com/youtube/v3/videos/",
                "ytKey": None,
Alexander Kryklia committed
76 77 78 79 80 81 82
                "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,
83
                "recordedYoutubeIsAvailable": True,
Alexander Kryklia committed
84
            })),
85
            'track': None,
86
            'transcript_download_format': 'srt',
Alexander Kryklia committed
87 88 89 90 91
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
92
        }
93

94 95
        self.assertEqual(
            context,
96
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),
97
        )
98 99


100
@attr(shard=1)
101 102 103
class TestVideoNonYouTube(TestVideo):
    """Integration tests: web client + mongo."""
    DATA = """
104
        <video show_captions="true"
105 106
        display_name="A Name"
        sub="a_sub_file.srt.sjson"
107
        download_video="true"
108 109
        start_time="01:00:03" end_time="01:00:10"
        >
110 111
            <source src="example.mp4"/>
            <source src="example.webm"/>
112
        </video>
113 114
    """
    MODEL_DATA = {
115
        'data': DATA,
116
    }
117
    METADATA = {}
118

119
    def test_video_constructor(self):
120 121 122
        """Make sure that if the 'youtube' attribute is omitted in XML, then
            the template generates an empty string for the YouTube streams.
        """
123
        context = self.item_descriptor.render(STUDENT_VIEW).content
Alexander Kryklia committed
124
        sources = [u'example.mp4', u'example.webm']
125

126
        expected_context = {
127
            'branding_info': None,
128
            'license': None,
Alexander Kryklia committed
129
            'bumper_metadata': 'null',
130 131
            'cdn_eval': False,
            'cdn_exp_group': None,
132
            'display_name': u'A Name',
133
            'download_video_link': u'example.mp4',
Alexander Kryklia committed
134
            'handout': None,
135
            'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
            '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,
152 153 154
                "ytApiUrl": "https://www.youtube.com/iframe_api",
                "ytMetadataUrl": "https://www.googleapis.com/youtube/v3/videos/",
                "ytKey": None,
Alexander Kryklia committed
155 156 157 158 159 160 161
                "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,
162
                "recordedYoutubeIsAvailable": True,
Alexander Kryklia committed
163
            })),
164
            'track': None,
165
            'transcript_download_format': 'srt',
Alexander Kryklia committed
166 167 168 169 170
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
171
        }
172

173 174
        self.assertEqual(
            context,
175
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),
176
        )
177 178


179
@attr(shard=1)
180
class TestGetHtmlMethod(BaseTestXmodule):
181
    '''
182
    Make sure that `get_html` works correctly.
183
    '''
184 185 186 187 188
    CATEGORY = "video"
    DATA = SOURCE_XML
    METADATA = {}

    def setUp(self):
189
        super(TestGetHtmlMethod, self).setUp()
190
        self.setup_course()
Alexander Kryklia committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
        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,
207 208 209
            "ytApiUrl": "https://www.youtube.com/iframe_api",
            "ytMetadataUrl": "https://www.googleapis.com/youtube/v3/videos/",
            "ytKey": None,
Alexander Kryklia committed
210 211 212 213 214 215 216
            "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,
217
            "recordedYoutubeIsAvailable": True,
Alexander Kryklia committed
218
        })
219 220 221 222 223 224

    def test_get_html_track(self):
        SOURCE_XML = """
            <video show_captions="true"
            display_name="A Name"
                sub="{sub}" download_track="{download_track}"
225
            start_time="01:00:03" end_time="01:00:10" download_video="true"
226 227 228 229
            >
                <source src="example.mp4"/>
                <source src="example.webm"/>
                {track}
230
                {transcripts}
231 232 233 234 235 236 237 238 239
            </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',
240
                'transcripts': '',
241 242 243 244 245 246
            },
            {
                'download_track': u'true',
                'track': u'',
                'sub': u'a_sub_file.srt.sjson',
                'expected_track_url': u'a_sub_file.srt.sjson',
247
                'transcripts': '',
248 249 250 251 252
            },
            {
                'download_track': u'true',
                'track': u'',
                'sub': u'',
253 254
                'expected_track_url': None,
                'transcripts': '',
255 256 257 258 259 260
            },
            {
                'download_track': u'false',
                'track': u'<track src="http://www.example.com/track"/>',
                'sub': u'a_sub_file.srt.sjson',
                'expected_track_url': None,
261 262 263 264 265 266 267 268
                '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" />',
269
            },
270
        ]
Alexander Kryklia committed
271
        sources = [u'example.mp4', u'example.webm']
272 273

        expected_context = {
274
            'branding_info': None,
275
            'license': None,
Alexander Kryklia committed
276
            'bumper_metadata': 'null',
277 278
            'cdn_eval': False,
            'cdn_exp_group': None,
279
            'display_name': u'A Name',
280
            'download_video_link': u'example.mp4',
Alexander Kryklia committed
281 282 283 284 285 286 287 288 289 290
            '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',
291 292 293
        }

        for data in cases:
Alexander Kryklia committed
294 295
            metadata = self.default_metadata_dict
            metadata['sources'] = sources
296 297 298
            DATA = SOURCE_XML.format(
                download_track=data['download_track'],
                track=data['track'],
299 300
                sub=data['sub'],
                transcripts=data['transcripts'],
301 302 303
            )

            self.initialize_module(data=DATA)
304
            track_url = self.item_descriptor.xmodule_runtime.handler_url(
305 306
                self.item_descriptor, 'transcript', 'download'
            ).rstrip('/?')
307

308
            context = self.item_descriptor.render(STUDENT_VIEW).content
Alexander Kryklia committed
309 310 311 312 313
            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__'
314
                ).rstrip('/?'),
Alexander Kryklia committed
315
                'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
316 317
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
Alexander Kryklia committed
318
                'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
319
                'sub': data['sub'],
Alexander Kryklia committed
320 321 322 323 324 325 326 327
            })
            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']
                ),
328
                'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
329
                'metadata': json.dumps(metadata)
330
            })
Alexander Kryklia committed
331

332 333
            self.assertEqual(
                context,
334
                self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),
335 336
            )

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    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': {
358
                    'download_video_link': u'example_source.mp4',
Alexander Kryklia committed
359
                    'sources': [u'example.mp4', u'example.webm'],
360 361 362 363 364 365 366 367 368 369
                },
            },
            {
                'download_video': 'true',
                'source': '',
                'sources': """
                    <source src="example.mp4"/>
                    <source src="example.webm"/>
                """,
                'result': {
370
                    'download_video_link': u'example.mp4',
Alexander Kryklia committed
371
                    'sources': [u'example.mp4', u'example.webm'],
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
                },
            },
            {
                '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
390
                    'sources': [u'example.mp4', u'example.webm'],
391 392 393 394
                },
            },
        ]

395
        initial_context = {
396
            'branding_info': None,
397
            'license': None,
Alexander Kryklia committed
398
            'bumper_metadata': 'null',
399 400
            'cdn_eval': False,
            'cdn_exp_group': None,
401
            'display_name': u'A Name',
Alexander Kryklia committed
402 403 404 405
            'download_video_link': u'example.mp4',
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
            'metadata': self.default_metadata_dict,
406
            'track': None,
407
            'transcript_download_format': 'srt',
Alexander Kryklia committed
408 409 410 411 412
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
413 414 415 416 417 418 419 420 421
        }

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

424
            expected_context = dict(initial_context)
Alexander Kryklia committed
425 426 427
            expected_context['metadata'].update({
                'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'translation/__lang__'
428
                ).rstrip('/?'),
Alexander Kryklia committed
429
                'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
430 431
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
Alexander Kryklia committed
432 433 434 435
                'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
                'sources': data['result'].get('sources', []),
            })
            expected_context.update({
436
                'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
437 438
                'download_video_link': data['result'].get('download_video_link'),
                'metadata': json.dumps(expected_context['metadata'])
439 440 441 442
            })

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

446
    def test_get_html_with_non_existent_edx_video_id(self):
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
        """
        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"/>
            """,
468
            'edx_video_id': "meow",
469 470
            'result': {
                'download_video_link': u'example_source.mp4',
Alexander Kryklia committed
471
                'sources': [u'example.mp4', u'example.webm'],
472 473 474 475 476 477 478 479 480 481 482 483 484 485
            }
        }
        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)

486
    def test_get_html_with_mocked_edx_video_id(self):
487 488 489 490 491 492 493 494 495 496 497
        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>
        """
498

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

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

        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)
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

        with patch('edxval.api.get_video_info') as mock_get_video_info:
            mock_get_video_info.return_value = {
                'url': '/edxval/video/example',
                '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'
                    }
                ]
            }
            context = self.item_descriptor.render(STUDENT_VIEW).content
563 564

        expected_context = dict(initial_context)
Alexander Kryklia committed
565 566 567
        expected_context['metadata'].update({
            'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
                self.item_descriptor, 'transcript', 'translation/__lang__'
568
            ).rstrip('/?'),
Alexander Kryklia committed
569
            'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
570 571
                self.item_descriptor, 'transcript', 'available_translations'
            ).rstrip('/?'),
Alexander Kryklia committed
572 573 574 575
            'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
            'sources': data['result']['sources'],
        })
        expected_context.update({
576
            'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
577 578
            'download_video_link': data['result']['download_video_link'],
            'metadata': json.dumps(expected_context['metadata'])
579 580 581 582 583 584 585 586
        })

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

    def test_get_html_with_existing_edx_video_id(self):
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
        """
        Tests the `VideoModule` `get_html` where `edx_video_id` is given and related video is found
        """
        edx_video_id = 'thundercats'
        # create video with provided edx_video_id and return encoded_videos
        encoded_videos = self.encode_and_create_video(edx_video_id)
        # data to be used to retrieve video by edxval API
        data = {
            'download_video': 'true',
            'source': 'example_source.mp4',
            'sources': """
                <source src="example.mp4"/>
                <source src="example.webm"/>
            """,
            'edx_video_id': edx_video_id,
            'result': {
                'download_video_link': u'http://fake-video.edx.org/{}.mp4'.format(edx_video_id),
                'sources': [u'example.mp4', u'example.webm'] + [video['url'] for video in encoded_videos],
            },
        }
        # context returned by get_html when provided with above data
        # expected_context, a dict to assert with context
        context, expected_context = self.helper_get_html_with_edx_video_id(data)
        self.assertEqual(
            context,
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context)
        )

    def test_get_html_with_existing_unstripped_edx_video_id(self):
        """
        Tests the `VideoModule` `get_html` where `edx_video_id` with some unwanted tab(\t)
        is given and related video is found
        """
        edx_video_id = 'thundercats'
        # create video with provided edx_video_id and return encoded_videos
        encoded_videos = self.encode_and_create_video(edx_video_id)
        # data to be used to retrieve video by edxval API
        # unstripped edx_video_id is provided here
        data = {
            'download_video': 'true',
            'source': 'example_source.mp4',
            'sources': """
                <source src="example.mp4"/>
                <source src="example.webm"/>
            """,
            'edx_video_id': "{}\t".format(edx_video_id),
            'result': {
                'download_video_link': u'http://fake-video.edx.org/{}.mp4'.format(edx_video_id),
                'sources': [u'example.mp4', u'example.webm'] + [video['url'] for video in encoded_videos],
            },
        }
        # context returned by get_html when provided with above data
        # expected_context, a dict to assert with context
        context, expected_context = self.helper_get_html_with_edx_video_id(data)
        self.assertEqual(
            context,
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context)
        )

    def encode_and_create_video(self, edx_video_id):
        """
        Create and encode video to be used for tests
        """
650 651
        encoded_videos = []
        for profile, extension in [("desktop_webm", "webm"), ("desktop_mp4", "mp4")]:
652
            create_profile(profile)
653 654
            encoded_videos.append(
                dict(
655
                    url=u"http://fake-video.edx.org/{}.{}".format(edx_video_id, extension),
656 657 658 659 660
                    file_size=9000,
                    bitrate=42,
                    profile=profile,
                )
            )
661 662
        result = create_video(
            dict(
663
                client_video_id='A Client Video id',
664
                duration=111,
665
                edx_video_id=edx_video_id,
666
                status='test',
667
                encoded_videos=encoded_videos,
668 669
            )
        )
670 671
        self.assertEqual(result, edx_video_id)
        return encoded_videos
672

673 674 675 676 677
    def helper_get_html_with_edx_video_id(self, data):
        """
        Create expected context and get actual context returned by `get_html` method.
        """
        # make sure the urls for the various encodings are included as part of the alternative sources.
678 679 680 681 682 683 684 685 686 687 688
        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>
        """
689

690
        # Video found for edx_video_id
Alexander Kryklia committed
691 692
        metadata = self.default_metadata_dict
        metadata['sources'] = ""
693
        initial_context = {
694
            'branding_info': None,
695
            'license': None,
Alexander Kryklia committed
696
            'bumper_metadata': 'null',
697 698
            'cdn_eval': False,
            'cdn_exp_group': None,
699
            'display_name': u'A Name',
Alexander Kryklia committed
700 701 702
            'download_video_link': u'example.mp4',
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
703 704
            'track': None,
            'transcript_download_format': 'srt',
Alexander Kryklia committed
705 706 707 708 709 710
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
            'metadata': metadata,
711 712
        }

713
        # pylint: disable=invalid-name
714 715 716 717 718 719 720
        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)
721
        # context returned by get_html
722 723
        context = self.item_descriptor.render(STUDENT_VIEW).content

724
        # expected_context, expected context to be returned by get_html
725
        expected_context = dict(initial_context)
Alexander Kryklia committed
726 727 728
        expected_context['metadata'].update({
            'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
                self.item_descriptor, 'transcript', 'translation/__lang__'
729
            ).rstrip('/?'),
Alexander Kryklia committed
730
            'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
731 732
                self.item_descriptor, 'transcript', 'available_translations'
            ).rstrip('/?'),
Alexander Kryklia committed
733 734 735 736
            'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
            'sources': data['result']['sources'],
        })
        expected_context.update({
737
            'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
738 739
            'download_video_link': data['result']['download_video_link'],
            'metadata': json.dumps(expected_context['metadata'])
740
        })
741
        return context, expected_context
742

743 744
    # pylint: disable=invalid-name
    @patch('xmodule.video_module.video_module.BrandingInfoConfig')
Edward Zarecor committed
745
    @patch('xmodule.video_module.video_module.rewrite_video_url')
746
    def test_get_html_cdn_source(self, mocked_get_video, mock_BrandingInfoConfig):
747
        """
Edward Zarecor committed
748
        Test if sources got from CDN
749
        """
750 751 752 753 754 755 756 757 758

        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'
            }
        }

759 760
        def side_effect(*args, **kwargs):
            cdn = {
Edward Zarecor committed
761 762
                'http://example.com/example.mp4': 'http://cdn-example.com/example.mp4',
                'http://example.com/example.webm': 'http://cdn-example.com/example.webm',
763 764 765 766 767 768 769 770 771 772
            }
            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}"
773
            edx_video_id="{edx_video_id}"
774 775 776 777 778 779
            start_time="01:00:03" end_time="01:00:10"
            >
                {sources}
            </video>
        """

780 781 782 783 784 785 786 787 788
        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
789
                'sources': [
Edward Zarecor committed
790 791
                    u'http://cdn-example.com/example.mp4',
                    u'http://cdn-example.com/example.webm'
Alexander Kryklia committed
792
                ],
793
            },
794 795
        }

796
        # test with and without edx_video_id specified.
797
        cases = [
798 799
            dict(case_data, edx_video_id=""),
            dict(case_data, edx_video_id="vid-v1:12345"),
800 801 802
        ]

        initial_context = {
803 804 805 806 807
            'branding_info': {
                'logo_src': 'http://www.xuetangx.com/static/images/logo.png',
                'logo_tag': 'Video hosted by XuetangX.com',
                'url': 'http://www.xuetangx.com'
            },
808
            'license': None,
Alexander Kryklia committed
809
            'bumper_metadata': 'null',
810 811
            'cdn_eval': False,
            'cdn_exp_group': None,
812 813
            'display_name': u'A Name',
            'download_video_link': None,
Alexander Kryklia committed
814
            'handout': None,
815
            'id': None,
Alexander Kryklia committed
816
            'metadata': self.default_metadata_dict,
817 818
            'track': None,
            'transcript_download_format': 'srt',
Alexander Kryklia committed
819 820 821 822 823
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
824 825 826 827 828 829
        }

        for data in cases:
            DATA = SOURCE_XML.format(
                download_video=data['download_video'],
                source=data['source'],
830 831
                sources=data['sources'],
                edx_video_id=data['edx_video_id'],
832 833 834 835 836
            )
            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
837 838 839
            expected_context['metadata'].update({
                'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
                    self.item_descriptor, 'transcript', 'translation/__lang__'
840
                ).rstrip('/?'),
Alexander Kryklia committed
841
                'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
842 843
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
Alexander Kryklia committed
844 845 846 847
                'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
                'sources': data['result'].get('sources', []),
            })
            expected_context.update({
848
                'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
849 850
                'download_video_link': data['result'].get('download_video_link'),
                'metadata': json.dumps(expected_context['metadata'])
851 852 853 854 855 856 857
            })

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

858 859 860 861 862 863 864 865 866 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
    @patch('xmodule.video_module.video_module.edxval_api.get_urls_for_profiles')
    def test_get_html_hls(self, get_urls_for_profiles):
        """
        Verify that hls profile functionality works as expected.

        * HLS source should be added into list of available sources
        * HLS source should not be used for download URL If available from edxval
        """
        video_xml = '<video display_name="Video" download_video="true" edx_video_id="12345-67890">[]</video>'

        get_urls_for_profiles.return_value = {
            'desktop_webm': 'https://webm.com/dw.webm',
            'hls': 'https://hls.com/hls.m3u8',
            'youtube': 'https://yt.com/?v=v0TFmdO4ZP0',
            'desktop_mp4': 'https://mp4.com/dm.mp4'
        }

        self.initialize_module(data=video_xml)
        context = self.item_descriptor.render(STUDENT_VIEW).content

        self.assertIn("'download_video_link': 'https://mp4.com/dm.mp4'", context)
        self.assertIn('"streams": "1.00:https://yt.com/?v=v0TFmdO4ZP0"', context)
        self.assertIn(
            '"sources": ["https://webm.com/dw.webm", "https://mp4.com/dm.mp4", "https://hls.com/hls.m3u8"]', context
        )

    def test_get_html_hls_no_video_id(self):
        """
        Verify that `download_video_link` is set to None for HLS videos if no video id
        """
        video_xml = """
        <video display_name="Video" download_video="true" source="https://hls.com/hls.m3u8">
        ["https://hls.com/hls2.m3u8", "https://hls.com/hls3.m3u8"]
        </video>
        """

        self.initialize_module(data=video_xml)
        context = self.item_descriptor.render(STUDENT_VIEW).content
        self.assertIn("'download_video_link': None", context)

898

899
@attr(shard=1)
Edward Zarecor committed
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
class TestVideoCDNRewriting(BaseTestXmodule):
    """
    Tests for Video CDN.
    """

    def setUp(self, *args, **kwargs):
        super(TestVideoCDNRewriting, self).setUp(*args, **kwargs)
        self.original_video_file = "original_video.mp4"
        self.original_video_url = "http://www.originalvideo.com/" + self.original_video_file

    @patch.dict("django.conf.settings.CDN_VIDEO_URLS",
                {"CN": "https://chinacdn.cn/"})
    def test_rewrite_video_url_success(self):
        """
        Test successful CDN request.
        """
        cdn_response_video_url = settings.CDN_VIDEO_URLS["CN"] + self.original_video_file

        self.assertEqual(
            rewrite_video_url(settings.CDN_VIDEO_URLS["CN"], self.original_video_url),
            cdn_response_video_url
        )

    @patch.dict("django.conf.settings.CDN_VIDEO_URLS",
                {"CN": "https://chinacdn.cn/"})
    def test_rewrite_url_concat(self):
        """
        Test that written URLs are returned clean despite input
        """
        cdn_response_video_url = settings.CDN_VIDEO_URLS["CN"] + "original_video.mp4"

        self.assertEqual(
            rewrite_video_url(settings.CDN_VIDEO_URLS["CN"] + "///", self.original_video_url),
            cdn_response_video_url
        )

    def test_rewrite_video_url_invalid_url(self):
        """
        Test if no alternative video in CDN exists.
        """
        invalid_cdn_url = 'http://http://fakecdn.com/'
        self.assertIsNone(rewrite_video_url(invalid_cdn_url, self.original_video_url))

    def test_none_args(self):
        """
        Ensure None args return None
        """
        self.assertIsNone(rewrite_video_url(None, None))

    def test_emptystring_args(self):
        """
        Ensure emptyrstring args return None
        """
        self.assertIsNone(rewrite_video_url("", ""))


956
@attr(shard=1)
957 958 959 960 961 962 963 964 965
class TestVideoDescriptorInitialization(BaseTestXmodule):
    """
    Make sure that module initialization works correctly.
    """
    CATEGORY = "video"
    DATA = SOURCE_XML
    METADATA = {}

    def setUp(self):
966
        super(TestVideoDescriptorInitialization, self).setUp()
967
        self.setup_course()
968

969 970 971
    def test_source_not_in_html5sources(self):
        metadata = {
            'source': 'http://example.org/video.mp4',
972
            'html5_sources': ['http://youtu.be/3_yD_cEKoCk.mp4'],
973 974 975 976 977 978
        }

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

        self.assertIn('source', fields)
979 980 981
        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)
982 983 984 985 986 987 988 989 990 991 992

    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)
993 994
        self.assertTrue(self.item_descriptor.download_video)
        self.assertFalse(self.item_descriptor.source_visible)
995

996
    def test_download_video_is_explicitly_set(self):
997 998 999 1000 1001 1002
        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,
        }
1003

1004
        self.initialize_module(metadata=metadata)
1005

1006 1007 1008
        fields = self.item_descriptor.editable_metadata_fields
        self.assertIn('source', fields)
        self.assertIn('download_video', fields)
1009

1010 1011 1012
        self.assertFalse(self.item_descriptor.download_video)
        self.assertTrue(self.item_descriptor.source_visible)
        self.assertTrue(self.item_descriptor.download_track)
1013 1014 1015 1016

    def test_source_is_empty(self):
        metadata = {
            'source': '',
1017
            'html5_sources': ['http://youtu.be/3_yD_cEKoCk.mp4'],
1018 1019 1020 1021 1022 1023
        }

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

        self.assertNotIn('source', fields)
1024
        self.assertFalse(self.item_descriptor.download_video)
1025 1026


1027
@attr(shard=1)
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 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
@ddt.ddt
class TestEditorSavedMethod(BaseTestXmodule):
    """
    Make sure that `editor_saved` method works correctly.
    """
    CATEGORY = "video"
    DATA = SOURCE_XML
    METADATA = {}

    def setUp(self):
        super(TestEditorSavedMethod, self).setUp()
        self.setup_course()
        self.metadata = {
            'source': 'http://youtu.be/3_yD_cEKoCk',
            'html5_sources': ['http://example.org/video.mp4'],
        }
        # path to subs_3_yD_cEKoCk.srt.sjson file
        self.file_name = 'subs_3_yD_cEKoCk.srt.sjson'
        # pylint: disable=no-value-for-parameter
        self.test_dir = path(__file__).abspath().dirname().dirname().dirname().dirname().dirname()
        self.file_path = self.test_dir + '/common/test/data/uploads/' + self.file_name

    @ddt.data(TEST_DATA_MONGO_MODULESTORE, TEST_DATA_SPLIT_MODULESTORE)
    def test_editor_saved_when_html5_sub_not_exist(self, default_store):
        """
        When there is youtube_sub exist but no html5_sub present for
        html5_sources, editor_saved function will generate new html5_sub
        for video.
        """
        self.MODULESTORE = default_store  # pylint: disable=invalid-name
        self.initialize_module(metadata=self.metadata)
        item = self.store.get_item(self.item_descriptor.location)
        with open(self.file_path, "r") as myfile:
            save_to_store(myfile.read(), self.file_name, 'text/sjson', item.location)
        item.sub = "3_yD_cEKoCk"
        # subs_video.srt.sjson does not exist before calling editor_saved function
        with self.assertRaises(NotFoundError):
            Transcript.get_asset(item.location, 'subs_video.srt.sjson')
        old_metadata = own_metadata(item)
        # calling editor_saved will generate new file subs_video.srt.sjson for html5_sources
        item.editor_saved(self.user, old_metadata, None)
        self.assertIsInstance(Transcript.get_asset(item.location, 'subs_3_yD_cEKoCk.srt.sjson'), StaticContent)
        self.assertIsInstance(Transcript.get_asset(item.location, 'subs_video.srt.sjson'), StaticContent)

    @ddt.data(TEST_DATA_MONGO_MODULESTORE, TEST_DATA_SPLIT_MODULESTORE)
    def test_editor_saved_when_youtube_and_html5_subs_exist(self, default_store):
        """
        When both youtube_sub and html5_sub already exist then no new
        sub will be generated by editor_saved function.
        """
        self.MODULESTORE = default_store
        self.initialize_module(metadata=self.metadata)
        item = self.store.get_item(self.item_descriptor.location)
        with open(self.file_path, "r") as myfile:
            save_to_store(myfile.read(), self.file_name, 'text/sjson', item.location)
            save_to_store(myfile.read(), 'subs_video.srt.sjson', 'text/sjson', item.location)
        item.sub = "3_yD_cEKoCk"
        # subs_3_yD_cEKoCk.srt.sjson and subs_video.srt.sjson already exist
        self.assertIsInstance(Transcript.get_asset(item.location, self.file_name), StaticContent)
        self.assertIsInstance(Transcript.get_asset(item.location, 'subs_video.srt.sjson'), StaticContent)
        old_metadata = own_metadata(item)
        with patch('xmodule.video_module.video_module.manage_video_subtitles_save') as manage_video_subtitles_save:
            item.editor_saved(self.user, old_metadata, None)
            self.assertFalse(manage_video_subtitles_save.called)

1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    @ddt.data(TEST_DATA_MONGO_MODULESTORE, TEST_DATA_SPLIT_MODULESTORE)
    def test_editor_saved_with_unstripped_video_id(self, default_store):
        """
        Verify editor saved when video id contains spaces/tabs.
        """
        self.MODULESTORE = default_store
        stripped_video_id = unicode(uuid4())
        unstripped_video_id = u'{video_id}{tabs}'.format(video_id=stripped_video_id, tabs=u'\t\t\t')
        self.metadata.update({
            'edx_video_id': unstripped_video_id
        })
        self.initialize_module(metadata=self.metadata)
        item = self.store.get_item(self.item_descriptor.location)
        self.assertEqual(item.edx_video_id, unstripped_video_id)

        # Now, modifying and saving the video module should strip the video id.
        old_metadata = own_metadata(item)
        item.display_name = u'New display name'
        item.editor_saved(self.user, old_metadata, None)
        self.assertEqual(item.edx_video_id, stripped_video_id)

1114

1115 1116 1117
@ddt.ddt
class TestVideoDescriptorStudentViewJson(TestCase):
    """
1118
    Tests for the student_view_data method on VideoDescriptor.
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    """
    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'
1131 1132
    TEST_YOUTUBE_ID = 'test_youtube_id'
    TEST_YOUTUBE_EXPECTED_URL = 'https://www.youtube.com/watch?v=test_youtube_id'
1133 1134 1135

    def setUp(self):
        super(TestVideoDescriptorStudentViewJson, self).setUp()
1136 1137 1138 1139 1140 1141
        video_declaration = "<video display_name='Test Video' youtube_id_1_0=\'" + self.TEST_YOUTUBE_ID + "\'>"
        sample_xml = ''.join([
            video_declaration,
            "<source src='", self.TEST_SOURCE_URL, "'/> ",
            "<transcript language='", self.TEST_LANGUAGE, "' src='german_translation.srt' /> ",
            "</video>"]
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        )
        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):
        """
1166
        Returns the result from calling the video's student_view_data method.
1167
        Arguments:
1168
            allow_cache_miss is passed in the context to the student_view_data method.
1169 1170 1171 1172 1173
        """
        context = {
            "profiles": [self.TEST_PROFILE],
            "allow_cache_miss": "True" if allow_cache_miss else "False"
        }
1174
        return self.video.student_view_data(context)
1175

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    def verify_result_with_fallback_and_youtube(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},
                    "youtube": {"url": self.TEST_YOUTUBE_EXPECTED_URL, "file_size": 0}
                },
            }
        )

    def verify_result_with_youtube_url(self, result):
1194 1195 1196 1197 1198 1199 1200 1201 1202
        """
        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},
1203
                "encoded_videos": {"youtube": {"url": self.TEST_YOUTUBE_EXPECTED_URL, "file_size": 0}},
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
            }
        )

    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()
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
        self.verify_result_with_fallback_and_youtube(result)

    def test_no_edx_video_id_and_no_fallback(self):
        video_declaration = "<video display_name='Test Video' youtube_id_1_0=\'{}\'>".format(self.TEST_YOUTUBE_ID)
        # the video has no source listed, only a youtube link, so no fallback url will be provided
        sample_xml = ''.join([
            video_declaration,
            "<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)
        result = self.get_result()
        self.verify_result_with_youtube_url(result)
1246

1247 1248 1249 1250 1251
    @ddt.data(True, False)
    def test_with_edx_video_id_video_associated_in_val(self, allow_cache_miss):
        """
        Tests retrieving a video that is stored in VAL and associated with a course in VAL.
        """
1252
        self.video.edx_video_id = self.TEST_EDX_VIDEO_ID
1253 1254
        self.setup_val_video(associate_course_in_val=True)
        # the video is associated in VAL so no cache miss should ever happen but test retrieval in both contexts
1255
        result = self.get_result(allow_cache_miss)
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
        self.verify_result_with_val_profile(result)

    @ddt.data(True, False)
    def test_with_edx_video_id_video_unassociated_in_val(self, allow_cache_miss):
        """
        Tests retrieving a video that is stored in VAL but not associated with a course in VAL.
        """
        self.video.edx_video_id = self.TEST_EDX_VIDEO_ID
        self.setup_val_video(associate_course_in_val=False)
        result = self.get_result(allow_cache_miss)
        if allow_cache_miss:
1267 1268
            self.verify_result_with_val_profile(result)
        else:
1269 1270 1271 1272 1273 1274 1275 1276
            self.verify_result_with_fallback_and_youtube(result)

    @ddt.data(True, False)
    def test_with_edx_video_id_video_not_in_val(self, allow_cache_miss):
        """
        Tests retrieving a video that is not stored in VAL.
        """
        self.video.edx_video_id = self.TEST_EDX_VIDEO_ID
1277
        # The video is not in VAL so in contexts that do and don't allow cache misses we should always get a fallback
1278 1279
        result = self.get_result(allow_cache_miss)
        self.verify_result_with_fallback_and_youtube(result)
1280 1281


1282
@attr(shard=1)
1283
class VideoDescriptorTest(TestCase, VideoDescriptorTestBase):
1284 1285 1286 1287
    """
    Tests for video descriptor that requires access to django settings.
    """
    def setUp(self):
1288
        super(VideoDescriptorTest, self).setUp()
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
        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)
1311

1312 1313 1314 1315 1316 1317
        # Assert that the Video ID field is present in basic tab metadata context.
        self.assertEqual(
            rendered_context['transcripts_basic_tab_metadata']['edx_video_id'],
            self.descriptor.editable_metadata_fields['edx_video_id']
        )

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
    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>
        """
1365 1366 1367
        id_generator = Mock()
        id_generator.target_course_id = "test_course_id"
        video = VideoDescriptor.from_xml(xml_data, module_system, id_generator)
1368 1369 1370 1371 1372
        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')
1373
        self.assertEqual(video_data['courses'], [id_generator.target_course_id])
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
        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
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492


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,
1493 1494 1495
                "ytApiUrl": "https://www.youtube.com/iframe_api",
                "ytMetadataUrl": "https://www.googleapis.com/youtube/v3/videos/",
                "ytKey": None,
Alexander Kryklia committed
1496 1497 1498 1499 1500 1501 1502
                "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,
1503
                "recordedYoutubeIsAvailable": True,
Alexander Kryklia committed
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
            })),
            '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)