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

4 5
import json
from collections import OrderedDict
6
from uuid import uuid4
7

8
import ddt
9
from django.conf import settings
10
from django.test import TestCase
Alexander Kryklia committed
11
from django.test.utils import override_settings
12 13 14 15 16
from edxval.api import ValCannotCreateError, ValVideoNotFoundError, create_profile, create_video, get_video_info
from lxml import etree
from mock import MagicMock, Mock, patch
from nose.plugins.attrib import attr
from path import Path as path
17

18 19
from xmodule.contentstore.content import StaticContent
from xmodule.exceptions import NotFoundError
20 21 22 23 24 25 26
from xmodule.modulestore.inheritance import own_metadata
from xmodule.modulestore.tests.django_utils import TEST_DATA_MONGO_MODULESTORE, TEST_DATA_SPLIT_MODULESTORE
from xmodule.tests.test_import import DummySystem
from xmodule.tests.test_video import VideoDescriptorTestBase, instantiate_descriptor
from xmodule.video_module import VideoDescriptor, bumper_utils, rewrite_video_url, video_utils
from xmodule.video_module.transcripts_utils import Transcript, save_to_store
from xmodule.x_module import STUDENT_VIEW
27

28
from .helpers import BaseTestXmodule
29
from .test_video_handlers import TestVideo
30
from .test_video_xml import SOURCE_XML
31 32


33
@attr(shard=1)
34 35 36
class TestVideoYouTube(TestVideo):
    METADATA = {}

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

42
        expected_context = {
43
            'branding_info': None,
44
            'license': None,
Alexander Kryklia committed
45
            'bumper_metadata': 'null',
46 47
            'cdn_eval': False,
            'cdn_exp_group': None,
48
            'display_name': u'A Name',
49
            'download_video_link': u'example.mp4',
Alexander Kryklia committed
50 51 52
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
            'metadata': json.dumps(OrderedDict({
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
                '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,
                'poster': None,
                '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,
                'ytApiUrl': 'https://www.youtube.com/iframe_api',
                'ytMetadataUrl': 'https://www.googleapis.com/youtube/v3/videos/',
                'ytKey': None,
                'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
Alexander Kryklia committed
73 74
                    self.item_descriptor, 'transcript', 'translation/__lang__'
                ).rstrip('/?'),
75
                'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
Alexander Kryklia committed
76 77
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
78 79
                'autohideHtml5': False,
                'recordedYoutubeIsAvailable': True,
Alexander Kryklia committed
80
            })),
81
            'track': None,
82
            'transcript_download_format': u'srt',
Alexander Kryklia committed
83 84 85 86 87
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
88
        }
89

90 91
        self.assertEqual(
            context,
92
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),
93
        )
94 95


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

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

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

170 171
        self.assertEqual(
            context,
172
            self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context),
173
        )
174 175


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

    def setUp(self):
187
        super(TestGetHtmlMethod, self).setUp()
188
        self.setup_course()
Alexander Kryklia committed
189
        self.default_metadata_dict = OrderedDict({
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
            'saveStateUrl': '',
            'autoplay': settings.FEATURES.get('AUTOPLAY_VIDEOS', True),
            'streams': '1.00:3_yD_cEKoCk',
            'sub': 'a_sub_file.srt.sjson',
            'sources': '[]',
            'poster': None,
            '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,
            'ytApiUrl': 'https://www.youtube.com/iframe_api',
            'ytMetadataUrl': 'https://www.googleapis.com/youtube/v3/videos/',
            'ytKey': None,
            'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
Alexander Kryklia committed
210 211
                self.item_descriptor, 'transcript', 'translation/__lang__'
            ).rstrip('/?'),
212
            'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
Alexander Kryklia committed
213 214
                self.item_descriptor, 'transcript', 'available_translations'
            ).rstrip('/?'),
215 216
            'autohideHtml5': False,
            'recordedYoutubeIsAvailable': True,
Alexander Kryklia committed
217
        })
218 219 220 221 222 223

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

        expected_context = {
273
            'branding_info': None,
274
            'license': None,
Alexander Kryklia committed
275
            'bumper_metadata': 'null',
276 277
            'cdn_eval': False,
            'cdn_exp_group': None,
278
            'display_name': u'A Name',
279
            'download_video_link': u'example.mp4',
Alexander Kryklia committed
280 281 282 283
            'handout': None,
            'id': self.item_descriptor.location.html_id(),
            'metadata': '',
            'track': None,
284
            'transcript_download_format': u'srt',
Alexander Kryklia committed
285 286 287 288 289
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': 'null',
290 291 292
        }

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

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

307
            context = self.item_descriptor.render(STUDENT_VIEW).content
Alexander Kryklia committed
308 309 310 311 312
            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__'
313
                ).rstrip('/?'),
Alexander Kryklia committed
314
                'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
315 316
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
Alexander Kryklia committed
317
                'saveStateUrl': self.item_descriptor.xmodule_runtime.ajax_url + '/save_user_state',
318
                'sub': data['sub'],
Alexander Kryklia committed
319 320 321
            })
            expected_context.update({
                'transcript_download_format': (
322
                    None if self.item_descriptor.track and self.item_descriptor.download_track else u'srt'
Alexander Kryklia committed
323 324 325 326
                ),
                'track': (
                    track_url if data['expected_track_url'] == u'a_sub_file.srt.sjson' else data['expected_track_url']
                ),
327
                'id': self.item_descriptor.location.html_id(),
Alexander Kryklia committed
328
                'metadata': json.dumps(metadata)
329
            })
Alexander Kryklia committed
330

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

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

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

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

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

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

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

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

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

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

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

        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
562 563

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

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

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

672 673 674 675 676
    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.
677 678 679 680 681 682 683 684 685 686 687
        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>
        """
688

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

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

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

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

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

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

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

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

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

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

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

857 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
    @ddt.data(
        (True, ['youtube', 'desktop_webm', 'desktop_mp4', 'hls']),
        (False, ['youtube', 'desktop_webm', 'desktop_mp4'])
    )
    @ddt.unpack
    def test_get_html_on_toggling_hls_feature(self, hls_feature_enabled, expected_val_profiles):
        """
        Verify val profiles on toggling HLS Playback feature.
        """
        with patch('xmodule.video_module.video_module.edxval_api.get_urls_for_profiles') as get_urls_for_profiles:
            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'
            }
            with patch('xmodule.video_module.video_module.HLSPlaybackEnabledFlag.feature_enabled') as feature_enabled:
                feature_enabled.return_value = hls_feature_enabled
                video_xml = '<video display_name="Video" download_video="true" edx_video_id="12345-67890">[]</video>'
                self.initialize_module(data=video_xml)
                self.item_descriptor.render(STUDENT_VIEW)
                get_urls_for_profiles.assert_called_with(
                    self.item_descriptor.edx_video_id,
                    expected_val_profiles,
                )

    @patch('xmodule.video_module.video_module.HLSPlaybackEnabledFlag.feature_enabled', Mock(return_value=True))
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
    @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)

924 925 926 927 928 929 930 931 932 933 934 935 936
    @patch('xmodule.video_module.video_module.edxval_api.get_course_video_image_url')
    def test_poster_image(self, get_course_video_image_url):
        """
        Verify that poster image functionality works as expected.
        """
        video_xml = '<video display_name="Video" download_video="true" edx_video_id="12345-67890">[]</video>'
        get_course_video_image_url.return_value = '/media/video-images/poster.png'

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

        self.assertIn('"poster": "/media/video-images/poster.png"', context)

937 938 939 940 941 942 943 944 945 946 947 948 949
    @patch('xmodule.video_module.video_module.edxval_api.get_course_video_image_url')
    def test_poster_image_without_edx_video_id(self, get_course_video_image_url):
        """
        Verify that poster image is set to None and there is no crash when no edx_video_id.
        """
        video_xml = '<video display_name="Video" download_video="true" edx_video_id="null">[]</video>'
        get_course_video_image_url.return_value = '/media/video-images/poster.png'

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

        self.assertIn("\'poster\': \'null\'", context)

950

951
@attr(shard=1)
Edward Zarecor committed
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 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
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("", ""))


1008
@attr(shard=1)
1009
@ddt.ddt
1010 1011 1012 1013 1014 1015 1016 1017 1018
class TestVideoDescriptorInitialization(BaseTestXmodule):
    """
    Make sure that module initialization works correctly.
    """
    CATEGORY = "video"
    DATA = SOURCE_XML
    METADATA = {}

    def setUp(self):
1019
        super(TestVideoDescriptorInitialization, self).setUp()
1020
        self.setup_course()
1021

1022 1023 1024
    def test_source_not_in_html5sources(self):
        metadata = {
            'source': 'http://example.org/video.mp4',
1025
            'html5_sources': ['http://youtu.be/3_yD_cEKoCk.mp4'],
1026 1027 1028 1029 1030 1031
        }

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

        self.assertIn('source', fields)
1032 1033 1034
        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)
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

    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)
1046 1047
        self.assertTrue(self.item_descriptor.download_video)
        self.assertFalse(self.item_descriptor.source_visible)
1048

1049
    def test_download_video_is_explicitly_set(self):
1050 1051 1052 1053 1054 1055
        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,
        }
1056

1057
        self.initialize_module(metadata=metadata)
1058

1059 1060 1061
        fields = self.item_descriptor.editable_metadata_fields
        self.assertIn('source', fields)
        self.assertIn('download_video', fields)
1062

1063 1064 1065
        self.assertFalse(self.item_descriptor.download_video)
        self.assertTrue(self.item_descriptor.source_visible)
        self.assertTrue(self.item_descriptor.download_track)
1066 1067 1068 1069

    def test_source_is_empty(self):
        metadata = {
            'source': '',
1070
            'html5_sources': ['http://youtu.be/3_yD_cEKoCk.mp4'],
1071 1072 1073 1074 1075 1076
        }

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

        self.assertNotIn('source', fields)
1077
        self.assertFalse(self.item_descriptor.download_video)
1078

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 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
    @ddt.data(
        (
            {
                'desktop_webm': 'https://webm.com/dw.webm',
                'hls': 'https://hls.com/hls.m3u8',
                'youtube': 'v0TFmdO4ZP0',
                'desktop_mp4': 'https://mp4.com/dm.mp4'
            },
            ['https://www.youtube.com/watch?v=v0TFmdO4ZP0']
        ),
        (
            {
                'desktop_webm': 'https://webm.com/dw.webm',
                'hls': 'https://hls.com/hls.m3u8',
                'youtube': None,
                'desktop_mp4': 'https://mp4.com/dm.mp4'
            },
            ['https://hls.com/hls.m3u8']
        ),
        (
            {
                'desktop_webm': 'https://webm.com/dw.webm',
                'hls': None,
                'youtube': None,
                'desktop_mp4': 'https://mp4.com/dm.mp4'
            },
            ['https://mp4.com/dm.mp4']
        ),
        (
            {
                'desktop_webm': 'https://webm.com/dw.webm',
                'hls': None,
                'youtube': None,
                'desktop_mp4': None
            },
            ['https://webm.com/dw.webm']
        ),
        (
            {
                'desktop_webm': None,
                'hls': None,
                'youtube': None,
                'desktop_mp4': None
            },
            ['https://www.youtube.com/watch?v=3_yD_cEKoCk']
        ),
    )
    @ddt.unpack
    @patch('xmodule.video_module.video_module.HLSPlaybackEnabledFlag.feature_enabled', Mock(return_value=True))
    def test_val_encoding_in_context(self, val_video_encodings, video_url):
        """
        Tests that the val encodings correctly override the video url when the edx video id is set and
        one or more encodings are present.
        """
        with patch('xmodule.video_module.video_module.edxval_api.get_urls_for_profiles') as get_urls_for_profiles:
            get_urls_for_profiles.return_value = val_video_encodings
            self.initialize_module(
                data='<video display_name="Video" download_video="true" edx_video_id="12345-67890">[]</video>'
            )
            context = self.item_descriptor.get_context()
            self.assertEqual(context['transcripts_basic_tab_metadata']['video_url']['value'], video_url)

1141

1142
@attr(shard=1)
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 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
@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)

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    @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)

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    @ddt.data(TEST_DATA_MONGO_MODULESTORE, TEST_DATA_SPLIT_MODULESTORE)
    @patch('xmodule.video_module.video_module.edxval_api.get_url_for_profile', Mock(return_value='test_yt_id'))
    def test_editor_saved_with_yt_val_profile(self, default_store):
        """
        Verify editor saved overrides `youtube_id_1_0` when a youtube val profile is there
        for a given `edx_video_id`.
        """
        self.MODULESTORE = default_store
        self.initialize_module(metadata=self.metadata)
        item = self.store.get_item(self.item_descriptor.location)
        self.assertEqual(item.youtube_id_1_0, '3_yD_cEKoCk')

        # Now, modify `edx_video_id` and save should override `youtube_id_1_0`.
        old_metadata = own_metadata(item)
        item.edx_video_id = unicode(uuid4())
        item.editor_saved(self.user, old_metadata, None)
        self.assertEqual(item.youtube_id_1_0, 'test_yt_id')

1247

1248 1249 1250
@ddt.ddt
class TestVideoDescriptorStudentViewJson(TestCase):
    """
1251
    Tests for the student_view_data method on VideoDescriptor.
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    """
    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'
1264 1265
    TEST_YOUTUBE_ID = 'test_youtube_id'
    TEST_YOUTUBE_EXPECTED_URL = 'https://www.youtube.com/watch?v=test_youtube_id'
1266 1267 1268

    def setUp(self):
        super(TestVideoDescriptorStudentViewJson, self).setUp()
1269 1270 1271 1272 1273 1274
        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>"]
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
        )
        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],
1293
            'courses': [unicode(self.video.location.course_key)] if associate_course_in_val else [],
1294 1295 1296 1297 1298
        })
        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):
        """
1299
        Returns the result from calling the video's student_view_data method.
1300
        Arguments:
1301
            allow_cache_miss is passed in the context to the student_view_data method.
1302 1303 1304 1305 1306
        """
        context = {
            "profiles": [self.TEST_PROFILE],
            "allow_cache_miss": "True" if allow_cache_miss else "False"
        }
1307
        return self.video.student_view_data(context)
1308

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
    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):
1327 1328 1329 1330 1331 1332 1333 1334 1335
        """
        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},
1336
                "encoded_videos": {"youtube": {"url": self.TEST_YOUTUBE_EXPECTED_URL, "file_size": 0}},
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
            }
        )

    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()
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        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)
1379

1380 1381 1382 1383 1384
    @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.
        """
1385
        self.video.edx_video_id = self.TEST_EDX_VIDEO_ID
1386 1387
        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
1388
        result = self.get_result(allow_cache_miss)
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
        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:
1400 1401
            self.verify_result_with_val_profile(result)
        else:
1402 1403 1404 1405 1406 1407 1408 1409
            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
1410
        # The video is not in VAL so in contexts that do and don't allow cache misses we should always get a fallback
1411 1412
        result = self.get_result(allow_cache_miss)
        self.verify_result_with_fallback_and_youtube(result)
1413 1414


1415
@attr(shard=1)
1416
class VideoDescriptorTest(TestCase, VideoDescriptorTestBase):
1417 1418 1419 1420
    """
    Tests for video descriptor that requires access to django settings.
    """
    def setUp(self):
1421
        super(VideoDescriptorTest, self).setUp()
1422
        self.descriptor.runtime.handler_url = MagicMock()
1423
        self.descriptor.runtime.course_id = MagicMock()
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444

    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)
1445

1446 1447 1448 1449 1450 1451
        # 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']
        )

1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
    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">
1471
                <video_asset client_video_id="test_client_video_id" duration="111.0" image="">
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
                    <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>
        """
1499 1500 1501
        id_generator = Mock()
        id_generator.target_course_id = "test_course_id"
        video = VideoDescriptor.from_xml(xml_data, module_system, id_generator)
1502 1503 1504 1505 1506
        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')
1507
        self.assertEqual(video_data['courses'], [{id_generator.target_course_id: None}])
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
        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
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570


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 = {
1571 1572
            'desktop_mp4': 'http://test_bumper.mp4',
            'desktop_webm': '',
Alexander Kryklia committed
1573 1574 1575
        }

        get_bumper_settings.return_value = {
1576 1577
            'video_id': 'edx_video_id',
            'transcripts': {},
Alexander Kryklia committed
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
        }

        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',
1589 1590
                'showCaptions': 'true',
                'sources': ['http://test_bumper.mp4'],
Alexander Kryklia committed
1591
                'streams': '',
1592 1593 1594
                'transcriptLanguage': 'en',
                'transcriptLanguages': {'en': 'English'},
                'transcriptTranslationUrl': video_utils.set_query_parameter(
Alexander Kryklia committed
1595 1596 1597 1598
                    self.item_descriptor.xmodule_runtime.handler_url(
                        self.item_descriptor, 'transcript', 'translation/__lang__'
                    ).rstrip('/?'), 'is_bumper', 1
                ),
1599
                'transcriptAvailableTranslationsUrl': video_utils.set_query_parameter(
Alexander Kryklia committed
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
                    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({
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
                '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,
                'poster': None,
                '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,
                'ytApiUrl': 'https://www.youtube.com/iframe_api',
                'ytMetadataUrl': 'https://www.googleapis.com/youtube/v3/videos/',
                'ytKey': None,
                'transcriptTranslationUrl': self.item_descriptor.xmodule_runtime.handler_url(
Alexander Kryklia committed
1632 1633
                    self.item_descriptor, 'transcript', 'translation/__lang__'
                ).rstrip('/?'),
1634
                'transcriptAvailableTranslationsUrl': self.item_descriptor.xmodule_runtime.handler_url(
Alexander Kryklia committed
1635 1636
                    self.item_descriptor, 'transcript', 'available_translations'
                ).rstrip('/?'),
1637 1638
                'autohideHtml5': False,
                'recordedYoutubeIsAvailable': True,
Alexander Kryklia committed
1639 1640
            })),
            'track': None,
1641
            'transcript_download_format': u'srt',
Alexander Kryklia committed
1642 1643 1644 1645 1646
            'transcript_download_formats_list': [
                {'display_name': 'SubRip (.srt) file', 'value': 'srt'},
                {'display_name': 'Text (.txt) file', 'value': 'txt'}
            ],
            'poster': json.dumps(OrderedDict({
1647 1648
                'url': 'http://img.youtube.com/vi/ZwkTiUPN0mg/0.jpg',
                'type': 'youtube'
Alexander Kryklia committed
1649 1650 1651 1652 1653
            }))
        }

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