Python rest_framework.status.is_success() Examples
The following are 30
code examples of rest_framework.status.is_success().
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 also want to check out all available functions/classes of the module
rest_framework.status
, or try the search function
.
Example #1
Source File: test_views_run_zip.py From ontask_b with MIT License | 6 votes |
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 #2
Source File: test_upload_logic.py From ontask_b with MIT License | 6 votes |
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 #3
Source File: test_upload_logic.py From ontask_b with MIT License | 6 votes |
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 #4
Source File: test_forms.py From ontask_b with MIT License | 6 votes |
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 #5
Source File: test_filtering.py From resolwe with Apache License 2.0 | 6 votes |
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 #6
Source File: test_upload_logic.py From ontask_b with MIT License | 6 votes |
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 #7
Source File: test_import_export.py From ontask_b with MIT License | 6 votes |
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 #8
Source File: test_crud.py From ontask_b with MIT License | 6 votes |
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 #9
Source File: test_crud.py From ontask_b with MIT License | 6 votes |
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 #10
Source File: test_crud.py From ontask_b with MIT License | 6 votes |
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 #11
Source File: test_crud.py From ontask_b with MIT License | 6 votes |
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 #12
Source File: test_crud.py From ontask_b with MIT License | 6 votes |
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 #13
Source File: test_crud.py From ontask_b with MIT License | 6 votes |
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
Source File: bulk_operations.py From product-definition-center with MIT License | 6 votes |
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 #15
Source File: bulk_operations.py From product-definition-center with MIT License | 6 votes |
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 #16
Source File: bulk_operations.py From product-definition-center with MIT License | 6 votes |
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
Source File: test_credit_trade_comments.py From tfrs with Apache License 2.0 | 6 votes |
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 #18
Source File: test_views_run.py From ontask_b with MIT License | 6 votes |
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 #19
Source File: test_logic.py From ontask_b with MIT License | 5 votes |
def test_delete(self): """Test invokation of delete table""" # Get the workflow first self.workflow = models.Workflow.objects.all().first() # JSON POST request for workflow delete resp = self.get_response( 'workflow:delete', method='POST', url_params={'wid': self.workflow.id}, is_ajax=True) self.assertTrue(status.is_success(resp.status_code)) self.assertTrue(models.Workflow.objects.count() == 0) self.workflow = None
Example #20
Source File: admin.py From django-translation-manager with Mozilla Public License 2.0 | 5 votes |
def sync_translations(self, request): if not request.user.has_perm('translation_manager.sync'): return HttpResponseRedirect(reverse("admin:translation_manager_translationentry_changelist")) url = '{}?token={}'.format( get_settings('TRANSLATIONS_SYNC_REMOTE_URL'), get_settings('TRANSLATIONS_SYNC_REMOTE_TOKEN'), ) remote_user = get_settings('TRANSLATIONS_SYNC_REMOTE_USER') remote_password = get_settings('TRANSLATIONS_SYNC_REMOTE_PASSWORD') if remote_user is not None and remote_password is not None: response = requests.get(url, verify=get_settings('TRANSLATIONS_SYNC_VERIFY_SSL'), auth=(remote_user, remote_password)) else: response = requests.get(url, verify=get_settings('TRANSLATIONS_SYNC_VERIFY_SSL')) if not is_success(response.status_code): return HttpResponseBadRequest('Wrong response from remote TRM URL') data = response.json() RemoteTranslationEntry.objects.all().delete() for language, domains in data.items(): for domain, translation_entries in domains.items(): for original, translation_entry in translation_entries.items(): try: main_entry = TranslationEntry.objects.get(language=language, original=original, domain=domain) except TranslationEntry.DoesNotExist as e: logger.debug('Missing: {} {} {}'.format(language, original, domain)) continue RemoteTranslationEntry.objects.create( translation=translation_entry['translation'], changed=translation_entry['changed'], translation_entry=main_entry ) return HttpResponseRedirect(reverse('admin:translation_manager_proxytranslationentry_changelist'))
Example #21
Source File: test_views_importexport.py From ontask_b with MIT License | 5 votes |
def test_action_import(self): """Test the import .""" # Get request resp = self.get_response( 'action:import') self.assertTrue(status.is_success(resp.status_code)) self.assertTrue('File containing a previously' in str(resp.content)) file_obj = open( os.path.join( settings.BASE_DIR(), 'lib', 'surveys', 'spq_survey.gz'), 'rb') # Post request req = self.factory.post( reverse('action:import'), {'upload_file': file_obj}) req.META['HTTP_ACCEPT_ENCODING'] = 'gzip, deflate' req.FILES['upload_file'].content_type = 'application/x-gzip' req = self.add_middleware(req) resp = action_import(req) self.assertEqual(resp.status_code, status.HTTP_302_FOUND) # Fails if the action is not there self.workflow.actions.get(name='SPQ')
Example #22
Source File: test_views_importexport.py From ontask_b with MIT License | 5 votes |
def test_export_ask(self): """Test the export views.""" action = self.workflow.actions.get(name='Detecting age') resp = self.get_response( 'workflow:export_list_ask', {'wid': action.workflow.id}) self.assertTrue(status.is_success(resp.status_code)) self.assertTrue(action.name in str(resp.content)) # Get export done # BROKEN!!! resp = self.get_response( 'workflow:export_list_ask', {'wid': action.workflow.id}, method='POST', req_params={'select_0': True}) self.assertTrue(status.is_success(resp.status_code)) self.assertTrue('Your download will start ' in str(resp.content)) # Get export download resp = self.get_response( 'action:export', {'pklist': str(action.id)}) self.assertTrue(status.is_success(resp.status_code)) self.assertEqual(resp['Content-Type'], 'application/octet-stream')
Example #23
Source File: test_views_run.py From ontask_b with MIT License | 5 votes |
def test_serve_survey(self): """Test the serve_action view.""" action = self.workflow.actions.get(name='Check registration') action.serve_enabled = True action.save(update_fields=['serve_enabled']) resp = self.get_response( 'action:serve', {'action_id': action.id}) self.assertTrue(status.is_success(resp.status_code)) self.assertTrue('id="action-row-datainput"' in str(resp.content)) self.assertTrue('csrfmiddlewaretoken' in str(resp.content))
Example #24
Source File: test_views_run.py From ontask_b with MIT License | 5 votes |
def test_serve_action(self): """Test the serve_action view.""" action = self.workflow.actions.get(name='simple action') action.serve_enabled = True action.save(update_fields=['serve_enabled']) resp = self.get_response( 'action:serve', {'action_id': action.id}) self.assertTrue(status.is_success(resp.status_code)) self.assertTrue('Oct. 10, 2017, 10:03 p.m.' in str(resp.content))
Example #25
Source File: test_views_run.py From ontask_b with MIT License | 5 votes |
def test_run_canvas_email_done(self): """Test last step of sending canvas emails.""" user = get_user_model().objects.get(email=self.user_email) utoken = models.OAuthUserToken( user=user, instance_name='Server one', access_token='bogus token', refresh_token=r'not needed', valid_until=timezone.now() + timedelta(days=1000000), ) utoken.save() action = self.workflow.actions.get(name='Initial motivation') column = action.workflow.columns.get(name='email') settings.EXECUTE_ACTION_JSON_TRANSFER = False # POST -> redirect to item filter resp = self.get_response( 'action:run_done', method='POST', 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'), 'subject': 'Email subject', 'export_wf': False}) self.assertTrue(status.is_success(resp.status_code))
Example #26
Source File: test_views_run.py From ontask_b with MIT License | 5 votes |
def test_run_json_action_no_filter(self): """Test JSON action using the filter execution.""" OnTaskSharedState.json_outbox = None action = self.workflow.actions.get(name='Send JSON to remote server') column = action.workflow.columns.get(name='email') # Step 1 invoke the form resp = self.get_response( 'action:run', url_params={'pk': action.id}) payload = SessionPayload.get_session_payload(self.last_request) self.assertTrue(action.id == payload['action_id']) self.assertTrue( payload['prev_url'] == reverse( 'action:run', kwargs={'pk': action.id})) self.assertTrue(payload['post_url'] == reverse('action:run_done')) self.assertTrue('post_url' in payload.keys()) self.assertTrue(status.is_success(resp.status_code)) # Step 2 send POST resp = self.get_response( 'action:run', url_params={'pk': action.id}, method='POST', req_params={ 'item_column': column.pk, 'token': 'fake token'}) payload = SessionPayload.get_session_payload(self.last_request) self.assertTrue(payload == {}) self.assertTrue( len(OnTaskSharedState.json_outbox) == action.get_rows_selected()) self._verify_content() self.assertTrue(status.is_success(resp.status_code))
Example #27
Source File: test_views_run.py From ontask_b with MIT License | 5 votes |
def test_run_json_report_action(self): """Test JSON action using the filter execution.""" OnTaskSharedState.json_outbox = None action = self.workflow.actions.get(name='Send JSON report') # Step 1 invoke the form resp = self.get_response( 'action:run', url_params={'pk': action.id}) payload = SessionPayload.get_session_payload(self.last_request) self.assertTrue(action.id == payload['action_id']) self.assertTrue( payload['prev_url'] == reverse( 'action:run', kwargs={'pk': action.id})) self.assertTrue(payload['post_url'] == reverse('action:run_done')) self.assertTrue('post_url' in payload.keys()) self.assertTrue(status.is_success(resp.status_code)) # Step 2 send POST resp = self.get_response( 'action:run', url_params={'pk': action.id}, method='POST', req_params={ 'token': 'fake token'}) payload = SessionPayload.get_session_payload(self.last_request) self.assertTrue(payload == {}) self.assertTrue(len(OnTaskSharedState.json_outbox) == 1) self.assertTrue( OnTaskSharedState.json_outbox[0]['auth'] == 'Bearer fake token') self.assertTrue(status.is_success(resp.status_code))
Example #28
Source File: test_sqlconn.py From ontask_b with MIT License | 5 votes |
def test_sql_views_instructor(self): """Test the view to filter items.""" resp = self.get_response('connection:sqlconns_index') self.assertTrue(status.is_success(resp.status_code))
Example #29
Source File: test_sqlconn.py From ontask_b with MIT License | 5 votes |
def test_sql_run(self): """Execute the RUN step.""" sql_conn = models.SQLConnection.objects.get(pk=1) self.assertIsNotNone(sql_conn) # Modify the item so that it is able to access the DB sql_conn.conn_type = 'postgresql' sql_conn.db_name = settings.DATABASE_URL['NAME'] sql_conn.db_user = settings.DATABASE_URL['USER'] sql_conn.db_password = settings.DATABASE_URL['PASSWORD'] sql_conn.db_port = settings.DATABASE_URL['PORT'] sql_conn.db_host = settings.DATABASE_URL['HOST'] sql_conn.db_table = '__ONTASK_WORKFLOW_TABLE_1' sql_conn.save() # Load the first step for the sql upload form (GET) resp = self.get_response( 'dataops:sqlupload_start', {'pk': sql_conn.id}) self.assertTrue(status.is_success(resp.status_code)) self.assertIn('Establish a SQL connection', str(resp.content)) # Load the first step for the sql upload form (POST) resp = self.get_response( 'dataops:sqlupload_start', {'pk': sql_conn.id}, method='POST', req_params={'db_password': 'boguspwd'}) self.assertEqual(resp.status_code, status.HTTP_302_FOUND) self.assertEqual(resp.url, reverse('dataops:upload_s2'))
Example #30
Source File: apidoc.py From ontask_b with MIT License | 5 votes |
def test_api_doc(self): """Test the availability of the API doc.""" resp = self.get_response('ontask-api-doc') resp.render() self.assertTrue(status.is_success(resp.status_code)) self.assertIn('OnTask API', str(resp.content))