Python rest_framework.status.is_success() Examples

The following are 30 code examples for showing how to use rest_framework.status.is_success(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.status , or try the search function .

Example 1
Project: resolwe   Author: genialis   File: test_filtering.py    License: Apache License 2.0 6 votes vote down vote up
def _check_filter(
        self, query_args, expected, expected_status_code=status.HTTP_200_OK
    ):
        """Check that query_args filter to expected queryset."""
        request = factory.get("/", query_args, format="json")
        force_authenticate(request, self.admin)
        response = self.viewset(request)

        if status.is_success(response.status_code):
            self.assertEqual(len(response.data), len(expected))
            self.assertCountEqual(
                [item.pk for item in expected], [item["id"] for item in response.data],
            )
        else:
            self.assertEqual(response.status_code, expected_status_code)
            response.render()

        return response 
Example 2
Project: tfrs   Author: bcgov   File: test_credit_trade_comments.py    License: Apache License 2.0 6 votes vote down vote up
def test_put_as_fs_invalid_trade(self):
        """
        Test an invalid Credit Trade Comment PUT by a Fuel supplier
        (not party to the trade)
        """

        c_url = "/api/comments/1"
        test_data = {
            "comment": "updated comment 1",
            "creditTrade": 201,
            "privilegedAccess": False
        }
        response = self.clients['fs_air_liquide'].put(
            c_url,
            content_type='application/json',
            data=json.dumps(test_data)
        )
        assert status.is_success(response.status_code) 
Example 3
Project: ontask_b   Author: abelardopardo   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_question_add(self):
        """Test adding a question to a survey."""
        # Get the survey action
        survey = self.workflow.actions.get(action_type=models.Action.SURVEY)

        # GET the form
        resp = self.get_response(
            'column:question_add',
            {'pk': survey.id},
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))

        # Create the new question
        resp = self.get_response(
            'column:question_add',
            {'pk': survey.id},
            method='POST',
            req_params={
                'name': 'NEW QUESTION',
                'description_text': 'QUESTION DESCRIPTION',
                'data_type': 'string',
                'position': '0',
                'raw_categories': 'A,B,C,D'},
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code)) 
Example 4
Project: ontask_b   Author: abelardopardo   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_formula_column_add(self):
        """Test adding a formula column."""
        # GET the form
        resp = self.get_response('column:formula_column_add', is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))

        # Create the new question
        resp = self.get_response(
            'column:formula_column_add',
            method='POST',
            req_params={
                'name': 'FORMULA COLUMN',
                'description_text': 'FORMULA COLUMN DESC',
                'data_type': 'integer',
                'position': '0',
                'columns': ['12', '13'],
                'op_type': 'sum'},
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))

        df = pandas.load_table(self.workflow.get_data_frame_table_name())
        self.assertTrue(
            df['FORMULA COLUMN'].equals(df['Q01'] + df['Q02'])) 
Example 5
Project: ontask_b   Author: abelardopardo   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_column_clone(self):
        """Test adding a random column."""
        column = self.workflow.columns.get(name='Q01')
        resp = self.get_response(
            'column:column_clone',
            {'pk': column.id},
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))

        # Create the new question
        resp = self.get_response(
            'column:column_clone',
            {'pk': column.id},
            method='POST',
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))

        df = pandas.load_table(self.workflow.get_data_frame_table_name())
        self.assertTrue(df['Copy of Q01'].equals(df['Q01'])) 
Example 6
Project: ontask_b   Author: abelardopardo   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_column_restrict(self):
        """Test Column restriction."""
        column = self.workflow.columns.get(name='Gender')
        self.assertEqual(column.categories, [])

        resp = self.get_response(
            'column:column_restrict',
            {'pk': column.id},
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))

        resp = self.get_response(
            'column:column_restrict',
            {'pk': column.id},
            method='POST',
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))

        column.refresh_from_db()
        self.assertEqual(set(column.categories), {'female', 'male'}) 
Example 7
Project: ontask_b   Author: abelardopardo   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_assign_luser_column(self):
        """Test assign luser column option."""
        column = self.workflow.columns.get(name='email')
        self.assertEqual(self.workflow.luser_email_column, None)

        resp = self.get_response(
            'workflow:assign_luser_column',
            {'pk': column.id},
            method='POST',
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))

        column = self.workflow.columns.get(name='email')
        self.workflow.refresh_from_db()
        self.assertEqual(self.workflow.luser_email_column, column)
        self.assertEqual(self.workflow.lusers.count(), self.workflow.nrows) 
Example 8
Project: ontask_b   Author: abelardopardo   File: test_forms.py    License: MIT License 6 votes vote down vote up
def test_google_sheet_upload(self):
        """Test the Google Sheet upload."""
        # Get the regular form
        resp = self.get_response('dataops:googlesheetupload_start')
        self.assertTrue(status.is_success(resp.status_code))

        # POST the data
        filename = os.path.join(settings.ONTASK_FIXTURE_DIR, 'simple.csv')
        resp = self.get_response(
            'dataops:googlesheetupload_start',
            method='POST',
            req_params={
                'google_url': 'file://' + filename,
                'skip_lines_at_top': -1,
                'skip_lines_at_bottom': 0})
        self.assertNotEqual(resp.status_code, status.HTTP_302_FOUND)
        resp = self.get_response(
            'dataops:googlesheetupload_start',
            method='POST',
            req_params={
                'google_url': 'file://' + filename,
                'skip_lines_at_top': 0,
                'skip_lines_at_bottom': -1})
        self.assertNotEqual(resp.status_code, status.HTTP_302_FOUND) 
Example 9
Project: ontask_b   Author: abelardopardo   File: test_upload_logic.py    License: MIT License 6 votes vote down vote up
def test_csv_upload(self):
        """Test the CSV upload."""
        # Get the regular form
        resp = self.get_response('dataops:csvupload_start')
        self.assertTrue(status.is_success(resp.status_code))

        # POST the data
        filename = os.path.join(settings.ONTASK_FIXTURE_DIR, 'simple.csv')
        with open(filename) as fp:
            resp = self.get_response(
                'dataops:csvupload_start',
                method='POST',
                req_params={
                    'data_file': fp,
                    'skip_lines_at_top': 0,
                    'skip_lines_at_bottom': 0})
        self.assertEqual(resp.status_code, status.HTTP_302_FOUND)
        self.assertEqual(resp.url, reverse('dataops:upload_s2')) 
Example 10
Project: ontask_b   Author: abelardopardo   File: test_upload_logic.py    License: MIT License 6 votes vote down vote up
def test_google_sheet_upload(self):
        """Test the Google Sheet upload."""
        # Get the regular form
        resp = self.get_response('dataops:googlesheetupload_start')
        self.assertTrue(status.is_success(resp.status_code))

        # POST the data
        filename = os.path.join(settings.ONTASK_FIXTURE_DIR, 'simple.csv')
        resp = self.get_response(
            'dataops:googlesheetupload_start',
            method='POST',
            req_params={
                'google_url': 'file://' + filename,
                'skip_lines_at_top': 0,
                'skip_lines_at_bottom': 0})
        self.assertEqual(resp.status_code, status.HTTP_302_FOUND)
        self.assertEqual(resp.url, reverse('dataops:upload_s2')) 
Example 11
Project: ontask_b   Author: abelardopardo   File: test_upload_logic.py    License: MIT License 6 votes vote down vote up
def test_s3_upload(self):
        """Test the S3 upload."""
        # Get the regular form
        resp = self.get_response('dataops:s3upload_start')
        self.assertTrue(status.is_success(resp.status_code))

        # POST the data
        filepath = os.path.join(settings.ONTASK_FIXTURE_DIR, 'simple.csv')
        resp = self.get_response(
            'dataops:s3upload_start',
            method='POST',
            req_params={
                'aws_bucket_name': filepath.split('/')[1],
                'aws_file_key': '/'.join(filepath.split('/')[2:]),
                'skip_lines_at_top': 0,
                'skip_lines_at_bottom': 0,
                'domain': 'file:/'})
        self.assertEqual(resp.status_code, status.HTTP_302_FOUND)
        self.assertEqual(resp.url, reverse('dataops:upload_s2')) 
Example 12
Project: ontask_b   Author: abelardopardo   File: test_import_export.py    License: MIT License 6 votes vote down vote up
def test_export(self):
        """Export ask followed by export request."""
        resp = self.get_response(
            'workflow:export_ask',
            {'wid': self.workflow.id})
        self.assertTrue(status.is_success(resp.status_code))

        req_params = {
            'select_{0}'.format(idx): True
            for idx in range(self.workflow.actions.count())}
        resp = self.get_response(
            'workflow:export_ask',
            {'wid': self.workflow.id},
            method='POST',
            req_params=req_params,
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code)) 
Example 13
Project: ontask_b   Author: abelardopardo   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_workflow_update(self):
        """Update the name and description of the workflow."""
        # Update name and description
        resp = self.get_response(
            'workflow:update',
            {'wid': self.workflow.id},
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))
        resp = self.get_response(
            'workflow:update',
            {'wid': self.workflow.id},
            method='POST',
            req_params={
                'name': self.workflow.name + '2',
                'description_text': 'description'},
            is_ajax=True)
        self.assertTrue(status.is_success(resp.status_code))
        self.workflow.refresh_from_db()
        self.assertEqual(self.workflow_name + '2', self.workflow.name)
        self.assertEqual(self.workflow.description_text, 'description') 
Example 14
Project: ontask_b   Author: abelardopardo   File: test_views_run_zip.py    License: MIT License 6 votes vote down vote up
def test_run_zip(self):
        """Run the zip action."""
        # Get the object first
        action = self.workflow.actions.get(name='Suggestions about the forum')
        column = action.workflow.columns.get(name='SID')
        column_fn = action.workflow.columns.get(name='email')
        # Request ZIP action execution
        resp = self.get_response('action:zip_action', {'pk': action.id})
        self.assertTrue(status.is_success(resp.status_code))

        # Post the execution request
        resp = self.get_response(
            'action:zip_action',
            {'pk': action.id},
            method='POST',
            req_params={
                'action_id': action.id,
                'item_column': column.pk,
                'user_fname_column': column_fn.pk,
                'confirm_items': False,
                'zip_for_moodle': False,
            })
        self.assertTrue(status.is_success(resp.status_code)) 
Example 15
Project: ontask_b   Author: abelardopardo   File: test_views_run.py    License: MIT License 6 votes vote down vote up
def test_run_canvas_email_action(self):
        """Test Canvas Email action execution."""
        action = self.workflow.actions.get(name='Initial motivation')
        column = action.workflow.columns.get(name='SID')
        resp = self.get_response('action:run', url_params={'pk': action.id})
        self.assertTrue(status.is_success(resp.status_code))

        # POST -> redirect to item filter
        resp = self.get_response(
            'action:run',
            url_params={'pk': action.id},
            method='POST',
            req_params={
                'subject': 'Email subject',
                'item_column': column.pk,
                'target_url': 'Server one',
            },
            session_payload={
                'item_column': column.pk,
                'action_id': action.id,
                'target_url': 'Server one',
                'prev_url': reverse('action:run', kwargs={'pk': action.id}),
                'post_url': reverse('action:run_done'),
            })
        self.assertEqual(resp.status_code, status.HTTP_302_FOUND) 
Example 16
Project: product-definition-center   Author: product-definition-center   File: bulk_operations.py    License: MIT License 6 votes vote down vote up
def bulk_create_wrapper(func):
    @wraps(func)
    def wrapper(self, request, *args, **kwargs):
        data = request.data
        if not isinstance(data, list):
            return func(self, request, *args, **kwargs)
        result = []
        for idx, obj in enumerate(data):
            request._full_data = obj
            response = _safe_run(func, self, request, *args, **kwargs)
            if not status.is_success(response.status_code):
                return _failure_response(idx, response, data=obj)
            # Reset object in view set.
            setattr(self, 'object', None)
            result.append(response.data)
        return Response(result, status=status.HTTP_201_CREATED)
    return wrapper 
Example 17
Project: product-definition-center   Author: product-definition-center   File: bulk_operations.py    License: MIT License 6 votes vote down vote up
def bulk_destroy_impl(self, request, **kwargs):
    """
    It is possible to delete multiple items in one request. Use the `DELETE`
    method with the same url as for listing/creating objects. The request body
    should contain a list with identifiers for objects to be deleted. The
    identifier is usually the last part of the URL for deleting a single
    object.
    """
    if not isinstance(request.data, list):
        return Response(status=status.HTTP_400_BAD_REQUEST,
                        data={'detail': 'Bulk delete needs a list of identifiers.'})
    for ident in request.data:
        if not isinstance(ident, basestring) and not isinstance(ident, int):
            return Response(status=status.HTTP_400_BAD_REQUEST,
                            data={'detail': '"%s" is not a valid identifier.' % ident})
    self.kwargs.update(kwargs)
    for ident in OrderedDict.fromkeys(request.data):
        self.kwargs[self.lookup_field] = unicode(ident)
        response = _safe_run(self.destroy, request, **self.kwargs)
        if not status.is_success(response.status_code):
            return _failure_response(ident, response)
    return Response(status=status.HTTP_204_NO_CONTENT) 
Example 18
Project: product-definition-center   Author: product-definition-center   File: bulk_operations.py    License: MIT License 6 votes vote down vote up
def bulk_update_impl(self, request, **kwargs):
    """
    It is possible to update multiple objects in one request. Use the `PUT` or
    `PATCH` method with the same url as for listing/creating objects. The
    request body should contain an object, where keys are identifiers of
    objects to be modified and their values use the same format as normal
    *update*.
    """
    if not isinstance(request.data, dict):
        return Response(status=status.HTTP_400_BAD_REQUEST,
                        data={'detail': 'Bulk update needs a mapping.'})
    result = {}
    self.kwargs.update(kwargs)
    orig_data = request.data
    for ident, data in orig_data.iteritems():
        self.kwargs[self.lookup_field] = unicode(ident)
        request._full_data = data
        response = _safe_run(self.update, request, **self.kwargs)
        if not status.is_success(response.status_code):
            return _failure_response(ident, response, data=data)
        result[ident] = response.data
    return Response(status=status.HTTP_200_OK, data=result) 
Example 19
Project: longclaw   Author: JamesRamm   File: utils.py    License: MIT License 5 votes vote down vote up
def get_test(self, urlname, urlkwargs=None, params=None, success_expected=True, **kwargs):
        """ Submit a GET request and assert the response status code is 200

        Arguments:
            urlname (str): The url name to pass to the 'reverse_lazy' function
            urlkwargs (dict): The `kwargs` parameter to pass to the `reverse_lazy` function
        """
        params = params or {}
        response = self.client.get(reverse_lazy(urlname, kwargs=urlkwargs), params, **kwargs)
        if success_expected:
            self.assertTrue(status.is_success(response.status_code), response.content)
        return response 
Example 20
Project: longclaw   Author: JamesRamm   File: utils.py    License: MIT License 5 votes vote down vote up
def post_test(self, data, urlname, urlkwargs=None, success_expected=True, **kwargs):
        """ Submit a POST request and assert the response status code is 201

        Arguments:
            data (dict): The data to pass to the post request
            urlname (str): The url name to pass to the 'reverse_lazy' function
            urlkwargs (dict): The `kwargs` parameter to pass to the `reverse_lazy` function
        """
        response = self.client.post(reverse_lazy(urlname, kwargs=urlkwargs), data, **kwargs)
        if success_expected:
            self.assertTrue(status.is_success(response.status_code), response.content)
        return response 
Example 21
Project: longclaw   Author: JamesRamm   File: utils.py    License: MIT License 5 votes vote down vote up
def patch_test(self, data, urlname, urlkwargs=None, success_expected=True, **kwargs):
        """ Submit a PATCH request and assert the response status code is 200
        """
        response = self.client.patch(reverse_lazy(urlname, kwargs=urlkwargs), data, **kwargs)
        if success_expected:
            self.assertTrue(status.is_success(response.status_code), response.content)
        return response 
Example 22
Project: longclaw   Author: JamesRamm   File: utils.py    License: MIT License 5 votes vote down vote up
def put_test(self, data, urlname, urlkwargs=None, success_expected=True, **kwargs):
        response = self.client.put(reverse_lazy(urlname, kwargs=urlkwargs), data, **kwargs)
        if success_expected:
            self.assertTrue(status.is_success(response.status_code), response.content)
        return response 
Example 23
Project: longclaw   Author: JamesRamm   File: utils.py    License: MIT License 5 votes vote down vote up
def del_test(self, urlname, urlkwargs=None, success_expected=True, **kwargs):
        response = self.client.delete(reverse_lazy(urlname, kwargs=urlkwargs), **kwargs)
        if success_expected:
            self.assertTrue(status.is_success(response.status_code), response.content)
        return response 
Example 24
Project: karrot-backend   Author: yunity   File: setup_sparkpost.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setup_event_webhook(self, s):
        response = s.get('https://api.sparkpost.com/api/v1/webhooks')
        self.log_response(response)
        if not status.is_success(response.status_code):
            self.errors.append(
                'Failed to get existing event webhooks.' +
                'Check if your subaccount API key has permission to Read/Write Event Webhooks.'
            )

        webhooks = response.json()
        event_webhook_data = {
            "name": settings.SITE_NAME[:23],  # obey sparkpost name length limit
            "target": settings.HOSTNAME + "/api/webhooks/email_event/",
            "auth_type": "basic",
            "auth_credentials": {
                "username": "xxx",
                "password": settings.SPARKPOST_WEBHOOK_SECRET
            },
            "events": settings.SPARKPOST_EMAIL_EVENTS,
        }
        existing_event_webhook = None
        for w in webhooks['results']:
            if w['target'] == event_webhook_data['target']:
                existing_event_webhook = w

        if existing_event_webhook is None:
            print(
                'WARNING: creating a new event webhook for {}. '
                'Please check on sparkpost.com if there are unused ones.'.format(event_webhook_data['target'])
            )
            response = s.post('https://api.sparkpost.com/api/v1/webhooks', json=event_webhook_data)
            self.log_response(response)
            if not status.is_success(response.status_code):
                self.errors.append('Failed to create new event webhook')
        else:
            response = s.put(
                'https://api.sparkpost.com/api/v1/webhooks/' + existing_event_webhook['id'], json=event_webhook_data
            )
            self.log_response(response)
            if not status.is_success(response.status_code):
                self.errors.append('Failed to update existing event webhook') 
Example 25
Project: tfrs   Author: bcgov   File: test_credit_trade_comments.py    License: Apache License 2.0 5 votes vote down vote up
def test_put_as_gov(self):
        """
        Test Credit Trade Comment PUT with multiple valid strings
        """

        valid_strings = [
            None,
            "",
            "updated comment",
            u"update with emojis \U0001F525\U0001F525",
            "update with escape\r\n chars and \"quotes\"",
            u"zero-width\u200Bspace",
            u"Chinese characters \u4E2D\u56FD",
            "RLM \u200F and LRM \u200E!"
        ]

        for test_string in valid_strings:
            c_url = "/api/comments/1"
            test_data = {
                "comment": test_string,
                "creditTrade": 200,
                "privilegedAccess": True
            }
            response = self.clients['gov_director'].put(
                c_url,
                content_type='application/json',
                data=json.dumps(test_data)
            )
            assert status.is_success(response.status_code)

            response = self.clients['gov_director'].get(c_url)

            assert status.is_success(response.status_code)
            assert json.loads(
                response.content.decode("utf-8")
            )['comment'] == test_string 
Example 26
Project: tfrs   Author: bcgov   File: test_credit_trade_comments.py    License: Apache License 2.0 5 votes vote down vote up
def test_put_as_gov_clobber_ro(self):
        """
        Test that read-only or write-once fields cannot be written
        in Credit Trade Comment PUT requests
        """

        c_url = "/api/comments/1"
        test_data = {
            "comment": "updated comment with clobbered ro values",
            "id": 90,
            "creditTrade": None,
            "privilegedAccess": True
        }
        response = self.clients['gov_director'].put(
            c_url,
            content_type='application/json',
            data=json.dumps(test_data)
        )
        assert status.is_success(response.status_code)

        response = self.clients['gov_director'].get(c_url)
        assert status.is_success(response.status_code)
        self.assertEqual(
            json.loads(response.content.decode("utf-8"))['comment'],
            "updated comment with clobbered ro values"
        )
        self.assertEqual(
            json.loads(response.content.decode("utf-8"))['id'],
            1
        )
        self.assertEqual(
            json.loads(response.content.decode("utf-8"))['creditTrade'],
            200
        ) 
Example 27
Project: tfrs   Author: bcgov   File: test_credit_trade_comments.py    License: Apache License 2.0 5 votes vote down vote up
def test_put_as_fs_valid(self):
        """Test a valid Credit Trade Comment PUT by a Fuel supplier"""

        c_url = "/api/comments/1"
        test_data = {
            "comment": "updated comment 1",
            "creditTrade": status.HTTP_200_OK,
            "privilegedAccess": False
        }
        response = self.clients['fs_air_liquide'].put(
            c_url,
            content_type='application/json',
            data=json.dumps(test_data)
        )
        assert status.is_success(response.status_code) 
Example 28
Project: boss   Author: jhuapl-boss   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def _get(category, cls, request, *args):
    boss = cls()
    boss.request = request # needed for check_role() to work
    resp = boss.get(request, *args)
    if not status.is_success(resp.status_code):
        category_name = args[-1] if len(args) > 0 else None
        return (None, error_response(request, resp, category, category_name))
    return (resp.data, None) 
Example 29
Project: boss   Author: jhuapl-boss   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def _del(category, cls, request, *args):
    boss = cls()
    boss.request = request # needed for check_role() to work
    resp = boss.delete(request, *args)
    if not status.is_success(resp.status_code):
        return error_message(resp)
    return None 
Example 30
Project: boss   Author: jhuapl-boss   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def _post(category, cls, request, data, *args):
    boss = cls()
    boss.request = request # needed for check_role() to work
    if data:
        boss.request.data = data # simulate the DRF request object
    resp = boss.post(request, *args)
    if not status.is_success(resp.status_code):
        return error_message(resp)
    return None