test_video_handlers.py 35 KB
Newer Older
1 2 3 4
# -*- coding: utf-8 -*-
"""Video xmodule tests in mongo."""

import os
Alexander Kryklia committed
5
import freezegun
6 7 8
import tempfile
import textwrap
import json
Alexander Kryklia committed
9 10 11 12
import ddt

from nose.plugins.attrib import attr
from datetime import timedelta, datetime
13
from webob import Request
Alexander Kryklia committed
14
from mock import MagicMock, Mock, patch
15 16 17

from xmodule.contentstore.content import StaticContent
from xmodule.contentstore.django import contentstore
18
from xmodule.modulestore.django import modulestore
19
from xmodule.modulestore import ModuleStoreEnum
20
from xmodule.x_module import STUDENT_VIEW
21 22 23 24 25
from . import BaseTestXmodule
from .test_video_xml import SOURCE_XML
from cache_toolbox.core import del_cached_content
from xmodule.exceptions import NotFoundError

26 27 28 29
from xmodule.video_module.transcripts_utils import (
    TranscriptException,
    TranscriptsGenerationException,
)
30

Alexander Kryklia committed
31 32 33

TRANSCRIPT = {"start": [10], "end": [100], "text": ["Hi, welcome to Edx."]}
BUMPER_TRANSCRIPT = {"start": [1], "end": [10], "text": ["A bumper"]}
34
SRT_content = textwrap.dedent("""
35 36 37 38
        0
        00:00:00,12 --> 00:00:00,100
        Привіт, edX вітає вас.
    """)
39 40 41 42 43 44 45


def _create_srt_file(content=None):
    """
    Create srt file in filesystem.
    """
    content = content or SRT_content
46
    srt_file = tempfile.NamedTemporaryFile(suffix=".srt")
47
    srt_file.content_type = 'application/x-subrip; charset=utf-8'
48 49 50 51 52
    srt_file.write(content)
    srt_file.seek(0)
    return srt_file


53 54 55 56 57
def _check_asset(location, asset_name):
    """
    Check that asset with asset_name exists in assets.
    """
    content_location = StaticContent.compute_location(
58
        location.course_key, asset_name
59 60 61 62 63 64 65 66
    )
    try:
        contentstore().find(content_location)
    except NotFoundError:
        return False
    else:
        return True

67

68 69 70 71 72 73
def _clear_assets(location):
    """
    Clear all assets for location.
    """
    store = contentstore()

74
    assets, __ = store.get_all_content_for_course(location.course_key)
75
    for asset in assets:
76
        asset_location = asset['asset_key']
77
        del_cached_content(asset_location)
Don Mitchell committed
78
        store.delete(asset_location)
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104


def _get_subs_id(filename):
    basename = os.path.splitext(os.path.basename(filename))[0]
    return basename.replace('subs_', '').replace('.srt', '')


def _create_file(content=''):
    """
    Create temporary subs_somevalue.srt.sjson file.
    """
    sjson_file = tempfile.NamedTemporaryFile(prefix="subs_", suffix=".srt.sjson")
    sjson_file.content_type = 'application/json'
    sjson_file.write(textwrap.dedent(content))
    sjson_file.seek(0)
    return sjson_file


def _upload_sjson_file(subs_file, location, default_filename='subs_{}.srt.sjson'):
    filename = default_filename.format(_get_subs_id(subs_file.name))
    _upload_file(subs_file, location, filename)


def _upload_file(subs_file, location, filename):
    mime_type = subs_file.content_type
    content_location = StaticContent.compute_location(
105
        location.course_key, filename
106 107 108 109 110 111
    )
    content = StaticContent(content_location, filename, mime_type, subs_file.read())
    contentstore().save(content)
    del_cached_content(content.location)


Alexander Kryklia committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125
def attach_sub(item, filename):
    """
    Attach `en` transcript.
    """
    item.sub = filename


def attach_bumper_transcript(item, filename, lang="en"):
    """
    Attach bumper transcript.
    """
    item.video_bumper["transcripts"][lang] = filename


126
@attr('shard_1')
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
class TestVideo(BaseTestXmodule):
    """Integration tests: web client + mongo."""
    CATEGORY = "video"
    DATA = SOURCE_XML
    METADATA = {}

    def test_handle_ajax_wrong_dispatch(self):
        responses = {
            user.username: self.clients[user.username].post(
                self.get_url('whatever'),
                {},
                HTTP_X_REQUESTED_WITH='XMLHttpRequest')
            for user in self.users
        }

David Baumgold committed
142 143
        status_codes = {response.status_code for response in responses.values()}
        self.assertEqual(status_codes.pop(), 404)
144 145 146 147

    def test_handle_ajax(self):

        data = [
148 149 150 151 152 153
            {u'speed': 2.0},
            {u'saved_video_position': "00:00:10"},
            {u'transcript_language': 'uk'},
            {u'bumper_do_not_show_again': True},
            {u'bumper_last_view_date': True},
            {u'demoo�': 'sample'}
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
        ]
        for sample in data:
            response = self.clients[self.users[0].username].post(
                self.get_url('save_user_state'),
                sample,
                HTTP_X_REQUESTED_WITH='XMLHttpRequest')
            self.assertEqual(response.status_code, 200)

        self.assertEqual(self.item_descriptor.speed, None)
        self.item_descriptor.handle_ajax('save_user_state', {'speed': json.dumps(2.0)})
        self.assertEqual(self.item_descriptor.speed, 2.0)
        self.assertEqual(self.item_descriptor.global_speed, 2.0)

        self.assertEqual(self.item_descriptor.saved_video_position, timedelta(0))
        self.item_descriptor.handle_ajax('save_user_state', {'saved_video_position': "00:00:10"})
        self.assertEqual(self.item_descriptor.saved_video_position, timedelta(0, 10))

        self.assertEqual(self.item_descriptor.transcript_language, 'en')
172
        self.item_descriptor.handle_ajax('save_user_state', {'transcript_language': "uk"})
173 174
        self.assertEqual(self.item_descriptor.transcript_language, 'uk')

Alexander Kryklia committed
175 176 177 178 179 180 181 182 183
        self.assertEqual(self.item_descriptor.bumper_do_not_show_again, False)
        self.item_descriptor.handle_ajax('save_user_state', {'bumper_do_not_show_again': True})
        self.assertEqual(self.item_descriptor.bumper_do_not_show_again, True)

        with freezegun.freeze_time(datetime.now()):
            self.assertEqual(self.item_descriptor.bumper_last_view_date, None)
            self.item_descriptor.handle_ajax('save_user_state', {'bumper_last_view_date': True})
            self.assertEqual(self.item_descriptor.bumper_last_view_date, datetime.utcnow())

184
        response = self.item_descriptor.handle_ajax('save_user_state', {u'demoo�': "sample"})
185 186
        self.assertEqual(json.loads(response)['success'], True)

187 188
    def tearDown(self):
        _clear_assets(self.item_descriptor.location)
189
        super(TestVideo, self).tearDown()
190

191

192
@attr('shard_1')
193 194 195
class TestTranscriptAvailableTranslationsDispatch(TestVideo):
    """
    Test video handler that provide available translations info.
196

197
    Tests for `available_translations` dispatch.
198
    """
Alexander Kryklia committed
199
    srt_file = _create_srt_file()
200 201 202 203 204 205 206 207
    DATA = """
        <video show_captions="true"
        display_name="A Name"
        >
            <source src="example.mp4"/>
            <source src="example.webm"/>
            <transcript language="uk" src="{}"/>
        </video>
Alexander Kryklia committed
208
    """.format(os.path.split(srt_file.name)[1])
209 210 211 212 213 214 215

    MODEL_DATA = {
        'data': DATA
    }

    def setUp(self):
        super(TestTranscriptAvailableTranslationsDispatch, self).setUp()
216
        self.item_descriptor.render(STUDENT_VIEW)
217 218 219 220 221 222 223 224
        self.item = self.item_descriptor.xmodule_runtime.xmodule_instance
        self.subs = {"start": [10], "end": [100], "text": ["Hi, welcome to Edx."]}

    def test_available_translation_en(self):
        good_sjson = _create_file(json.dumps(self.subs))
        _upload_sjson_file(good_sjson, self.item_descriptor.location)
        self.item.sub = _get_subs_id(good_sjson.name)

225
        request = Request.blank('/available_translations')
226 227 228 229
        response = self.item.transcript(request=request, dispatch='available_translations')
        self.assertEqual(json.loads(response.body), ['en'])

    def test_available_translation_non_en(self):
Alexander Kryklia committed
230
        _upload_file(self.srt_file, self.item_descriptor.location, os.path.split(self.srt_file.name)[1])
231

232
        request = Request.blank('/available_translations')
233 234 235 236 237
        response = self.item.transcript(request=request, dispatch='available_translations')
        self.assertEqual(json.loads(response.body), ['uk'])

    def test_multiple_available_translations(self):
        good_sjson = _create_file(json.dumps(self.subs))
238

239 240 241 242
        # Upload english transcript.
        _upload_sjson_file(good_sjson, self.item_descriptor.location)

        # Upload non-english transcript.
Alexander Kryklia committed
243
        _upload_file(self.srt_file, self.item_descriptor.location, os.path.split(self.srt_file.name)[1])
244

245 246 247
        self.item.sub = _get_subs_id(good_sjson.name)

        request = Request.blank('/available_translations')
248 249 250
        response = self.item.transcript(request=request, dispatch='available_translations')
        self.assertEqual(json.loads(response.body), ['en', 'uk'])

251

252
@attr('shard_1')
Alexander Kryklia committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 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 306 307 308 309
@ddt.ddt
class TestTranscriptAvailableTranslationsBumperDispatch(TestVideo):
    """
    Test video handler that provide available translations info.

    Tests for `available_translations_bumper` dispatch.
    """
    srt_file = _create_srt_file()
    DATA = """
        <video show_captions="true"
        display_name="A Name"
        >
            <source src="example.mp4"/>
            <source src="example.webm"/>
            <transcript language="uk" src="{}"/>
        </video>
    """.format(os.path.split(srt_file.name)[1])

    MODEL_DATA = {
        'data': DATA
    }

    def setUp(self):
        super(TestTranscriptAvailableTranslationsBumperDispatch, self).setUp()
        self.item_descriptor.render(STUDENT_VIEW)
        self.item = self.item_descriptor.xmodule_runtime.xmodule_instance
        self.dispatch = "available_translations/?is_bumper=1"
        self.item.video_bumper = {"transcripts": {"en": ""}}

    @ddt.data("en", "uk")
    def test_available_translation_en_and_non_en(self, lang):
        filename = os.path.split(self.srt_file.name)[1]
        _upload_file(self.srt_file, self.item_descriptor.location, filename)
        self.item.video_bumper["transcripts"][lang] = filename

        request = Request.blank('/' + self.dispatch)
        response = self.item.transcript(request=request, dispatch=self.dispatch)
        self.assertEqual(json.loads(response.body), [lang])

    def test_multiple_available_translations(self):
        en_translation = _create_srt_file()
        en_translation_filename = os.path.split(en_translation.name)[1]
        uk_translation_filename = os.path.split(self.srt_file.name)[1]
        # Upload english transcript.
        _upload_file(en_translation, self.item_descriptor.location, en_translation_filename)

        # Upload non-english transcript.
        _upload_file(self.srt_file, self.item_descriptor.location, uk_translation_filename)

        self.item.video_bumper["transcripts"]["en"] = en_translation_filename
        self.item.video_bumper["transcripts"]["uk"] = uk_translation_filename

        request = Request.blank('/' + self.dispatch)
        response = self.item.transcript(request=request, dispatch=self.dispatch)
        self.assertEqual(json.loads(response.body), ['en', 'uk'])


310 311 312 313 314
class TestTranscriptDownloadDispatch(TestVideo):
    """
    Test video handler that provide translation transcripts.

    Tests for `download` dispatch.
315 316 317 318 319
    """

    DATA = """
        <video show_captions="true"
        display_name="A Name"
320
        sub='OEoXaMPEzfM'
321 322 323 324
        >
            <source src="example.mp4"/>
            <source src="example.webm"/>
        </video>
325
    """
326 327 328 329 330 331

    MODEL_DATA = {
        'data': DATA
    }

    def setUp(self):
332
        super(TestTranscriptDownloadDispatch, self).setUp()
333
        self.item_descriptor.render(STUDENT_VIEW)
334 335 336
        self.item = self.item_descriptor.xmodule_runtime.xmodule_instance

    def test_download_transcript_not_exist(self):
337
        request = Request.blank('/download')
338 339 340
        response = self.item.transcript(request=request, dispatch='download')
        self.assertEqual(response.status, '404 Not Found')

341
    @patch('xmodule.video_module.VideoModule.get_transcript', return_value=('Subs!', 'test_filename.srt', 'application/x-subrip; charset=utf-8'))
342
    def test_download_srt_exist(self, __):
343
        request = Request.blank('/download')
344 345
        response = self.item.transcript(request=request, dispatch='download')
        self.assertEqual(response.body, 'Subs!')
346 347
        self.assertEqual(response.headers['Content-Type'], 'application/x-subrip; charset=utf-8')
        self.assertEqual(response.headers['Content-Language'], 'en')
348

349
    @patch('xmodule.video_module.VideoModule.get_transcript', return_value=('Subs!', 'txt', 'text/plain; charset=utf-8'))
350 351
    def test_download_txt_exist(self, __):
        self.item.transcript_format = 'txt'
352
        request = Request.blank('/download')
353 354
        response = self.item.transcript(request=request, dispatch='download')
        self.assertEqual(response.body, 'Subs!')
355 356
        self.assertEqual(response.headers['Content-Type'], 'text/plain; charset=utf-8')
        self.assertEqual(response.headers['Content-Language'], 'en')
357

358
    def test_download_en_no_sub(self):
359
        request = Request.blank('/download')
360 361
        response = self.item.transcript(request=request, dispatch='download')
        self.assertEqual(response.status, '404 Not Found')
Alexander Kryklia committed
362
        transcripts = self.item.get_transcripts_info()
363
        with self.assertRaises(NotFoundError):
Alexander Kryklia committed
364
            self.item.get_transcript(transcripts)
365

366 367 368 369 370 371 372 373 374
    @patch('xmodule.video_module.VideoModule.get_transcript', return_value=('Subs!', u"塞.srt", 'application/x-subrip; charset=utf-8'))
    def test_download_non_en_non_ascii_filename(self, __):
        request = Request.blank('/download')
        response = self.item.transcript(request=request, dispatch='download')
        self.assertEqual(response.body, 'Subs!')
        self.assertEqual(response.headers['Content-Type'], 'application/x-subrip; charset=utf-8')
        self.assertEqual(response.headers['Content-Disposition'], 'attachment; filename="塞.srt"')


375
@attr('shard_1')
Alexander Kryklia committed
376
@ddt.ddt
377
class TestTranscriptTranslationGetDispatch(TestVideo):
378 379 380
    """
    Test video handler that provide translation transcripts.

Alexander Kryklia committed
381
    Tests for `translation` and `translation_bumper` dispatches.
382 383
    """

Alexander Kryklia committed
384
    srt_file = _create_srt_file()
385 386 387 388 389 390 391 392
    DATA = """
        <video show_captions="true"
        display_name="A Name"
        >
            <source src="example.mp4"/>
            <source src="example.webm"/>
            <transcript language="uk" src="{}"/>
        </video>
Alexander Kryklia committed
393
    """.format(os.path.split(srt_file.name)[1])
394 395 396 397 398 399

    MODEL_DATA = {
        'data': DATA
    }

    def setUp(self):
400
        super(TestTranscriptTranslationGetDispatch, self).setUp()
401
        self.item_descriptor.render(STUDENT_VIEW)
402
        self.item = self.item_descriptor.xmodule_runtime.xmodule_instance
Alexander Kryklia committed
403
        self.item.video_bumper = {"transcripts": {"en": ""}}
404

Alexander Kryklia committed
405
    @ddt.data(
406
        # No language
Alexander Kryklia committed
407
        ('/translation', 'translation', '400 Bad Request'),
408
        # No videoId - HTML5 video with language that is not in available languages
Alexander Kryklia committed
409
        ('/translation/ru', 'translation/ru', '404 Not Found'),
410
        # Language is not in available languages
Alexander Kryklia committed
411
        ('/translation/ru?videoId=12345', 'translation/ru', '404 Not Found'),
412
        # Youtube_id is invalid or does not exist
Alexander Kryklia committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
        ('/translation/uk?videoId=9855256955511225', 'translation/uk', '404 Not Found'),
        ('/translation?is_bumper=1', 'translation', '400 Bad Request'),
        ('/translation/ru?is_bumper=1', 'translation/ru', '404 Not Found'),
        ('/translation/ru?videoId=12345&is_bumper=1', 'translation/ru', '404 Not Found'),
        ('/translation/uk?videoId=9855256955511225&is_bumper=1', 'translation/uk', '404 Not Found'),
    )
    @ddt.unpack
    def test_translation_fails(self, url, dispatch, status_code):
        request = Request.blank(url)
        response = self.item.transcript(request=request, dispatch=dispatch)
        self.assertEqual(response.status, status_code)

    @ddt.data(
        ('translation/en?videoId={}', 'translation/en', attach_sub),
        ('translation/en?videoId={}&is_bumper=1', 'translation/en', attach_bumper_transcript))
    @ddt.unpack
    def test_translaton_en_youtube_success(self, url, dispatch, attach):
430 431 432 433 434
        subs = {"start": [10], "end": [100], "text": ["Hi, welcome to Edx."]}
        good_sjson = _create_file(json.dumps(subs))
        _upload_sjson_file(good_sjson, self.item_descriptor.location)
        subs_id = _get_subs_id(good_sjson.name)

Alexander Kryklia committed
435 436 437
        attach(self.item, subs_id)
        request = Request.blank(url.format(subs_id))
        response = self.item.transcript(request=request, dispatch=dispatch)
438 439
        self.assertDictEqual(json.loads(response.body), subs)

440
    def test_translation_non_en_youtube_success(self):
441 442 443 444
        subs = {
            u'end': [100],
            u'start': [12],
            u'text': [
445 446 447
                u'\u041f\u0440\u0438\u0432\u0456\u0442, edX \u0432\u0456\u0442\u0430\u0454 \u0432\u0430\u0441.'
            ]
        }
Alexander Kryklia committed
448 449 450
        self.srt_file.seek(0)
        _upload_file(self.srt_file, self.item_descriptor.location, os.path.split(self.srt_file.name)[1])
        subs_id = _get_subs_id(self.srt_file.name)
451 452 453 454

        # youtube 1_0 request, will generate for all speeds for existing ids
        self.item.youtube_id_1_0 = subs_id
        self.item.youtube_id_0_75 = '0_75'
455 456
        request = Request.blank('/translation/uk?videoId={}'.format(subs_id))
        response = self.item.transcript(request=request, dispatch='translation/uk')
457 458 459
        self.assertDictEqual(json.loads(response.body), subs)

        # 0_75 subs are exist
460 461
        request = Request.blank('/translation/uk?videoId={}'.format('0_75'))
        response = self.item.transcript(request=request, dispatch='translation/uk')
462 463 464 465
        calculated_0_75 = {
            u'end': [75],
            u'start': [9],
            u'text': [
David Baumgold committed
466
                u'\u041f\u0440\u0438\u0432\u0456\u0442, edX \u0432\u0456\u0442\u0430\u0454 \u0432\u0430\u0441.'
467 468 469 470 471
            ]
        }
        self.assertDictEqual(json.loads(response.body), calculated_0_75)
        # 1_5 will be generated from 1_0
        self.item.youtube_id_1_5 = '1_5'
472 473
        request = Request.blank('/translation/uk?videoId={}'.format('1_5'))
        response = self.item.transcript(request=request, dispatch='translation/uk')
474 475 476 477
        calculated_1_5 = {
            u'end': [150],
            u'start': [18],
            u'text': [
David Baumgold committed
478
                u'\u041f\u0440\u0438\u0432\u0456\u0442, edX \u0432\u0456\u0442\u0430\u0454 \u0432\u0430\u0441.'
479 480 481 482
            ]
        }
        self.assertDictEqual(json.loads(response.body), calculated_1_5)

Alexander Kryklia committed
483 484 485 486 487 488
    @ddt.data(
        ('translation/en', 'translation/en', attach_sub),
        ('translation/en?is_bumper=1', 'translation/en', attach_bumper_transcript))
    @ddt.unpack
    def test_translaton_en_html5_success(self, url, dispatch, attach):
        good_sjson = _create_file(json.dumps(TRANSCRIPT))
489 490 491
        _upload_sjson_file(good_sjson, self.item_descriptor.location)
        subs_id = _get_subs_id(good_sjson.name)

Alexander Kryklia committed
492 493 494 495
        attach(self.item, subs_id)
        request = Request.blank(url)
        response = self.item.transcript(request=request, dispatch=dispatch)
        self.assertDictEqual(json.loads(response.body), TRANSCRIPT)
496 497 498 499 500 501

    def test_translaton_non_en_html5_success(self):
        subs = {
            u'end': [100],
            u'start': [12],
            u'text': [
David Baumgold committed
502
                u'\u041f\u0440\u0438\u0432\u0456\u0442, edX \u0432\u0456\u0442\u0430\u0454 \u0432\u0430\u0441.'
503 504
            ]
        }
Alexander Kryklia committed
505 506
        self.srt_file.seek(0)
        _upload_file(self.srt_file, self.item_descriptor.location, os.path.split(self.srt_file.name)[1])
507 508 509

        # manually clean youtube_id_1_0, as it has default value
        self.item.youtube_id_1_0 = ""
510 511
        request = Request.blank('/translation/uk')
        response = self.item.transcript(request=request, dispatch='translation/uk')
512 513
        self.assertDictEqual(json.loads(response.body), subs)

Oleg Marshev committed
514
    def test_translation_static_transcript_xml_with_data_dirc(self):
515
        """
Oleg Marshev committed
516 517 518 519
        Test id data_dir is set in XML course.

        Set course data_dir and ensure we get redirected to that path
        if it isn't found in the contentstore.
520
        """
Oleg Marshev committed
521 522 523 524 525
        # Simulate data_dir set in course.
        test_modulestore = MagicMock()
        attrs = {'get_course.return_value': Mock(data_dir='dummy/static', static_asset_path='')}
        test_modulestore.configure_mock(**attrs)
        self.item_descriptor.runtime.modulestore = test_modulestore
526 527 528 529 530 531 532

        # Test youtube style en
        request = Request.blank('/translation/en?videoId=12345')
        response = self.item.transcript(request=request, dispatch='translation/en')
        self.assertEqual(response.status, '307 Temporary Redirect')
        self.assertIn(
            ('Location', '/static/dummy/static/subs_12345.srt.sjson'),
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
            response.headerlist
        )

        # Test HTML5 video style
        self.item.sub = 'OEoXaMPEzfM'
        request = Request.blank('/translation/en')
        response = self.item.transcript(request=request, dispatch='translation/en')
        self.assertEqual(response.status, '307 Temporary Redirect')
        self.assertIn(
            ('Location', '/static/dummy/static/subs_OEoXaMPEzfM.srt.sjson'),
            response.headerlist
        )

        # Test different language to ensure we are just ignoring it since we can't
        # translate with static fallback
        request = Request.blank('/translation/uk')
        response = self.item.transcript(request=request, dispatch='translation/uk')
        self.assertEqual(response.status, '404 Not Found')

Alexander Kryklia committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
    @ddt.data(
        # Test youtube style en
        ('/translation/en?videoId=12345', 'translation/en', '307 Temporary Redirect', '12345'),
        # Test html5 style en
        ('/translation/en', 'translation/en', '307 Temporary Redirect', 'OEoXaMPEzfM', attach_sub),
        # Test different language to ensure we are just ignoring it since we can't
        # translate with static fallback
        ('/translation/uk', 'translation/uk', '404 Not Found'),
        (
            '/translation/en?is_bumper=1', 'translation/en', '307 Temporary Redirect', 'OEoXaMPEzfM',
            attach_bumper_transcript
        ),
        ('/translation/uk?is_bumper=1', 'translation/uk', '404 Not Found'),
    )
    @ddt.unpack
    def test_translation_static_transcript(self, url, dispatch, status_code, sub=None, attach=None):
568
        """
Oleg Marshev committed
569 570
        Set course static_asset_path and ensure we get redirected to that path
        if it isn't found in the contentstore
571
        """
572
        self._set_static_asset_path()
573

Alexander Kryklia committed
574 575 576 577 578 579 580 581 582 583
        if attach:
            attach(self.item, sub)
        request = Request.blank(url)
        response = self.item.transcript(request=request, dispatch=dispatch)
        self.assertEqual(response.status, status_code)
        if sub:
            self.assertIn(
                ('Location', '/static/dummy/static/subs_{}.srt.sjson'.format(sub)),
                response.headerlist
            )
584

585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    @patch('xmodule.video_module.VideoModule.course_id', return_value='not_a_course_locator')
    def test_translation_static_non_course(self, __):
        """
        Test that get_static_transcript short-circuits in the case of a non-CourseLocator.
        This fixes a bug for videos inside of content libraries.
        """
        self._set_static_asset_path()

        # When course_id is not mocked out, these values would result in 307, as tested above.
        request = Request.blank('/translation/en?videoId=12345')
        response = self.item.transcript(request=request, dispatch='translation/en')
        self.assertEqual(response.status, '404 Not Found')

    def _set_static_asset_path(self):
        """ Helper method for setting up the static_asset_path information """
        self.course.static_asset_path = 'dummy/static'
        self.course.save()
        store = modulestore()
        with store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, self.course.id):
            store.update_item(self.course, self.user.id)

606

607
@attr('shard_1')
608 609 610 611 612 613
class TestStudioTranscriptTranslationGetDispatch(TestVideo):
    """
    Test Studio video handler that provide translation transcripts.

    Tests for `translation` dispatch GET HTTP method.
    """
Alexander Kryklia committed
614
    srt_file = _create_srt_file()
615 616 617 618 619 620 621 622 623
    DATA = """
        <video show_captions="true"
        display_name="A Name"
        >
            <source src="example.mp4"/>
            <source src="example.webm"/>
            <transcript language="uk" src="{}"/>
            <transcript language="zh" src="{}"/>
        </video>
Alexander Kryklia committed
624
    """.format(os.path.split(srt_file.name)[1], u"塞.srt".encode('utf8'))
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639

    MODEL_DATA = {'data': DATA}

    def test_translation_fails(self):
        # No language
        request = Request.blank('')
        response = self.item_descriptor.studio_transcript(request=request, dispatch='translation')
        self.assertEqual(response.status, '400 Bad Request')

        # No filename in request.GET
        request = Request.blank('')
        response = self.item_descriptor.studio_transcript(request=request, dispatch='translation/uk')
        self.assertEqual(response.status, '400 Bad Request')

        # Correct case:
Alexander Kryklia committed
640 641 642
        filename = os.path.split(self.srt_file.name)[1]
        _upload_file(self.srt_file, self.item_descriptor.location, filename)
        self.srt_file.seek(0)
643 644
        request = Request.blank(u'translation/uk?filename={}'.format(filename))
        response = self.item_descriptor.studio_transcript(request=request, dispatch='translation/uk')
Alexander Kryklia committed
645
        self.assertEqual(response.body, self.srt_file.read())
646 647 648 649 650 651 652 653
        self.assertEqual(response.headers['Content-Type'], 'application/x-subrip; charset=utf-8')
        self.assertEqual(
            response.headers['Content-Disposition'],
            'attachment; filename="{}"'.format(filename)
        )
        self.assertEqual(response.headers['Content-Language'], 'uk')

        # Non ascii file name download:
Alexander Kryklia committed
654 655 656
        self.srt_file.seek(0)
        _upload_file(self.srt_file, self.item_descriptor.location, u'塞.srt')
        self.srt_file.seek(0)
657 658
        request = Request.blank('translation/zh?filename={}'.format(u'塞.srt'.encode('utf8')))
        response = self.item_descriptor.studio_transcript(request=request, dispatch='translation/zh')
Alexander Kryklia committed
659
        self.assertEqual(response.body, self.srt_file.read())
660 661 662 663 664
        self.assertEqual(response.headers['Content-Type'], 'application/x-subrip; charset=utf-8')
        self.assertEqual(response.headers['Content-Disposition'], 'attachment; filename="塞.srt"')
        self.assertEqual(response.headers['Content-Language'], 'zh')


665
@attr('shard_1')
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
class TestStudioTranscriptTranslationPostDispatch(TestVideo):
    """
    Test Studio video handler that provide translation transcripts.

    Tests for `translation` dispatch with HTTP POST method.
    """
    DATA = """
        <video show_captions="true"
        display_name="A Name"
        >
            <source src="example.mp4"/>
            <source src="example.webm"/>

        </video>
    """

    MODEL_DATA = {
        'data': DATA
    }

    METADATA = {}

    def test_studio_transcript_post(self):
        # Check for exceptons:

        # Language is passed, bad content or filename:

        # should be first, as other tests save transcrips to store.
        request = Request.blank('/translation/uk', POST={'file': ('filename.srt', SRT_content)})
        with patch('xmodule.video_module.video_handlers.save_to_store'):
            with self.assertRaises(TranscriptException):  # transcripts were not saved to store for some reason.
                response = self.item_descriptor.studio_transcript(request=request, dispatch='translation/uk')
        request = Request.blank('/translation/uk', POST={'file': ('filename', 'content')})
        with self.assertRaises(TranscriptsGenerationException):  # Not an srt filename
            self.item_descriptor.studio_transcript(request=request, dispatch='translation/uk')

        request = Request.blank('/translation/uk', POST={'file': ('filename.srt', 'content')})
        with self.assertRaises(TranscriptsGenerationException):  # Content format is not srt.
            response = self.item_descriptor.studio_transcript(request=request, dispatch='translation/uk')

        request = Request.blank('/translation/uk', POST={'file': ('filename.srt', SRT_content.decode('utf8').encode('cp1251'))})
707 708 709 710
        # Non-UTF8 file content encoding.
        response = self.item_descriptor.studio_transcript(request=request, dispatch='translation/uk')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.body, "Invalid encoding type, transcripts should be UTF-8 encoded.")
711 712 713 714

        # No language is passed.
        request = Request.blank('/translation', POST={'file': ('filename', SRT_content)})
        response = self.item_descriptor.studio_transcript(request=request, dispatch='translation')
715
        self.assertEqual(response.status, '400 Bad Request')
716 717 718 719 720 721 722 723 724 725

        # Language, good filename and good content.
        request = Request.blank('/translation/uk', POST={'file': ('filename.srt', SRT_content)})
        response = self.item_descriptor.studio_transcript(request=request, dispatch='translation/uk')
        self.assertEqual(response.status, '201 Created')
        self.assertDictEqual(json.loads(response.body), {'filename': u'filename.srt', 'status': 'Success'})
        self.assertDictEqual(self.item_descriptor.transcripts, {})
        self.assertTrue(_check_asset(self.item_descriptor.location, u'filename.srt'))


726
@attr('shard_1')
727
class TestGetTranscript(TestVideo):
728 729 730
    """
    Make sure that `get_transcript` method works correctly
    """
Alexander Kryklia committed
731
    srt_file = _create_srt_file()
732 733 734 735 736 737
    DATA = """
        <video show_captions="true"
        display_name="A Name"
        >
            <source src="example.mp4"/>
            <source src="example.webm"/>
738
            <transcript language="uk" src="{}"/>
739
            <transcript language="zh" src="{}"/>
740
        </video>
Alexander Kryklia committed
741
    """.format(os.path.split(srt_file.name)[1], u"塞.srt".encode('utf8'))
742

743 744 745 746 747 748
    MODEL_DATA = {
        'data': DATA
    }
    METADATA = {}

    def setUp(self):
749
        super(TestGetTranscript, self).setUp()
750
        self.item_descriptor.render(STUDENT_VIEW)
751 752
        self.item = self.item_descriptor.xmodule_runtime.xmodule_instance

753 754 755 756
    def test_good_transcript(self):
        """
        Test for download 'en' sub with html5 video and self.sub has correct non-empty value.
        """
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
        good_sjson = _create_file(content=textwrap.dedent("""\
                {
                  "start": [
                    270,
                    2720
                  ],
                  "end": [
                    2720,
                    5430
                  ],
                  "text": [
                    "Hi, welcome to Edx.",
                    "Let&#39;s start with what is on your screen right now."
                  ]
                }
            """))

        _upload_sjson_file(good_sjson, self.item.location)
        self.item.sub = _get_subs_id(good_sjson.name)
776

Alexander Kryklia committed
777 778
        transcripts = self.item.get_transcripts_info()
        text, filename, mime_type = self.item.get_transcript(transcripts)
779

780 781 782 783 784 785 786 787 788 789 790 791
        expected_text = textwrap.dedent("""\
            0
            00:00:00,270 --> 00:00:02,720
            Hi, welcome to Edx.

            1
            00:00:02,720 --> 00:00:05,430
            Let&#39;s start with what is on your screen right now.

            """)

        self.assertEqual(text, expected_text)
792
        self.assertEqual(filename[:-4], self.item.sub)
793
        self.assertEqual(mime_type, 'application/x-subrip; charset=utf-8')
794

795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
    def test_good_txt_transcript(self):
        good_sjson = _create_file(content=textwrap.dedent("""\
                {
                  "start": [
                    270,
                    2720
                  ],
                  "end": [
                    2720,
                    5430
                  ],
                  "text": [
                    "Hi, welcome to Edx.",
                    "Let&#39;s start with what is on your screen right now."
                  ]
                }
            """))

        _upload_sjson_file(good_sjson, self.item.location)
        self.item.sub = _get_subs_id(good_sjson.name)
Alexander Kryklia committed
815 816
        transcripts = self.item.get_transcripts_info()
        text, filename, mime_type = self.item.get_transcript(transcripts, transcript_format="txt")
817 818 819 820 821
        expected_text = textwrap.dedent("""\
            Hi, welcome to Edx.
            Let's start with what is on your screen right now.""")

        self.assertEqual(text, expected_text)
822
        self.assertEqual(filename, self.item.sub + '.txt')
823
        self.assertEqual(mime_type, 'text/plain; charset=utf-8')
824 825

    def test_en_with_empty_sub(self):
826

Alexander Kryklia committed
827
        transcripts = {"transcripts": {}, "sub": ""}
828
        # no self.sub, self.youttube_1_0 exist, but no file in assets
829
        with self.assertRaises(NotFoundError):
Alexander Kryklia committed
830
            self.item.get_transcript(transcripts)
831

Alexander Kryklia committed
832
        # no self.sub and no self.youtube_1_0, no non-en transcritps
833 834
        self.item.youtube_id_1_0 = None
        with self.assertRaises(ValueError):
Alexander Kryklia committed
835
            self.item.get_transcript(transcripts)
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856

        # no self.sub but youtube_1_0 exists with file in assets
        good_sjson = _create_file(content=textwrap.dedent("""\
                {
                  "start": [
                    270,
                    2720
                  ],
                  "end": [
                    2720,
                    5430
                  ],
                  "text": [
                    "Hi, welcome to Edx.",
                    "Let&#39;s start with what is on your screen right now."
                  ]
                }
            """))
        _upload_sjson_file(good_sjson, self.item.location)
        self.item.youtube_id_1_0 = _get_subs_id(good_sjson.name)

Alexander Kryklia committed
857
        text, filename, mime_type = self.item.get_transcript(transcripts)
858 859 860 861 862 863 864 865 866 867 868 869 870
        expected_text = textwrap.dedent("""\
            0
            00:00:00,270 --> 00:00:02,720
            Hi, welcome to Edx.

            1
            00:00:02,720 --> 00:00:05,430
            Let&#39;s start with what is on your screen right now.

            """)

        self.assertEqual(text, expected_text)
        self.assertEqual(filename, self.item.youtube_id_1_0 + '.srt')
871
        self.assertEqual(mime_type, 'application/x-subrip; charset=utf-8')
872

873 874
    def test_non_en_with_non_ascii_filename(self):
        self.item.transcript_language = 'zh'
Alexander Kryklia committed
875 876
        self.srt_file.seek(0)
        _upload_file(self.srt_file, self.item_descriptor.location, u"塞.srt")
877

Alexander Kryklia committed
878 879
        transcripts = self.item.get_transcripts_info()
        text, filename, mime_type = self.item.get_transcript(transcripts)
880 881 882 883 884 885
        expected_text = textwrap.dedent("""
        0
        00:00:00,12 --> 00:00:00,100
        Привіт, edX вітає вас.
        """)
        self.assertEqual(text, expected_text)
886 887 888
        self.assertEqual(filename, u"塞.srt")
        self.assertEqual(mime_type, 'application/x-subrip; charset=utf-8')

889 890 891 892 893 894
    def test_value_error(self):
        good_sjson = _create_file(content='bad content')

        _upload_sjson_file(good_sjson, self.item.location)
        self.item.sub = _get_subs_id(good_sjson.name)

Alexander Kryklia committed
895
        transcripts = self.item.get_transcripts_info()
896
        with self.assertRaises(ValueError):
Alexander Kryklia committed
897
            self.item.get_transcript(transcripts)
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915

    def test_key_error(self):
        good_sjson = _create_file(content="""
                {
                  "start": [
                    270,
                    2720
                  ],
                  "end": [
                    2720,
                    5430
                  ]
                }
            """)

        _upload_sjson_file(good_sjson, self.item.location)
        self.item.sub = _get_subs_id(good_sjson.name)

Alexander Kryklia committed
916
        transcripts = self.item.get_transcripts_info()
917
        with self.assertRaises(KeyError):
Alexander Kryklia committed
918
            self.item.get_transcript(transcripts)