Ejemplo n.º 1
0
    def test_bad_parameters(self) -> None:
        """Test parameters with bad values."""
        request_data = MultiDict({
            'id': 'foo',  # invalid
            'function': 'prev',  # valid
            'context': 'cs.AI'  # valid
        })
        with self.assertRaises(BadRequest):
            prevnext.get_prevnext(request_data)

        request_data = MultiDict({
            'id': 'cs/0001001',  # valid
            'function': 'bar',  # invalid
            'context': 'cs'  # valid
        })
        with self.assertRaises(BadRequest):
            prevnext.get_prevnext(request_data)

        request_data = MultiDict({
            'id': 'cs/0001001',  # valid
            'function': 'next',  # valid
            'context': 'baz'  # invalid
        })
        with self.assertRaises(BadRequest):
            prevnext.get_prevnext(request_data)
Ejemplo n.º 2
0
    def test_date_range_supports_variable_precision(self):
        """Date range in advanced search should support variable precision."""
        data = MultiDict({
            'terms-0-operator': 'AND',
            'terms-0-field': 'title',
            'terms-0-term': 'foo',
            'date-filter_by': 'date_range',
            'date-to_date': '2012-02-05'
        })
        form = AdvancedSearchForm(data)
        self.assertTrue(form.validate())

        data = MultiDict({
            'terms-0-operator': 'AND',
            'terms-0-field': 'title',
            'terms-0-term': 'foo',
            'date-filter_by': 'date_range',
            'date-to_date': '2012-02'
        })
        form = AdvancedSearchForm(data)
        self.assertTrue(form.validate())

        data = MultiDict({
            'terms-0-operator': 'AND',
            'terms-0-field': 'title',
            'terms-0-term': 'foo',
            'date-filter_by': 'date_range',
            'date-to_date': '2013',
            'date-from_date': '2012-03'
        })
        form = AdvancedSearchForm(data)
        self.assertTrue(form.validate())
Ejemplo n.º 3
0
    def test_date_range_must_be_specified(self):
        """If the user selects date range, they must indicate start or end."""
        data = MultiDict({
            'terms-0-operator': 'AND',
            'terms-0-field': 'title',
            'terms-0-term': 'foo',
            'date-filter_by': 'date_range',
        })
        form = AdvancedSearchForm(data)
        self.assertFalse(form.validate())
        self.assertEqual(len(form.errors), 1)

        data = MultiDict({
            'terms-0-operator': 'AND',
            'terms-0-field': 'title',
            'terms-0-term': 'foo',
            'date-filter_by': 'date_range',
            'date-from_date': '2012-02-05'
        })
        form = AdvancedSearchForm(data)
        self.assertTrue(form.validate())

        data = MultiDict({
            'terms-0-operator': 'AND',
            'terms-0-field': 'title',
            'terms-0-term': 'foo',
            'date-filter_by': 'date_range',
            'date-to_date': '2012-02-05'
        })
        form = AdvancedSearchForm(data)
        self.assertTrue(form.validate())
Ejemplo n.º 4
0
    def test_good_parameters(self, mock_url_for,
                             mock_get_sequential_id) -> None:  # type: ignore
        """Test parameters with good values."""
        request_data = MultiDict({
            'id': '1801.00001',
            'function': 'next',
            'context': 'all'
        })
        mock_get_sequential_id.return_value = '1801.00002'
        _, status, headers = prevnext.get_prevnext(request_data)
        self.assertEqual(status, 301)

        request_data = MultiDict({
            'id': '1801.00002',
            'function': 'prev',
            'context': 'cs.AI'
        })
        mock_get_sequential_id.return_value = '1801.00001'
        _, status, headers = prevnext.get_prevnext(request_data)
        self.assertEqual(status, 301)

        request_data = MultiDict({
            'id': '1701.00002',
            'function': 'next',
            'context': 'physics.gen-ph'
        })
        mock_get_sequential_id.return_value = None
        with self.assertRaises(BadRequest):
            prevnext.get_prevnext(request_data)
        mock_get_sequential_id.return_value = ''
        with self.assertRaises(BadRequest):
            prevnext.get_prevnext(request_data)
Ejemplo n.º 5
0
    def test_individual_admins_post_errors(self):
        with self.request_context_with_admin("/", method="POST"):
            flask.request.form = MultiDict([])
            response = self.manager.admin_individual_admin_settings_controller.process_post()
            eq_(response.uri, INCOMPLETE_CONFIGURATION.uri)

        with self.request_context_with_admin("/", method="POST"):
            flask.request.form = MultiDict([
               ("email", "*****@*****.**"),
               ("roles", json.dumps([{ "role": AdminRole.LIBRARIAN, "library": "notalibrary" }])),
            ])
            response = self.manager.admin_individual_admin_settings_controller.process_post()
            eq_(response.uri, LIBRARY_NOT_FOUND.uri)

        library = self._library()
        with self.request_context_with_admin("/", method="POST"):
            flask.request.form = MultiDict([
               ("email", "*****@*****.**"),
               ("roles", json.dumps([{ "role": "notarole", "library": library.short_name }])),
            ])
            response = self.manager.admin_individual_admin_settings_controller.process_post()
            eq_(response.uri, UNKNOWN_ROLE.uri)

        with self.request_context_with_admin("/", method="POST"):
            flask.request.form = MultiDict([
                ("email", "wrong!"),
                ("password", "pass"),
                ("roles", json.dumps([{ "role": AdminRole.LIBRARY_MANAGER, "library": self._default_library.short_name }])),
            ])
            response = self.manager.admin_individual_admin_settings_controller.process_post()
            eq_(response.uri, INVALID_EMAIL.uri)
            assert "wrong!" in response.detail
Ejemplo n.º 6
0
    def test_validate_language_code(self):
        all_valid = ["eng", "spa", "ita"]
        all_invalid = ["abc", "def", "ghi"]
        mixed = ["eng", "abc", "spa"]

        form = MultiDict([("large_collections", all_valid)])
        response = Validator().validate_language_code(
            Configuration.LIBRARY_SETTINGS, {"form": form})
        eq_(response, None)

        form = MultiDict([("large_collections", all_invalid)])
        response = Validator().validate_language_code(
            Configuration.LIBRARY_SETTINGS, {"form": form})
        eq_(response.detail, '"abc" is not a valid language code.')
        eq_(response.status_code, 400)

        form = MultiDict([("large_collections", mixed)])
        response = Validator().validate_language_code(
            Configuration.LIBRARY_SETTINGS, {"form": form})
        eq_(response.detail, '"abc" is not a valid language code.')
        eq_(response.status_code, 400)

        form = MultiDict([("large_collections", all_valid),
                          ("small_collections", all_valid),
                          ("tiny_collections", mixed)])
        response = Validator().validate_language_code(
            Configuration.LIBRARY_SETTINGS, {"form": form})
        eq_(response.detail, '"abc" is not a valid language code.')
        eq_(response.status_code, 400)
Ejemplo n.º 7
0
 def test_is_valid_issue_form(self):
     """Assert that we get the form parameters we want."""
     incomplete_form = MultiDict([('problem_category', 'unknown_bug')])
     self.assertFalse(helpers.is_valid_issue_form(incomplete_form))
     valid_form = MultiDict([
         ('browser', 'Firefox 61.0'),
         ('description', 'streamlining the form.'),
         ('details', ''),
         ('os', 'Mac OS X 10.13'),
         ('problem_category', 'unknown_bug'),
         ('submit_type', 'github-auth-report'),
         ('url', 'http://2479.example.com'),
         ('username', ''), ])
     self.assertTrue(helpers.is_valid_issue_form(valid_form))
     # The value for submit-Type can be only:
     # - github-auth-report
     # - github-proxy-report
     wrong_value_form = MultiDict([
         ('browser', 'Firefox 61.0'),
         ('description', 'streamlining the form.'),
         ('details', ''),
         ('os', 'Mac OS X 10.13'),
         ('problem_category', 'unknown_bug'),
         ('submit_type', 'wrong-value'),
         ('url', 'http://2479.example.com'),
         ('username', ''), ])
     self.assertFalse(helpers.is_valid_issue_form(wrong_value_form))
Ejemplo n.º 8
0
    def test_is_valid_issue_form(self):
        """Assert that we get the form parameters we want."""
        cookie = 'exp=form-v1; Path=/'
        with webcompat.app.test_request_context(
                environ_base={'HTTP_COOKIE': cookie}):
            webcompat.app.preprocess_request()

            incomplete_form = MultiDict([('problem_category', 'unknown_bug')])
            self.assertFalse(helpers.is_valid_issue_form(incomplete_form))
            valid_form = MultiDict([
                ('browser', 'Firefox 61.0'),
                ('description', 'streamlining the form.'),
                ('details', ''),
                ('os', 'Mac OS X 10.13'),
                ('problem_category', 'unknown_bug'),
                ('submit_type', 'github-auth-report'),
                ('url', 'http://2479.example.com'),
                ('username', ''), ])
            self.assertTrue(helpers.is_valid_issue_form(valid_form))
            # The value for submit-Type can be only:
            # - github-auth-report
            # - github-proxy-report
            wrong_value_form = MultiDict([
                ('browser', 'Firefox 61.0'),
                ('description', 'streamlining the form.'),
                ('details', ''),
                ('os', 'Mac OS X 10.13'),
                ('problem_category', 'unknown_bug'),
                ('submit_type', 'wrong-value'),
                ('url', 'http://2479.example.com'),
                ('username', ''), ])
            self.assertFalse(helpers.is_valid_issue_form(wrong_value_form))
Ejemplo n.º 9
0
def test_urlencoded_parser():
    parser = urlencoded_parser()
    stream = io.BytesIO(b'foo=1&bar=2')
    assert parser(stream) == MultiDict({"foo": "1", "bar": "2"})

    parser = urlencoded_parser()
    stream = io.BytesIO(b'foo=1&foo=2')
    assert parser(stream) == MultiDict([("foo", "1"), ("foo", "2")])
Ejemplo n.º 10
0
    def test_request_missing_parameter(self):
        """Request for a new compilation with missing parameter."""
        with self.assertRaises(BadRequest):
            controllers.compile(MultiDict({'checksum': 'as12345'}), 'footoken',
                                mock.MagicMock())

        with self.assertRaises(BadRequest):
            controllers.compile(MultiDict({'source_id': '1234'}), 'footoken',
                                mock.MagicMock())
    def test_source(self):
        req = Mock(['args', 'headers', 'values'])
        req.args = {'foo': 'bar'}
        req.headers = {'baz': 'bat'}
        arg = Argument('foo', location=['args'])
        self.assertEquals(arg.source(req), MultiDict(req.args))

        arg = Argument('foo', location=['headers'])
        self.assertEquals(arg.source(req), MultiDict(req.headers))
Ejemplo n.º 12
0
    def test_collections_post_edit_mirror_integration(self):
        # The collection exists.
        collection = self._collection(
            name="Collection 1",
            protocol=ExternalIntegration.RB_DIGITAL
        )

        # There is a storage integration not associated with the collection.
        storage = self._external_integration(
            protocol=ExternalIntegration.S3,
            goal=ExternalIntegration.STORAGE_GOAL
        )

        # It's possible to associate the storage integration with the
        # collection for either a books or covers mirror.
        base_request = self._base_collections_post_request(collection)
        with self.request_context_with_admin("/", method="POST"):
            request = MultiDict(
                base_request + [("books_mirror_integration_id", storage.id)]
            )
            flask.request.form = request
            response = self.manager.admin_collection_settings_controller.process_collections()
            eq_(response.status_code, 200)

            # There is an external integration link to associate the collection's
            # external integration with the storage integration for a books mirror.
            external_integration_link = get_one(
                self._db, ExternalIntegrationLink,
                external_integration_id=collection.external_integration.id
            )
            eq_(storage.id, external_integration_link.other_integration_id)

        # It's possible to unset the mirror integration.
        controller = self.manager.admin_collection_settings_controller
        with self.request_context_with_admin("/", method="POST"):
            request = MultiDict(
                base_request + [("books_mirror_integration_id",
                                 str(controller.NO_MIRROR_INTEGRATION))]
            )
            flask.request.form = request
            response = controller.process_collections()
            eq_(response.status_code, 200)
            external_integration_link = get_one(
                self._db, ExternalIntegrationLink,
                external_integration_id=collection.external_integration.id
            )
            eq_(None, external_integration_link)

        # Providing a nonexistent integration ID gives an error.
        with self.request_context_with_admin("/", method="POST"):
            request = MultiDict(
                base_request + [("books_mirror_integration_id", -200)]
            )
            flask.request.form = request
            response = self.manager.admin_collection_settings_controller.process_collections()
            eq_(response, MISSING_SERVICE)
Ejemplo n.º 13
0
def handle(controller: Callable, template: str, title: str,
           submission_id: Optional[int] = None,
           get_params: bool = False, **kwargs) -> Response:
    """
    Generalized request handling pattern.

    Parameters
    ----------
    controller : callable
        A controller function with the signature ``(method: str, params:
        MultiDict, session: Session, submission_id: int, token: str) ->
        Tuple[dict, int, dict]``
    template : str
        HTML template to use in the response.
    title : str
        Page title, if not provided by controller.
    submission_id : int or None
    get_params : bool
        If True, GET parameters will be passed to the controller on GET
        requests. Default is False.
    kwargs : kwargs
        Passed as ``**kwargs`` to the controller.

    Returns
    -------
    :class:`.Response`

    """
    logger.debug('Handle call to controller %s with template %s, title %s,'
                 ' and ID %s', controller, template, title, submission_id)
    if request.method == 'GET' and get_params:
        request_data = MultiDict(request.args.items(multi=True))
    else:
        request_data = MultiDict(request.form.items(multi=True))

    context = {'pagetitle': title}
    try:
        data, code, headers = controller(request.method, request_data,
                                         request.session, submission_id,
                                         **kwargs)
    except (BadRequest, InternalServerError) as e:
        logger.debug('Caught %s from controller', e)
        context.update(e.description)
        context.update({'error': e})
        message = Markup(f'Something unexpected went wrong. {SUPPORT}')
        add_immediate_alert(context, alerts.FAILURE, message)
        return make_response(render_template(template, **context), e.code)
    except Unavailable as e:
        raise InternalServerError('Could not connect to database') from e
    context.update(data)

    if code < 300:
        return make_response(render_template(template, **context), code)
    if 'Location' in headers:
        return redirect(headers['Location'], code=code)
    return Response(response=context, status=code, headers=headers)
Ejemplo n.º 14
0
 def test_post_upload(self, mock_load, mock_save, mock_filemanager):
     """POST request for submission with an existing upload package."""
     submission_id = 2
     mock_submission = mock.MagicMock(
         submission_id=submission_id,
         source_content=SubmissionContent(
             identifier='5433',
             checksum='a1s2d3f4',
             uncompressed_size=593920,
             compressed_size=1000,
             source_format=SubmissionContent.Format.TEX),
         is_finalized=False,
         is_announced=False,
         arxiv_id=None,
         version=1)
     mock_load.return_value = (mock_submission, [])
     mock_save.return_value = (mock_submission, [])
     mock_fm = mock.MagicMock()
     mock_fm.add_file.return_value = Upload(
         identifier=25,
         checksum='a1s2d3f4',
         size=593920,
         started=datetime.now(),
         completed=datetime.now(),
         created=datetime.now(),
         modified=datetime.now(),
         status=Upload.Status.READY,
         lifecycle=Upload.LifecycleStates.ACTIVE,
         locked=False,
         files=[
             FileStatus(path='',
                        name='thebestfile.pdf',
                        file_type='PDF',
                        modified=datetime.now(),
                        size=20505,
                        ancillary=False,
                        errors=[])
         ],
         errors=[])
     mock_filemanager.current_session.return_value = mock_fm
     params = MultiDict({})
     mock_file = mock.MagicMock()
     files = MultiDict({'file': mock_file})
     _, code, _ = upload.upload_files('POST',
                                      params,
                                      self.session,
                                      submission_id,
                                      files=files,
                                      token='footoken')
     self.assertEqual(code, status.SEE_OTHER, 'Returns 303')
     self.assertEqual(mock_fm.add_file.call_count, 1,
                      'Calls the file management service')
     self.assertTrue(mock_filemanager.add_file.called_with(mock_file))
Ejemplo n.º 15
0
 def test_get_upload(self, mock_load, mock_filemanager):
     """GET request for submission with an existing upload package."""
     submission_id = 2
     mock_load.return_value = (mock.MagicMock(
         submission_id=submission_id,
         source_content=SubmissionContent(
             identifier='5433',
             checksum='a1s2d3f4',
             uncompressed_size=593920,
             compressed_size=1000,
             source_format=SubmissionContent.Format.TEX),
         is_finalized=False,
         is_announced=False,
         arxiv_id=None,
         version=1), [])
     mock_filemanager.get_upload_status.return_value = (Upload(
         identifier=25,
         checksum='a1s2d3f4',
         size=593920,
         started=datetime.now(),
         completed=datetime.now(),
         created=datetime.now(),
         modified=datetime.now(),
         status=Upload.Status.READY,
         lifecycle=Upload.LifecycleStates.ACTIVE,
         locked=False,
         files=[
             FileStatus(path='',
                        name='thebestfile.pdf',
                        file_type='PDF',
                        modified=datetime.now(),
                        size=20505,
                        ancillary=False,
                        errors=[])
         ],
         errors=[]))
     params = MultiDict({})
     files = MultiDict({})
     data, code, _ = upload.upload_files('GET',
                                         params,
                                         self.session,
                                         submission_id,
                                         files=files,
                                         token='footoken')
     self.assertEqual(code, status.OK, 'Returns 200 OK')
     self.assertEqual(mock_filemanager.get_upload_status.call_count, 1,
                      'Calls the file management service')
     self.assertIn('status', data, 'Upload status is in response')
     self.assertIn('submission', data, 'Submission is in response')
     self.assertIn('submission_id', data, 'ID is in response')
Ejemplo n.º 16
0
    def test_analytics_services_post_create(self):
        library, ignore = create(
            self._db,
            Library,
            name="Library",
            short_name="L",
        )
        with self.request_context_with_admin("/", method="POST"):
            flask.request.form = MultiDict([
                ("name", "Google analytics name"),
                ("protocol", GoogleAnalyticsProvider.__module__),
                (ExternalIntegration.URL, "http://test"),
                ("libraries",
                 json.dumps([{
                     "short_name": "L",
                     "tracking_id": "trackingid"
                 }])),
            ])
            response = self.manager.admin_analytics_services_controller.process_analytics_services(
            )
            eq_(response.status_code, 201)

        service = get_one(self._db,
                          ExternalIntegration,
                          goal=ExternalIntegration.ANALYTICS_GOAL)
        eq_(service.id, int(response.response[0]))
        eq_(GoogleAnalyticsProvider.__module__, service.protocol)
        eq_("http://test", service.url)
        eq_([library], service.libraries)
        eq_(
            "trackingid",
            ConfigurationSetting.for_library_and_externalintegration(
                self._db, GoogleAnalyticsProvider.TRACKING_ID, library,
                service).value)

        # Creating a local analytics service doesn't require a URL.
        with self.request_context_with_admin("/", method="POST"):
            flask.request.form = MultiDict([
                ("name", "local analytics name"),
                ("protocol", LocalAnalyticsProvider.__module__),
                ("libraries",
                 json.dumps([{
                     "short_name": "L",
                     "tracking_id": "trackingid"
                 }])),
            ])
            response = self.manager.admin_analytics_services_controller.process_analytics_services(
            )
            eq_(response.status_code, 201)
Ejemplo n.º 17
0
    def test_search_services_post_create(self):
        with self.request_context_with_admin("/", method="POST"):
            flask.request.form = MultiDict([
                ("name", "Name"),
                ("protocol", ExternalIntegration.ELASTICSEARCH),
                (ExternalIntegration.URL, "http://search_url"),
                (ExternalSearchIndex.WORKS_INDEX_PREFIX_KEY,
                 "works-index-prefix"),
                (ExternalSearchIndex.TEST_SEARCH_TERM_KEY,
                 "sample-search-term")
            ])
            response = self.manager.admin_search_services_controller.process_services(
            )
            eq_(response.status_code, 201)

        service = get_one(self._db,
                          ExternalIntegration,
                          goal=ExternalIntegration.SEARCH_GOAL)
        eq_(service.id, int(response.response[0]))
        eq_(ExternalIntegration.ELASTICSEARCH, service.protocol)
        eq_("http://search_url", service.url)
        eq_("works-index-prefix",
            service.setting(ExternalSearchIndex.WORKS_INDEX_PREFIX_KEY).value)
        eq_("sample-search-term",
            service.setting(ExternalSearchIndex.TEST_SEARCH_TERM_KEY).value)
Ejemplo n.º 18
0
    def test_validate_image(self):
        def create_image_file(format_string):
            image_data = '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x01\x03\x00\x00\x00%\xdbV\xca\x00\x00\x00\x06PLTE\xffM\x00\x01\x01\x01\x8e\x1e\xe5\x1b\x00\x00\x00\x01tRNS\xcc\xd24V\xfd\x00\x00\x00\nIDATx\x9cc`\x00\x00\x00\x02\x00\x01H\xaf\xa4q\x00\x00\x00\x00IEND\xaeB`\x82'

            class TestImageFile(StringIO):
                headers = {"Content-Type": "image/" + format_string}

            return TestImageFile(image_data)
            return result

        [png, jpeg, gif, invalid] = [
            MultiDict([(Configuration.LOGO, create_image_file(x))])
            for x in ["png", "jpeg", "gif", "abc"]
        ]

        png_response = Validator().validate_image(
            Configuration.LIBRARY_SETTINGS, {"files": png})
        eq_(png_response, None)
        jpeg_response = Validator().validate_image(
            Configuration.LIBRARY_SETTINGS, {"files": jpeg})
        eq_(jpeg_response, None)
        gif_response = Validator().validate_image(
            Configuration.LIBRARY_SETTINGS, {"files": gif})
        eq_(gif_response, None)

        abc_response = Validator().validate_image(
            Configuration.LIBRARY_SETTINGS, {"files": invalid})
        eq_(
            abc_response.detail,
            'Upload for Logo image must be in GIF, PNG, or JPG format. (Upload was image/abc.)'
        )
        eq_(abc_response.status_code, 400)
    def test_admin_auth_services_post_create(self):
        with self.request_context_with_admin("/", method="POST"):
            flask.request.form = MultiDict([
                ("name", "oauth"),
                ("protocol", "Google OAuth"),
                ("url", "http://url2"),
                ("username", "username"),
                ("password", "password"),
                ("libraries",
                 json.dumps([{
                     "short_name": self._default_library.short_name,
                     "domains": ["nypl.org", "gmail.com"]
                 }])),
            ])
            response = self.manager.admin_auth_services_controller.process_admin_auth_services(
            )
            eq_(response.status_code, 201)

        # The auth service was created and configured properly.
        auth_service = ExternalIntegration.admin_authentication(self._db)
        eq_(auth_service.protocol, response.response[0])
        eq_("oauth", auth_service.name)
        eq_("http://url2", auth_service.url)
        eq_("username", auth_service.username)
        eq_("password", auth_service.password)

        eq_([self._default_library], auth_service.libraries)
        setting = ConfigurationSetting.for_library_and_externalintegration(
            self._db, "domains", self._default_library, auth_service)
        eq_("domains", setting.key)
        eq_(["nypl.org", "gmail.com"], json.loads(setting.value))
Ejemplo n.º 20
0
    def test_cannot_set_non_storage_integration_as_mirror_integration(self):
        # The collection exists.
        collection = self._collection(
            name="Collection 1",
            protocol=ExternalIntegration.RB_DIGITAL
        )

        # There is a storage integration not associated with the collection,
        # which makes it possible to associate storage integrations
        # with collections through the collections controller.
        storage = self._external_integration(
            protocol=ExternalIntegration.S3,
            goal=ExternalIntegration.STORAGE_GOAL
        )

        # Trying to set a non-storage integration (such as the
        # integration associated with the collection's licenses) as
        # the collection's mirror integration gives an error.
        base_request = self._base_collections_post_request(collection)
        with self.request_context_with_admin("/", method="POST"):
            request = MultiDict(
                base_request + [
                    ("books_mirror_integration_id", collection.external_integration.id)
                ]
            )
            flask.request.form = request
            response = self.manager.admin_collection_settings_controller.process_collections()
            eq_(response, INTEGRATION_GOAL_CONFLICT)
Ejemplo n.º 21
0
def create(method: str, params: MultiDict, session: Session, *args,
           **kwargs) -> Response:
    """Create a new submission, and redirect to workflow."""
    submitter, client = user_and_client_from_session(session)
    response_data = {}
    if method == 'GET':     # Display a splash page.
        response_data['user_submissions'] \
            = _load_submissions_for_user(session.user.user_id)
        params = MultiDict()

    # We're using a form here for CSRF protection.
    form = CreateSubmissionForm(params)
    response_data['form'] = form

    if method == 'POST':
        if not form.validate():
            raise BadRequest(response_data)

        command = CreateSubmission(creator=submitter, client=client)
        if not validate_command(form, command):
            raise BadRequest(response_data)

        try:
            submission, _ = save(command)
        except SaveError as e:
            logger.error('Could not save command: %s', e)
            raise InternalServerError(response_data) from e

        loc = url_for('ui.verify_user', submission_id=submission.submission_id)
        return {}, status.SEE_OTHER, {'Location': loc}
    return response_data, status.OK, {}
Ejemplo n.º 22
0
 def test_post_request_invalid_data(self, mock_load, mock_save):
     """POST request with invalid data."""
     submission_id = 2
     mock_submission = mock.MagicMock(
         submission_id=submission_id,
         is_finalized=False,
         metadata=mock.MagicMock(
             title='the old title',
             abstract='not the abstract that you are looking for',
             authors_display='bloggs, j'
         )
     )
     mock_load.return_value = (mock_submission, [])
     mock_save.return_value = (mock_submission, [])
     params = MultiDict({
         'title': 'the new title',
         'abstract': 'too short',
         'authors_display': 'bloggs, j'
     })
     try:
         metadata.metadata('POST', params, self.session, submission_id)
         self.fail('BadRequest not raised')
     except BadRequest as e:
         data = e.description
         self.assertIsInstance(data['form'], Form, "Data includes a form")
Ejemplo n.º 23
0
def test_generate_inspire_search_links_gets_proper_formats(inspire_app):
    expected_links_test2 = {
        "self": "http://localhost:5000/api/test2/?q=&size=10&page=1",
        "format4": "http://localhost:5000/api/test2/?q=&size=10&page=1&format=format4",
        "format5": "http://localhost:5000/api/test2/?q=&size=10&page=1&format=format5",
    }
    expected_links_test = {
        "self": "http://localhost:5000/api/test/?q=&size=10&page=1",
        "format1": "http://localhost:5000/api/test/?q=&size=10&page=1&format=format1",
        "format2": "http://localhost:5000/api/test/?q=&size=10&page=1&format=format2",
        "format3": "http://localhost:5000/api/test/?q=&size=10&page=1&format=format3",
    }
    config = {
        "TEST": {
            "search_serializers_aliases": {
                "format1": "format/1",
                "format2": "format/2",
                "format3": "format/3",
            }
        },
        "TEST2": {
            "search_serializers_aliases": {"format4": "format/4", "format5": "format/5"}
        },
    }
    with override_config(**config):
        links_test = {"self": "http://localhost:5000/api/test/?q=&size=10&page=1"}
        links_test2 = {"self": "http://localhost:5000/api/test2/?q=&size=10&page=1"}
        with mock.patch("inspirehep.records.links.request") as mock_request:
            mock_request.values = MultiDict()
            mock_request.path = "/test"
            links_test = inspire_search_links(links_test)
            mock_request.path = "/test2"
            links_test2 = inspire_search_links(links_test2)
    assert links_test == expected_links_test
    assert links_test2 == expected_links_test2
Ejemplo n.º 24
0
def form():
    data = MultiDict()
    data.update(request.args)
    data.update(request.form)

    form_name = data.get('_form_name')
    redirect_url = data.get('_redirect_url')

    body = []
    for key, val in data.items():
        body.append('%s: %s' % (key, val))
        body.append('')
    body.append('')
    body.append('--')
    body.append('sent form former2 by Ondrej Sika')
    body.append('https://github.com/former2/former2')

    if form_name:
        subject = '[former2] Submit notification from %s' % form_name
    else:
        subject = '[former2] Submit notification'

    message = Message(subject,
                      sender=args.smtp_email,
                      recipients=args.notify_to.split(','))

    message.body = '\n'.join(body)
    mail.send(message)

    if redirect_url:
        return redirect(redirect_url)
    else:
        return message.body.replace('\n', '\n<br>')
Ejemplo n.º 25
0
def record_id_process(form, field, submit=False):
    value = field.data or ''
    if value == "" or value.isspace():
        return

    def is_number(s):
        try:
            float(s)
            return True
        except ValueError:
            return False

    if is_number(field.data):
        json_reader = get_record(value)
    else:
        field.add_message("Record id must be a number!", state='error')
        return

    if json_reader is not None:
        webdeposit_json = form.uncook_json(json_reader, {}, value)
        #FIXME: update current json, past self, what do you mean?? :S

        field.add_message('<a href="/record/"' + value +
                          '>Record</a> was loaded successfully',
                          state='info')

        form.process(MultiDict(webdeposit_json))
    else:
        field.add_message("Record doesn't exist", state='info')
Ejemplo n.º 26
0
def edit(name):
    if name not in _USER_SETTINGS:
        flash(_('Invalid plugin name'), 'error')
        return redirect(url_for('.index'))

    plugin = _USER_SETTINGS[name]()
    form = None

    if request.method == 'POST':
        if plugin.form_builder:
            form = plugin.form_builder(request.form)

        if not form or form.validate():
            plugin.store(request.form)
            plugin.save()
            flash(_('Data has been saved.'), 'success')
            return redirect(url_for('.index'))

        flash(_('Please, corrent errors.'), 'error')

    # get post data or load data from settings
    if not form and plugin.form_builder:
        form = plugin.form_builder(MultiDict(plugin.load()))

    return render_template(getattr(plugin, 'edit_template', '')
                           or 'webaccount_edit.html',
                           plugin=plugin,
                           form=form)
Ejemplo n.º 27
0
 def bad_choice():
     parser = RequestParser()
     parser.add_argument('foo', choices=['one', 'two'])
     req = Mock(['values'])
     req.values = MultiDict([('foo', 'three')])
     parser.parse_args(req)
     abort.assert_called_with(400, message='three is not a valid choice')
Ejemplo n.º 28
0
    def test_save_error_is_raised(self, mock_load, mock_save):
        """POST request results in an SaveError exception."""
        submission_id = 2
        mock_submission = mock.MagicMock(
            submission_id=submission_id,
            is_finalized=False,
            metadata=mock.MagicMock(
                title='the old title',
                abstract='not the abstract that you are looking for',
                authors_display='bloggs, j'
            )
        )
        mock_load.return_value = (mock_submission, [])

        def raise_save_error(*args, **kwargs):
            raise events.SaveError('nope')

        mock_save.side_effect = raise_save_error
        params = MultiDict({
            'title': 'a new, valid title',
            'abstract': 'this abstract is at least twenty characters long',
            'authors_display': 'j doe, j bloggs'
        })
        with self.assertRaises(InternalServerError):
            metadata.metadata('POST', params, self.session, submission_id)
Ejemplo n.º 29
0
def test_search_links_with_fields_filtering(inspire_app):
    expected_links_test = {
        "self": "http://localhost:5000/api/test/?q=&size=10&page=1&fields=ids,authors",
        "next": "http://localhost:5000/api/test/?q=&size=10&page=2&fields=ids,authors",
        "format1": "http://localhost:5000/api/test/?q=&size=10&page=1&format=format1",
        "json": "http://localhost:5000/api/test/?q=&size=10&page=1&fields=ids,authors&format=json",
    }
    config = {
        "TEST": {
            "search_serializers_aliases": {
                "format1": "format/1",
                "json": "application/json",
            }
        }
    }
    with override_config(**config):
        links_test = {
            "self": "http://localhost:5000/api/test/?q=&size=10&page=1",
            "next": "http://localhost:5000/api/test/?q=&size=10&page=2",
        }
        with mock.patch("inspirehep.records.links.request") as mock_request:
            mock_request.path = "/test"
            mock_request.values = MultiDict([("fields", "ids,authors")])
            links_test = inspire_search_links(links_test)
    assert links_test == expected_links_test
Ejemplo n.º 30
0
def GetValidFilters(args):
    filters = MultiDict()
    for arg, val in args.iteritems(True):
        if arg in ValidFilters:
            filters.add(arg, val)

    return filters