def test_compatible_context(self):
        """
        Tests that the get_context_data method supplies a backwards-compatible
        "data" context variable in addition to adding the form and video to the
        context.

        """
        view = SubmitVideoView(form_class=forms.SubmitVideoFormBase)
        view.request = self.factory.get('/')
        view.request.session[view.get_session_key()] = {
            'url': '',
            'video': VidscraperVideo('')
        }
        view.object = self.create_video()
        view.url = (view.object.website_url or view.object.file_url)
        view.video = VidscraperVideo(view.url)
        form = view.get_form(view.get_form_class())

        context_data = view.get_context_data(form=form)
        self.assertEqual(context_data.get('video'), view.object)
        self.assertIsInstance(context_data.get('form'), view.form_class)
        self.assertTrue('data' in context_data)
        self.assertEqual(
            set(context_data['data']),
            set([
                'link', 'publish_date', 'tags', 'title', 'description',
                'thumbnail_url', 'user', 'user_url'
            ]))
Example #2
0
 def _set_session(self, data):
     video = VidscraperVideo(data['video_data']['url'])
     for attr, value in data['video_data'].iteritems():
         setattr(video, attr, value)
     session = self.client.session
     session[SubmitURLView.session_key] = {'video': video, 'url': video.url}
     session.save()
Example #3
0
    def _test_submit__existing_approved(self,
                                        video_kwargs=None,
                                        vidscraper_kwargs=None):
        """
        If the URL represents an existing and approved video, the form should
        be redisplayed. Additionally, the context should contain two variables
        for backwards-compatibility:

            * ``was_duplicate``: True
            * ``video``: The duplicate video instance

        """
        video = Video.objects.create(site=self.site_settings.site,
                                     name='Participatory Culture',
                                     status=Video.ACTIVE,
                                     **video_kwargs)
        data = {'url': 'http://pculture.org/'}
        expected_error = "That video has already been submitted!"

        vidscraper_video = VidscraperVideo(data['url'])
        for attr, value in (vidscraper_kwargs or {}).iteritems():
            setattr(vidscraper_video, attr, value)
        with patch.object(vidscraper,
                          'auto_scrape',
                          return_value=vidscraper_video):
            response = self.client.get(self.url, data)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, self.template_name)
        self.assertFormError(response, 'form', 'url', [expected_error])
        self.assertTrue(response.context['was_duplicate'])
        self.assertEqual(response.context['video'], video)
    def test_form_valid(self):
        """
        If the submitted form is valid, a :class:`ContestVideo` should be
        created for the newly submitted :class:`Video`.
        """
        self.view.request = self.factory.get('/')
        self.view.object = Video()
        self.view.url = u'http://google.com/'
        self.view.video = VidscraperVideo(self.view.url)
        self.view.video.name = 'Test Video'
        self.view.video.embed_code = 'Test Code'
        self.view.request.session[self.view.get_session_key()] = {
            'url': self.view.url,
            'video': self.view.video
            }

        form = self.view.get_form_class()(data={
                'url': self.view.url,
                'name': self.view.video.name,
                'embed_code': self.view.video.embed_code},
                                     **self.view.get_form_kwargs())
        self.assertTrue(form.is_valid(), form.errors.items())
        self.assertTrue(self.view.form_valid(form))
        cv = ContestVideo.objects.get()
        self.assertEqual(cv.video, self.view.object)
        self.assertEqual(cv.contest, self.contest)
    def test_form_valid__scraped__embed(self):
        """
        Checks that, if the form represents a scraped video with embed code,
        the success_url is the url of the scraped_video view, and that the
        session data contains the scraped video as 'video' and the video's
        url as 'url'.

        """
        scraped_url = reverse('localtv_submit_scraped_video')
        view = SubmitURLView(scraped_url=scraped_url)
        video_url = "http://google.com"
        url = "%s?url=%s" % (reverse('localtv_submit_video'), video_url)
        view.request = self.factory.get(url)
        expected_success_url = "%s?%s" % (scraped_url,
                                          view.request.GET.urlencode())
        form = view.get_form(view.get_form_class())

        video = VidscraperVideo(video_url)
        video.embed_code = "blink"
        form.video_cache = video
        form.cleaned_data = {'url': video_url}

        view.form_valid(form)
        self.assertEqual(view.request.session[view.get_session_key()], {
            'video': video,
            'url': video_url
        })
        self.assertEqual(view.success_url, expected_success_url)
    def test_form_valid__embedrequest(self):
        """
        Checks that, if the form represents an embedrequest video - i.e. a video
        that vidscraper can't scrape and which doesn't look like a direct link -
        the success_url is set to the url of the embedrequest view, and that the
        session data contains the scraped video (or ``None``) as 'video' and the
        video's url as 'url'.

        """
        embed_url = reverse('localtv_submit_embedrequest_video')
        view = SubmitURLView(embed_url=embed_url)
        video_url = 'http://google.com'
        url = "%s?url=%s" % (reverse('localtv_submit_video'), video_url)
        view.request = self.factory.get(url)
        expected_success_url = "%s?%s" % (embed_url,
                                          view.request.GET.urlencode())
        form = view.get_form(view.get_form_class())

        # Option 1: no video
        form.video_cache = None
        form.cleaned_data = {'url': video_url}

        view.form_valid(form)
        self.assertEqual(view.request.session[view.get_session_key()], {
            'video': None,
            'url': video_url
        })
        self.assertEqual(view.success_url, expected_success_url)

        # Option two: video missing embed & file_url
        video = VidscraperVideo(video_url)
        form.video_cache = video
        form.cleaned_data = {'url': video_url}

        view.form_valid(form)
        self.assertEqual(view.request.session[view.get_session_key()], {
            'video': video,
            'url': video_url
        })
        self.assertEqual(view.success_url, expected_success_url)

        # Option three: video with expiring file_url.
        video.file_url = 'hola'
        video.file_url_expires = datetime.datetime.now() + datetime.timedelta(
            1)

        view.form_valid(form)
        self.assertEqual(view.request.session[view.get_session_key()], {
            'video': video,
            'url': video_url
        })
        self.assertEqual(view.success_url, expected_success_url)
    def test_requires_session_data(self):
        # This differs from the functional testing in that it tests the view
        # directly. The inputs given can only result in a 302 response or a 200
        # response, depending on whether there is correct session data or not.
        view = SubmitVideoView(form_class=forms.SubmitVideoFormBase,
                               submit_video_url='http://google.com/')
        request = self.factory.get('/')
        response = view.dispatch(request)
        self.assertEqual(response.status_code, 302)

        request.session[view.get_session_key()] = {
            'url': 'http://google.com',
            'video': VidscraperVideo('http://google.com/')
        }
        response = view.dispatch(request)
        self.assertEqual(response.status_code, 200)
    def test_get_initial_tags(self):
        """
        Tests that tags are in the initial data only if tags are defined on the
        video, and that the tags in the expected format - at the moment, this
        is the return value of get_or_create_tags(tags).

        """
        view = SubmitVideoView()
        view.video = VidscraperVideo('http://google.com')
        initial = view.get_initial()
        self.assertFalse('tags' in initial)

        tags = ['hello', 'goodbye']
        view.video.tags = tags
        initial = view.get_initial()
        self.assertTrue('tags' in initial)
        # This is perhaps not the best way to test this.
        self.assertEqual(initial['tags'], get_or_create_tags(tags))
    def test_form_valid(self):
        """
        Tests that when the form_valid method is run, the session information
        is cleared, and the submit_finished signal is sent.

        """
        view = SubmitVideoView(form_class=forms.SubmitVideoFormBase,
                               form_fields=(
                                   'tags',
                                   'contact',
                                   'notes',
                               ),
                               thanks_url_name='localtv_submit_thanks')
        view.request = self.factory.get('/')
        view.object = Video()
        view.url = u'http://google.com/'
        view.video = VidscraperVideo(view.url)
        view.video.embed_code = 'Test Code'
        view.request.session[view.get_session_key()] = {
            'url': view.url,
            'video': view.video
        }

        submit_dict = {'hit': False}

        def test_submit_finished(sender, **kwargs):
            submit_dict['hit'] = True

        submit_finished.connect(test_submit_finished)
        form = view.get_form_class()(data={
            'url': view.url,
            'name': 'Test Video',
            'embed_code': 'Test Code',
            'contact': '*****@*****.**'
        },
                                     **view.get_form_kwargs())
        self.assertTrue(form.is_valid(), form.errors.items())
        self.assertTrue(view.form_valid(form))

        self.assertEqual(submit_dict['hit'], True)
        self.assertFalse(view.get_session_key() in view.request.session)
        submit_finished.disconnect(test_submit_finished)
    def test_form_valid__directlink(self):
        """
        Checks that, if the form represents a direct link to a video file, the
        success_url is the url of the direct_link view, and that the session
        data contains the video (or ``None``) as 'video' and the video's url
        as 'url'.

        NOTE:: Direct link videos will probably not actually result in the
        creation of VidscraperVideo instances; this is tested only to maintain
        the exact behavior which previously existed.

        """
        direct_url = reverse('localtv_submit_directlink_video')
        view = SubmitURLView(direct_url=direct_url)
        video_url = "http://google.com/file.mov"
        url = "%s?url=%s" % (reverse('localtv_submit_video'), video_url)
        view.request = self.factory.get(url)
        expected_success_url = "%s?%s" % (direct_url,
                                          view.request.GET.urlencode())
        form = view.get_form(view.get_form_class())

        # Option one: No video, but a video file url.
        form.video_cache = None
        form.cleaned_data = {'url': video_url}

        view.form_valid(form)
        self.assertEqual(view.request.session[view.get_session_key()], {
            'video': None,
            'url': video_url
        })
        self.assertEqual(view.success_url, expected_success_url)

        # Option two: A video missing embed_code and file_url data, but a video
        # file url.
        video = VidscraperVideo(video_url)
        form.video_cache = video
        view.form_valid(form)
        self.assertEqual(view.request.session[view.get_session_key()], {
            'video': video,
            'url': video_url
        })
        self.assertEqual(view.success_url, expected_success_url)
    def test_get_object(self):
        """
        Tests that the view's get_object method returns a Video instance,
        populated with data from a vidscraper video if available.

        """
        view = SubmitVideoView()
        view.video = None
        obj = view.get_object()
        self.assertIsInstance(obj, Video)
        self.assertEqual(obj.name, '')
        self.assertEqual(obj.embed_code, '')

        view.video = VidscraperVideo('')
        view.video.title = 'Title'
        view.video.embed_code = 'embed_code'
        obj = view.get_object()
        self.assertIsInstance(view.get_object(), Video)
        self.assertEqual(obj.name, 'Title')
        self.assertEqual(obj.embed_code, 'embed_code')
Example #12
0
    def _test_submit__succeed(self, url, next_view, **kwargs):
        """
        A GET request to the SubmitURLView with GET data should submit the form
        if the GET data overlaps with the form field(s). On success, the user
        should be redirected to the correct submission completion view,
        preserving GET data.

        All the views to which the user could be redirected are instances of
        the same class-based view. This is essentially a test for
        backwards-compatibility.

        """
        data = {'url': url, 'q': 'hello', 'next': 'blink'}
        expected_url = "%s?%s" % (reverse(next_view), urlencode(data))
        video = VidscraperVideo(url)
        video._loaded = True
        for attr, value in kwargs.iteritems():
            setattr(video, attr, value)
        with patch.object(vidscraper, 'auto_scrape', return_value=video):
            response = self.client.get(self.url, data)
        self.assertRedirects(response, expected_url)
Example #13
0
    def test_m2m_errors(self):
        """
        If video.save_m2m raises an exception during import, the video should
        be deleted and the error reraised.

        """
        class FakeException(Exception):
            pass

        video = mock.MagicMock(save_m2m=mock.MagicMock(
            side_effect=FakeException))
        kwargs = {'from_vidscraper_video.return_value': video}
        vidscraper_video = VidscraperVideo(None)

        with mock.patch('localtv.tasks.get_model'):
            with mock.patch('localtv.tasks.Video', **kwargs):
                with self.assertRaises(FakeException):
                    video_from_vidscraper_video.apply(
                        args=(vidscraper_video.serialize(), 1))

        video.save.assert_called_once_with(update_index=False)
        video.save_m2m.assert_called_once_with()
        video.delete.assert_called_once_with()