test_transcripts.py 34.9 KB
Newer Older
1 2
"""Tests for items views."""

Ned Batchelder committed
3
import copy
4
import ddt
5
import json
Ned Batchelder committed
6
import os
7 8
import tempfile
import textwrap
Ned Batchelder committed
9
from uuid import uuid4
10

11
from django.conf import settings
12 13
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
14
from mock import patch, Mock
15
from opaque_keys.edx.keys import UsageKey
16

17
from contentstore.tests.utils import CourseTestCase, mock_requests_get
18
from openedx.core.djangoapps.contentserver.caching import del_cached_content
19
from xmodule.contentstore.content import StaticContent
20
from xmodule.contentstore.django import contentstore
21
from xmodule.exceptions import NotFoundError
22
from xmodule.modulestore.django import modulestore
23
from xmodule.video_module import transcripts_utils
24 25 26 27 28

TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex


29
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE)
30
class BaseTranscripts(CourseTestCase):
31 32 33 34 35 36
    """Base test class for transcripts tests."""

    def clear_subs_content(self):
        """Remove, if transcripts content exists."""
        for youtube_id in self.get_youtube_ids().values():
            filename = 'subs_{0}.srt.sjson'.format(youtube_id)
37
            content_location = StaticContent.compute_location(self.course.id, filename)
38 39 40 41 42 43
            try:
                content = contentstore().find(content_location)
                contentstore().delete(content.get_id())
            except NotFoundError:
                pass

44 45 46 47 48 49 50 51 52 53 54 55 56 57
    def save_subs_to_store(self, subs, subs_id):
        """
        Save transcripts into `StaticContent`.
        """
        filedata = json.dumps(subs, indent=2)
        mime_type = 'application/json'
        filename = 'subs_{0}.srt.sjson'.format(subs_id)

        content_location = StaticContent.compute_location(self.course.id, filename)
        content = StaticContent(content_location, filename, mime_type, filedata)
        contentstore().save(content)
        del_cached_content(content_location)
        return content_location

58 59
    def setUp(self):
        """Create initial data."""
60
        super(BaseTranscripts, self).setUp()
61 62 63

        # Add video module
        data = {
64
            'parent_locator': unicode(self.course.location),
65 66 67
            'category': 'video',
            'type': 'video'
        }
68
        resp = self.client.ajax_post('/xblock/', data)
69 70
        self.assertEqual(resp.status_code, 200)

71 72
        self.video_usage_key = self._get_usage_key(resp)
        self.item = modulestore().get_item(self.video_usage_key)
73 74
        # hI10vDNYz4M - valid Youtube ID with transcripts.
        # JMD_ifUUfsU, AKqURZnYqpk, DYpADpL7jAY - valid Youtube IDs without transcripts.
75
        self.item.data = '<video youtube="0.75:JMD_ifUUfsU,1.0:hI10vDNYz4M,1.25:AKqURZnYqpk,1.50:DYpADpL7jAY" />'
76
        modulestore().update_item(self.item, self.user.id)
77

78
        self.item = modulestore().get_item(self.video_usage_key)
79 80 81
        # Remove all transcripts for current module.
        self.clear_subs_content()

82 83 84 85
    def _get_usage_key(self, resp):
        """ Returns the usage key from the response returned by a create operation. """
        usage_key_string = json.loads(resp.content).get('locator')
        return UsageKey.from_string(usage_key_string)
86

87 88
    def get_youtube_ids(self):
        """Return youtube speeds and ids."""
89
        item = modulestore().get_item(self.video_usage_key)
90 91 92 93 94 95 96 97 98

        return {
            0.75: item.youtube_id_0_75,
            1: item.youtube_id_1_0,
            1.25: item.youtube_id_1_25,
            1.5: item.youtube_id_1_5
        }


99
class TestUploadTranscripts(BaseTranscripts):
100 101 102
    """
    Tests for '/transcripts/upload' url.
    """
103 104
    def setUp(self):
        """Create initial data."""
105
        super(TestUploadTranscripts, self).setUp()
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

        self.good_srt_file = tempfile.NamedTemporaryFile(suffix='.srt')
        self.good_srt_file.write(textwrap.dedent("""
            1
            00:00:10,500 --> 00:00:13,000
            Elephant's Dream

            2
            00:00:15,000 --> 00:00:18,000
            At the left we can see...
        """))
        self.good_srt_file.seek(0)

        self.bad_data_srt_file = tempfile.NamedTemporaryFile(suffix='.srt')
        self.bad_data_srt_file.write('Some BAD data')
        self.bad_data_srt_file.seek(0)

        self.bad_name_srt_file = tempfile.NamedTemporaryFile(suffix='.BAD')
        self.bad_name_srt_file.write(textwrap.dedent("""
            1
            00:00:10,500 --> 00:00:13,000
            Elephant's Dream

            2
            00:00:15,000 --> 00:00:18,000
            At the left we can see...
        """))
        self.bad_name_srt_file.seek(0)

135 136
        self.ufeff_srt_file = tempfile.NamedTemporaryFile(suffix='.srt')

137
    def test_success_video_module_source_subs_uploading(self):
138
        self.item.data = textwrap.dedent("""
139 140 141 142 143 144
            <video youtube="">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </video>
        """)
145
        modulestore().update_item(self.item, self.user.id)
146 147 148 149

        link = reverse('upload_transcripts')
        filename = os.path.splitext(os.path.basename(self.good_srt_file.name))[0]
        resp = self.client.post(link, {
150
            'locator': self.video_usage_key,
151
            'transcript-file': self.good_srt_file,
152 153 154 155 156 157 158 159 160
            'video_list': json.dumps([{
                'type': 'html5',
                'video': filename,
                'mode': 'mp4',
            }])
        })
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.content).get('status'), 'Success')

161
        item = modulestore().get_item(self.video_usage_key)
162 163 164
        self.assertEqual(item.sub, filename)

        content_location = StaticContent.compute_location(
165
            self.course.id, 'subs_{0}.srt.sjson'.format(filename))
166 167 168 169
        self.assertTrue(contentstore().find(content_location))

    def test_fail_data_without_id(self):
        link = reverse('upload_transcripts')
170
        resp = self.client.post(link, {'transcript-file': self.good_srt_file})
171
        self.assertEqual(resp.status_code, 400)
172
        self.assertEqual(json.loads(resp.content).get('status'), 'POST data without "locator" form data.')
173 174 175

    def test_fail_data_without_file(self):
        link = reverse('upload_transcripts')
176
        resp = self.client.post(link, {'locator': self.video_usage_key})
177 178 179
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(json.loads(resp.content).get('status'), 'POST data without "file" form data.')

180
    def test_fail_data_with_bad_locator(self):
181 182 183 184
        # Test for raising `InvalidLocationError` exception.
        link = reverse('upload_transcripts')
        filename = os.path.splitext(os.path.basename(self.good_srt_file.name))[0]
        resp = self.client.post(link, {
185
            'locator': 'BAD_LOCATOR',
186
            'transcript-file': self.good_srt_file,
187 188 189 190 191 192 193
            'video_list': json.dumps([{
                'type': 'html5',
                'video': filename,
                'mode': 'mp4',
            }])
        })
        self.assertEqual(resp.status_code, 400)
194
        self.assertEqual(json.loads(resp.content).get('status'), "Can't find item by locator.")
195 196 197 198 199

        # Test for raising `ItemNotFoundError` exception.
        link = reverse('upload_transcripts')
        filename = os.path.splitext(os.path.basename(self.good_srt_file.name))[0]
        resp = self.client.post(link, {
200
            'locator': '{0}_{1}'.format(self.video_usage_key, 'BAD_LOCATOR'),
201
            'transcript-file': self.good_srt_file,
202 203 204 205 206 207 208
            'video_list': json.dumps([{
                'type': 'html5',
                'video': filename,
                'mode': 'mp4',
            }])
        })
        self.assertEqual(resp.status_code, 400)
209
        self.assertEqual(json.loads(resp.content).get('status'), "Can't find item by locator.")
210 211 212 213

    def test_fail_for_non_video_module(self):
        # non_video module: setup
        data = {
214
            'parent_locator': unicode(self.course.location),
215 216 217
            'category': 'non_video',
            'type': 'non_video'
        }
218 219 220
        resp = self.client.ajax_post('/xblock/', data)
        usage_key = self._get_usage_key(resp)
        item = modulestore().get_item(usage_key)
221
        item.data = '<non_video youtube="0.75:JMD_ifUUfsU,1.0:hI10vDNYz4M" />'
222
        modulestore().update_item(item, self.user.id)
223 224 225 226 227 228

        # non_video module: testing

        link = reverse('upload_transcripts')
        filename = os.path.splitext(os.path.basename(self.good_srt_file.name))[0]
        resp = self.client.post(link, {
229
            'locator': unicode(usage_key),
230
            'transcript-file': self.good_srt_file,
231 232 233 234 235 236 237 238 239 240
            'video_list': json.dumps([{
                'type': 'html5',
                'video': filename,
                'mode': 'mp4',
            }])
        })
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(json.loads(resp.content).get('status'), 'Transcripts are supported only for "video" modules.')

    def test_fail_bad_xml(self):
241
        self.item.data = '<<<video youtube="0.75:JMD_ifUUfsU,1.25:AKqURZnYqpk,1.50:DYpADpL7jAY" />'
242
        modulestore().update_item(self.item, self.user.id)
243 244 245 246

        link = reverse('upload_transcripts')
        filename = os.path.splitext(os.path.basename(self.good_srt_file.name))[0]
        resp = self.client.post(link, {
247
            'locator': unicode(self.video_usage_key),
248
            'transcript-file': self.good_srt_file,
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
            'video_list': json.dumps([{
                'type': 'html5',
                'video': filename,
                'mode': 'mp4',
            }])
        })

        self.assertEqual(resp.status_code, 400)
        # incorrect xml produces incorrect item category error
        self.assertEqual(json.loads(resp.content).get('status'), 'Transcripts are supported only for "video" modules.')

    def test_fail_bad_data_srt_file(self):
        link = reverse('upload_transcripts')
        filename = os.path.splitext(os.path.basename(self.bad_data_srt_file.name))[0]
        resp = self.client.post(link, {
264
            'locator': unicode(self.video_usage_key),
265
            'transcript-file': self.bad_data_srt_file,
266 267 268 269 270 271 272 273 274 275 276 277 278
            'video_list': json.dumps([{
                'type': 'html5',
                'video': filename,
                'mode': 'mp4',
            }])
        })
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(json.loads(resp.content).get('status'), 'Something wrong with SubRip transcripts file during parsing.')

    def test_fail_bad_name_srt_file(self):
        link = reverse('upload_transcripts')
        filename = os.path.splitext(os.path.basename(self.bad_name_srt_file.name))[0]
        resp = self.client.post(link, {
279
            'locator': unicode(self.video_usage_key),
280
            'transcript-file': self.bad_name_srt_file,
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
            'video_list': json.dumps([{
                'type': 'html5',
                'video': filename,
                'mode': 'mp4',
            }])
        })
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(json.loads(resp.content).get('status'), 'We support only SubRip (*.srt) transcripts format.')

    def test_undefined_file_extension(self):
        srt_file = tempfile.NamedTemporaryFile(suffix='')
        srt_file.write(textwrap.dedent("""
            1
            00:00:10,500 --> 00:00:13,000
            Elephant's Dream

            2
            00:00:15,000 --> 00:00:18,000
            At the left we can see...
        """))
        srt_file.seek(0)

        link = reverse('upload_transcripts')
        filename = os.path.splitext(os.path.basename(srt_file.name))[0]
        resp = self.client.post(link, {
306
            'locator': self.video_usage_key,
307
            'transcript-file': srt_file,
308 309 310 311 312 313 314 315 316
            'video_list': json.dumps([{
                'type': 'html5',
                'video': filename,
                'mode': 'mp4',
            }])
        })
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(json.loads(resp.content).get('status'), 'Undefined file extension.')

317 318 319 320
    def test_subs_uploading_with_byte_order_mark(self):
        """
        Test uploading subs containing BOM(Byte Order Mark), e.g. U+FEFF
        """
321
        filedata = textwrap.dedent("""
322 323 324 325 326 327 328 329 330 331
            1
            00:00:10,500 --> 00:00:13,000
            Test ufeff characters

            2
            00:00:15,000 --> 00:00:18,000
            At the left we can see...
        """).encode('utf-8-sig')

        # Verify that ufeff character is in filedata.
332 333
        self.assertIn("ufeff", filedata)
        self.ufeff_srt_file.write(filedata)
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        self.ufeff_srt_file.seek(0)

        link = reverse('upload_transcripts')
        filename = os.path.splitext(os.path.basename(self.ufeff_srt_file.name))[0]
        resp = self.client.post(link, {
            'locator': self.video_usage_key,
            'transcript-file': self.ufeff_srt_file,
            'video_list': json.dumps([{
                'type': 'html5',
                'video': filename,
                'mode': 'mp4',
            }])
        })
        self.assertEqual(resp.status_code, 200)

        content_location = StaticContent.compute_location(
            self.course.id, 'subs_{0}.srt.sjson'.format(filename))
        self.assertTrue(contentstore().find(content_location))

        subs_text = json.loads(contentstore().find(content_location).data).get('text')
        self.assertIn("Test ufeff characters", subs_text)

356
    def tearDown(self):
357
        super(TestUploadTranscripts, self).tearDown()
358 359 360 361

        self.good_srt_file.close()
        self.bad_data_srt_file.close()
        self.bad_name_srt_file.close()
362
        self.ufeff_srt_file.close()
363 364


365
class TestDownloadTranscripts(BaseTranscripts):
366 367 368
    """
    Tests for '/transcripts/download' url.
    """
369
    def test_success_download_youtube(self):
370
        self.item.data = '<video youtube="1:JMD_ifUUfsU" />'
371
        modulestore().update_item(self.item, self.user.id)
372 373 374 375 376 377 378 379 380 381 382 383 384

        subs = {
            'start': [100, 200, 240],
            'end': [200, 240, 380],
            'text': [
                'subs #1',
                'subs #2',
                'subs #3'
            ]
        }
        self.save_subs_to_store(subs, 'JMD_ifUUfsU')

        link = reverse('download_transcripts')
385
        resp = self.client.get(link, {'locator': self.video_usage_key, 'subs_id': "JMD_ifUUfsU"})
386 387 388 389 390
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.content, """0\n00:00:00,100 --> 00:00:00,200\nsubs #1\n\n1\n00:00:00,200 --> 00:00:00,240\nsubs #2\n\n2\n00:00:00,240 --> 00:00:00,380\nsubs #3\n\n""")

    def test_success_download_nonyoutube(self):
        subs_id = str(uuid4())
391
        self.item.data = textwrap.dedent("""
392 393 394 395 396 397
            <video youtube="" sub="{}">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </video>
        """.format(subs_id))
398
        modulestore().update_item(self.item, self.user.id)
399 400 401 402 403 404 405 406 407 408 409 410 411

        subs = {
            'start': [100, 200, 240],
            'end': [200, 240, 380],
            'text': [
                'subs #1',
                'subs #2',
                'subs #3'
            ]
        }
        self.save_subs_to_store(subs, subs_id)

        link = reverse('download_transcripts')
412
        resp = self.client.get(link, {'locator': self.video_usage_key, 'subs_id': subs_id})
413 414 415 416 417 418 419 420 421 422
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
            resp.content,
            '0\n00:00:00,100 --> 00:00:00,200\nsubs #1\n\n1\n00:00:00,200 --> '
            '00:00:00,240\nsubs #2\n\n2\n00:00:00,240 --> 00:00:00,380\nsubs #3\n\n'
        )
        transcripts_utils.remove_subs_from_store(subs_id, self.item)

    def test_fail_data_without_file(self):
        link = reverse('download_transcripts')
423
        resp = self.client.get(link, {'locator': ''})
424 425 426 427 428
        self.assertEqual(resp.status_code, 404)

        resp = self.client.get(link, {})
        self.assertEqual(resp.status_code, 404)

429
    def test_fail_data_with_bad_locator(self):
430 431
        # Test for raising `InvalidLocationError` exception.
        link = reverse('download_transcripts')
432
        resp = self.client.get(link, {'locator': 'BAD_LOCATOR'})
433 434 435 436
        self.assertEqual(resp.status_code, 404)

        # Test for raising `ItemNotFoundError` exception.
        link = reverse('download_transcripts')
437
        resp = self.client.get(link, {'locator': '{0}_{1}'.format(self.video_usage_key, 'BAD_LOCATOR')})
438 439 440 441 442
        self.assertEqual(resp.status_code, 404)

    def test_fail_for_non_video_module(self):
        # Video module: setup
        data = {
443
            'parent_locator': unicode(self.course.location),
444 445 446
            'category': 'videoalpha',
            'type': 'videoalpha'
        }
447 448
        resp = self.client.ajax_post('/xblock/', data)
        usage_key = self._get_usage_key(resp)
449
        subs_id = str(uuid4())
450
        item = modulestore().get_item(usage_key)
451
        item.data = textwrap.dedent("""
452 453 454 455 456 457
            <videoalpha youtube="" sub="{}">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </videoalpha>
        """.format(subs_id))
458
        modulestore().update_item(item, self.user.id)
459 460 461 462 463 464 465 466 467 468 469 470 471

        subs = {
            'start': [100, 200, 240],
            'end': [200, 240, 380],
            'text': [
                'subs #1',
                'subs #2',
                'subs #3'
            ]
        }
        self.save_subs_to_store(subs, subs_id)

        link = reverse('download_transcripts')
472
        resp = self.client.get(link, {'locator': unicode(usage_key)})
473 474 475
        self.assertEqual(resp.status_code, 404)

    def test_fail_nonyoutube_subs_dont_exist(self):
476
        self.item.data = textwrap.dedent("""
477 478 479 480 481 482
            <video youtube="" sub="UNDEFINED">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </video>
        """)
483
        modulestore().update_item(self.item, self.user.id)
484 485

        link = reverse('download_transcripts')
486
        resp = self.client.get(link, {'locator': self.video_usage_key})
487 488 489
        self.assertEqual(resp.status_code, 404)

    def test_empty_youtube_attr_and_sub_attr(self):
490
        self.item.data = textwrap.dedent("""
491 492 493 494 495 496
            <video youtube="">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </video>
        """)
497
        modulestore().update_item(self.item, self.user.id)
498 499

        link = reverse('download_transcripts')
500
        resp = self.client.get(link, {'locator': self.video_usage_key})
501 502 503 504 505

        self.assertEqual(resp.status_code, 404)

    def test_fail_bad_sjson_subs(self):
        subs_id = str(uuid4())
506
        self.item.data = textwrap.dedent("""
507 508 509 510 511 512
            <video youtube="" sub="{}">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </video>
        """.format(subs_id))
513
        modulestore().update_item(self.item, self.user.id)
514 515 516 517 518 519 520 521 522 523 524

        subs = {
            'start': [100, 200, 240],
            'end': [200, 240, 380],
            'text': [
                'subs #1'
            ]
        }
        self.save_subs_to_store(subs, 'JMD_ifUUfsU')

        link = reverse('download_transcripts')
525
        resp = self.client.get(link, {'locator': self.video_usage_key})
526 527 528

        self.assertEqual(resp.status_code, 404)

529 530 531 532 533 534 535 536 537 538 539 540 541 542
    @patch('xmodule.video_module.transcripts_utils.VideoTranscriptEnabledFlag.feature_enabled', Mock(return_value=True))
    @patch('xmodule.video_module.transcripts_utils.edxval_api.get_video_transcript_data')
    def test_download_fallback_transcript(self, mock_get_video_transcript_data):
        """
        Verify that the val transcript is returned if its not found in content-store.
        """
        mock_get_video_transcript_data.return_value = {
            'content': json.dumps({
                "start": [10],
                "end": [100],
                "text": ["Hi, welcome to Edx."],
            }),
            'file_name': 'edx.sjson'
        }
543

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
        self.item.data = textwrap.dedent("""
            <video youtube="" sub="">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </video>
        """)
        modulestore().update_item(self.item, self.user.id)

        download_transcripts_url = reverse('download_transcripts')
        response = self.client.get(download_transcripts_url, {'locator': self.video_usage_key})

        # Expected response
        expected_content = u'0\n00:00:00,010 --> 00:00:00,100\nHi, welcome to Edx.\n\n'
        expected_headers = {
            'content-disposition': 'attachment; filename="edx.srt"',
            'content-type': 'application/x-subrip; charset=utf-8'
        }

        # Assert the actual response
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, expected_content)
        for attribute, value in expected_headers.iteritems():
            self.assertEqual(response.get(attribute), value)

    @patch(
        'xmodule.video_module.transcripts_utils.VideoTranscriptEnabledFlag.feature_enabled',
        Mock(return_value=False),
    )
    def test_download_fallback_transcript_feature_disabled(self):
        """
        Verify the transcript download when feature is disabled.
        """
        self.item.data = textwrap.dedent("""
            <video youtube="" sub="">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </video>
        """)
        modulestore().update_item(self.item, self.user.id)

        download_transcripts_url = reverse('download_transcripts')
        response = self.client.get(download_transcripts_url, {'locator': self.video_usage_key})
        # Assert the actual response
        self.assertEqual(response.status_code, 404)


@ddt.ddt
593
class TestCheckTranscripts(BaseTranscripts):
594 595 596
    """
    Tests for '/transcripts/check' url.
    """
597 598
    def test_success_download_nonyoutube(self):
        subs_id = str(uuid4())
599
        self.item.data = textwrap.dedent("""
600 601 602 603 604 605
            <video youtube="" sub="{}">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </video>
        """.format(subs_id))
606
        modulestore().update_item(self.item, self.user.id)
607 608 609 610 611 612 613 614 615 616 617 618 619

        subs = {
            'start': [100, 200, 240],
            'end': [200, 240, 380],
            'text': [
                'subs #1',
                'subs #2',
                'subs #3'
            ]
        }
        self.save_subs_to_store(subs, subs_id)

        data = {
620
            'locator': unicode(self.video_usage_key),
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
            'videos': [{
                'type': 'html5',
                'video': subs_id,
                'mode': 'mp4',
            }]
        }
        link = reverse('check_transcripts')
        resp = self.client.get(link, {'data': json.dumps(data)})
        self.assertEqual(resp.status_code, 200)
        self.assertDictEqual(
            json.loads(resp.content),
            {
                u'status': u'Success',
                u'subs': unicode(subs_id),
                u'youtube_local': False,
                u'is_youtube_mode': False,
                u'youtube_server': False,
                u'command': u'found',
                u'current_item_subs': unicode(subs_id),
                u'youtube_diff': True,
                u'html5_local': [unicode(subs_id)],
                u'html5_equal': False,
            }
        )

        transcripts_utils.remove_subs_from_store(subs_id, self.item)

    def test_check_youtube(self):
649
        self.item.data = '<video youtube="1:JMD_ifUUfsU" />'
650
        modulestore().update_item(self.item, self.user.id)
651 652 653 654 655 656 657 658 659 660 661 662 663

        subs = {
            'start': [100, 200, 240],
            'end': [200, 240, 380],
            'text': [
                'subs #1',
                'subs #2',
                'subs #3'
            ]
        }
        self.save_subs_to_store(subs, 'JMD_ifUUfsU')
        link = reverse('check_transcripts')
        data = {
664
            'locator': unicode(self.video_usage_key),
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
            'videos': [{
                'type': 'youtube',
                'video': 'JMD_ifUUfsU',
                'mode': 'youtube',
            }]
        }
        resp = self.client.get(link, {'data': json.dumps(data)})
        self.assertEqual(resp.status_code, 200)
        self.assertDictEqual(
            json.loads(resp.content),
            {
                u'status': u'Success',
                u'subs': u'JMD_ifUUfsU',
                u'youtube_local': True,
                u'is_youtube_mode': True,
                u'youtube_server': False,
                u'command': u'found',
                u'current_item_subs': None,
                u'youtube_diff': True,
                u'html5_local': [],
                u'html5_equal': False,
            }
        )

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
    @patch('xmodule.video_module.transcripts_utils.requests.get', side_effect=mock_requests_get)
    def test_check_youtube_with_transcript_name(self, mock_get):
        """
        Test that the transcripts are fetched correctly when the the transcript name is set
        """
        self.item.data = '<video youtube="good_id_2" />'
        modulestore().update_item(self.item, self.user.id)

        subs = {
            'start': [100, 200, 240],
            'end': [200, 240, 380],
            'text': [
                'subs #1',
                'subs #2',
                'subs #3'
            ]
        }
        self.save_subs_to_store(subs, 'good_id_2')
        link = reverse('check_transcripts')
        data = {
            'locator': unicode(self.video_usage_key),
            'videos': [{
                'type': 'youtube',
                'video': 'good_id_2',
                'mode': 'youtube',
            }]
        }
        resp = self.client.get(link, {'data': json.dumps(data)})

        mock_get.assert_any_call(
            'http://video.google.com/timedtext',
            params={'lang': 'en', 'v': 'good_id_2', 'name': 'Custom'}
        )

        self.assertEqual(resp.status_code, 200)

        self.assertDictEqual(
            json.loads(resp.content),
            {
                u'status': u'Success',
                u'subs': u'good_id_2',
                u'youtube_local': True,
                u'is_youtube_mode': True,
                u'youtube_server': True,
                u'command': u'replace',
                u'current_item_subs': None,
                u'youtube_diff': True,
                u'html5_local': [],
                u'html5_equal': False,
            }
        )

741 742 743
    def test_fail_data_without_id(self):
        link = reverse('check_transcripts')
        data = {
744
            'locator': '',
745 746 747 748 749 750 751 752
            'videos': [{
                'type': '',
                'video': '',
                'mode': '',
            }]
        }
        resp = self.client.get(link, {'data': json.dumps(data)})
        self.assertEqual(resp.status_code, 400)
753
        self.assertEqual(json.loads(resp.content).get('status'), "Can't find item by locator.")
754

755
    def test_fail_data_with_bad_locator(self):
756 757 758
        # Test for raising `InvalidLocationError` exception.
        link = reverse('check_transcripts')
        data = {
759
            'locator': '',
760 761 762 763 764 765 766 767
            'videos': [{
                'type': '',
                'video': '',
                'mode': '',
            }]
        }
        resp = self.client.get(link, {'data': json.dumps(data)})
        self.assertEqual(resp.status_code, 400)
768
        self.assertEqual(json.loads(resp.content).get('status'), "Can't find item by locator.")
769 770 771

        # Test for raising `ItemNotFoundError` exception.
        data = {
772
            'locator': '{0}_{1}'.format(self.video_usage_key, 'BAD_LOCATOR'),
773 774 775 776 777 778 779 780
            'videos': [{
                'type': '',
                'video': '',
                'mode': '',
            }]
        }
        resp = self.client.get(link, {'data': json.dumps(data)})
        self.assertEqual(resp.status_code, 400)
781
        self.assertEqual(json.loads(resp.content).get('status'), "Can't find item by locator.")
782 783 784 785

    def test_fail_for_non_video_module(self):
        # Not video module: setup
        data = {
786
            'parent_locator': unicode(self.course.location),
787 788 789
            'category': 'not_video',
            'type': 'not_video'
        }
790 791
        resp = self.client.ajax_post('/xblock/', data)
        usage_key = self._get_usage_key(resp)
792
        subs_id = str(uuid4())
793
        item = modulestore().get_item(usage_key)
794
        item.data = textwrap.dedent("""
795 796 797 798 799 800
            <not_video youtube="" sub="{}">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </videoalpha>
        """.format(subs_id))
801
        modulestore().update_item(item, self.user.id)
802 803 804 805 806 807 808 809 810 811 812 813 814

        subs = {
            'start': [100, 200, 240],
            'end': [200, 240, 380],
            'text': [
                'subs #1',
                'subs #2',
                'subs #3'
            ]
        }
        self.save_subs_to_store(subs, subs_id)

        data = {
815
            'locator': unicode(usage_key),
816 817 818 819 820 821 822 823 824 825
            'videos': [{
                'type': '',
                'video': '',
                'mode': '',
            }]
        }
        link = reverse('check_transcripts')
        resp = self.client.get(link, {'data': json.dumps(data)})
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(json.loads(resp.content).get('status'), 'Transcripts are supported only for "video" modules.')
826

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    @ddt.data(
        (True, 'found'),
        (False, 'not_found')
    )
    @ddt.unpack
    @patch('xmodule.video_module.transcripts_utils.VideoTranscriptEnabledFlag.feature_enabled')
    @patch('xmodule.video_module.transcripts_utils.edxval_api.get_video_transcript_data', Mock(return_value=True))
    def test_command_for_fallback_transcript(self, feature_enabled, expected_command, video_transcript_feature):
        """
        Verify the command if a transcript is not found in content-store but
        its there in edx-val.
        """
        video_transcript_feature.return_value = feature_enabled
        self.item.data = textwrap.dedent("""
            <video youtube="" sub="">
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm"/>
                <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv"/>
            </video>
        """)
        modulestore().update_item(self.item, self.user.id)

        # Make request to check transcript view
        data = {
            'locator': unicode(self.video_usage_key),
            'videos': [{
                'type': 'html5',
                'video': "",
                'mode': 'mp4',
            }]
        }
        check_transcripts_url = reverse('check_transcripts')
        response = self.client.get(check_transcripts_url, {'data': json.dumps(data)})

        # Assert the response
        self.assertEqual(response.status_code, 200)
        self.assertDictEqual(
            json.loads(response.content),
            {
                u'status': u'Success',
                u'subs': u'',
                u'youtube_local': False,
                u'is_youtube_mode': False,
                u'youtube_server': False,
                u'command': expected_command,
                u'current_item_subs': None,
                u'youtube_diff': True,
                u'html5_local': [],
                u'html5_equal': False,
            }
        )

879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937

class TestSaveTranscripts(BaseTranscripts):
    """
    Tests for '/transcripts/save' url.
    """
    def assert_current_subs(self, expected_subs):
        """
        Asserts the current subtitles set on the video module.

        Arguments:
            expected_subs (String): Expected current subtitles for video.
        """
        item = modulestore().get_item(self.video_usage_key)
        self.assertEqual(item.sub, expected_subs)

    def test_prioritize_youtube_sub_on_save(self):
        """
        Test that the '/transcripts/save' endpoint prioritises youtube subtitles over html5 ones
        while deciding the current subs for video module.
        """
        # Update video module to contain 1 youtube and 2 html5 sources.
        youtube_id = str(uuid4())
        self.item.data = textwrap.dedent(
            """
            <video youtube="1:{youtube_id}" sub="">
                <source src="http://www.testvid.org/html5/videos/testvid.mp4"/>
                <source src="http://www.testvid2.org/html5/videos/testvid2.webm"/>
            </video>
            """.format(youtube_id=youtube_id)
        )
        modulestore().update_item(self.item, self.user.id)
        self.assert_current_subs(expected_subs='')

        # Save new subs in the content store.
        subs = {
            'start': [100, 200, 240],
            'end': [200, 240, 380],
            'text': [
                'subs #1',
                'subs #2',
                'subs #3'
            ]
        }
        self.save_subs_to_store(subs, youtube_id)

        # Now, make request to /transcripts/save endpoint with new subs.
        data = {
            'locator': unicode(self.video_usage_key),
            'metadata': {
                'sub': youtube_id
            }
        }
        resp = self.client.get(reverse('save_transcripts'), {'data': json.dumps(data)})
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.content), {"status": "Success"})

        # Now check item.sub, it should be same as youtube id because /transcripts/save prioritize
        # youtube subs over html5 ones.
        self.assert_current_subs(expected_subs=youtube_id)