def test_resource_schema_field_create_complex(self): '''More complex test of creating a schema field. Pass all recommended params and test they all get created correctly. ''' resource = factories.Resource(dataset=factories.Dataset()) # The field attributes we will pass. name = 'test-field' title = 'Test Field' description = 'Just a simple test field.' type_ = 'string' format_ = 'foobar' helpers.call_action('resource_schema_field_create', resource_id=resource['id'], index=0, name=name, title=title, description=description, type=type_, format=format_) schema = helpers.call_action('resource_schema_show', resource_id=resource['id']) assert 'fields' in schema fields = schema['fields'] assert len(fields) == 1 field = fields[0] assert field['name'] == name assert field['title'] == title assert field['description'] == description assert field['type'] == type_ assert field['format'] == format_
def test_resource_schema_field_create_with_custom_attributes(self): '''Test that custom schema field attributes are saved correctly.''' resource = factories.Resource(dataset=factories.Dataset()) # The field attributes we will pass. name = 'test-field' title = 'Test Field' custom_attribute_1 = 'foo' custom_attribute_2 = 'bar' helpers.call_action('resource_schema_field_create', resource_id=resource['id'], index=0, name=name, title=title, custom_attribute_1=custom_attribute_1, custom_attribute_2=custom_attribute_2) schema = helpers.call_action('resource_schema_show', resource_id=resource['id']) assert 'fields' in schema fields = schema['fields'] assert len(fields) == 1 field = fields[0] assert field['name'] == name assert field['title'] == title assert field['custom_attribute_1'] == custom_attribute_1 assert field['custom_attribute_2'] == custom_attribute_2
def test_resource_schema_field_create_non_string_custom_attribute(self): '''Non-string custom attribute values should be converted to strings. ''' resource = factories.Resource(dataset=factories.Dataset()) # The field attributes we will pass. name = 'test-field' title = 'Test Field' custom_attribute_1 = 145 custom_attribute_2 = True helpers.call_action('resource_schema_field_create', resource_id=resource['id'], index=0, name=name, title=title, custom_attribute_1=custom_attribute_1, custom_attribute_2=custom_attribute_2) schema = helpers.call_action('resource_schema_show', resource_id=resource['id']) assert 'fields' in schema fields = schema['fields'] assert len(fields) == 1 field = fields[0] assert field['custom_attribute_1'] == '145' assert field['custom_attribute_2'] == 'True'
def setup(self): self.ec_dict = { u'About': u'Description', u'DisplayName': u'', u'Email': u'', u'FirstName': u'', u'IsRegistered': False, u'LastName': u'', u'OrganisationId': u'de0f2f6e-58ca-4a7b-95b1-7fd6e8df1f69', u'Roles': [u'OrganisationEditor'], u'UserId': u'dcfb1b12-fe52-4d71-9aad-c60fc4c6952c', u'UserName': u'johndoe' } self.org_owner = helpers.call_action('user_create', name='org_owner', email='*****@*****.**', password='******') self.test_org = helpers.call_action('organization_create', context={ 'user': '******', 'local_action': True, }, name='test_org', id=u'de0f2f6e-58ca-4a7b-95b1-7fd6e8df1f69')
def test_add_default_views_to_resource(self): # New resources have no views dataset_dict = factories.Dataset() resource_dict = factories.Resource( package_id=dataset_dict['id'], url='http://some.image.png', format='png', ) # Change default views config setting config['ckan.views.default_views'] = 'image_view' context = { 'user': helpers.call_action('get_site_user')['name'] } created_views = helpers.call_action( 'resource_create_default_resource_views', context, resource=resource_dict, package=dataset_dict) assert_equals(len(created_views), 1) assert_equals(created_views[0]['view_type'], 'image_view')
def test_primary_key_is_on_page_list(self): dataset, resource, schema = self._create_resource() helpers.call_action( 'resource_schema_pkey_create', resource_id=resource['id'], pkey=["playerID", "teamID"] ) response = self.app.get( toolkit.url_for(controller='package', action='resource_read', id=dataset['id'], resource_id=resource['id'])) soup = response.html nose.tools.assert_true(soup.find(text='Primary key')) pkey = soup.find(id='primary-key') pkeys = pkey.find_all('li') nose.tools.assert_true( pkeys[0].a.attrs['href'], '/package/{0}/file/{1}/schema/0'.format( dataset['id'], resource['id']) ) nose.tools.assert_true(pkeys[0].a.text, 'playerID') nose.tools.assert_true( pkeys[1].a.attrs['href'], '/package/{0}/file/{1}/schema/0'.format( dataset['id'], resource['id']) ) nose.tools.assert_true(pkeys[1].a.text, 'teamID')
def test_update_does_not_remove_users(self, mock_request): old_members = helpers.call_action('member_list', id=self.test_org['id']) content = { 'MetadataResultSet': [{ "Id": self.test_org['id'], "Title": "Glasgow City Council", "CreatedTime": "2014-05-21T06:06:18.353", "ModifiedTime": "2014-05-21T06:06:18.353" }] } mock_request.return_value = mock.Mock( status_code=200, content=json.dumps(content), **{ 'raise_for_status.return_value': None, 'json.return_value': content, } ) site_user = helpers.call_action('get_site_user') handle_organization_update( context={ 'model': model, 'ignore_auth': True, 'local_action': True, 'user': site_user['name'] }, audit={'CustomProperties':{'OrganisationId': self.test_org['id']}}, harvest_object=None, ) members = helpers.call_action('member_list', id=self.test_org['id']) nt.assert_equals(old_members, members)
def test_add_default_views_to_dataset_resources(self): # New resources have no views dataset_dict = factories.Dataset(resources=[ { 'url': 'http://some.image.png', 'format': 'png', 'name': 'Image 1', }, { 'url': 'http://some.image.png', 'format': 'png', 'name': 'Image 2', }, ]) # Change default views config setting config['ckan.views.default_views'] = 'image_view' context = { 'user': helpers.call_action('get_site_user')['name'] } created_views = helpers.call_action( 'package_create_default_resource_views', context, package=dataset_dict) assert_equals(len(created_views), 2) assert_equals(created_views[0]['view_type'], 'image_view') assert_equals(created_views[1]['view_type'], 'image_view')
def test_member_create(self): '''Test that the member_create API is also blocked. Most of the tests above use organization_member_create. ''' organization_admin = factories.User() organization = factories.Organization(user=organization_admin) editor_1 = factories.User() helpers.call_action('member_create', context={'user': organization_admin['name']}, id=organization['id'], object=editor_1['id'], object_type='user', capacity='editor') editor_2 = factories.User() helpers.call_action('member_create', context={'user': organization_admin['name']}, id=organization['id'], object=editor_2['id'], object_type='user', capacity='editor') # We should not be able to create another editor. editor_3 = factories.User() url = toolkit.url_for(controller='api', logic_function='member_create', action='action', ver=3) data_dict = {'id': organization['id'], 'object': editor_3['id'], 'object_type': 'user', 'capacity': 'editor'} response = self.app.post_json(url, data_dict, extra_environ={'REMOTE_USER': str(organization_admin['name'])}, status=403) # Test that we were denied for the right reason. # (This catches mistakes in the tests, for example if the test didn't # pass REMOTE_USER we would get a 403 but for a different reason.) assert response.json['error']['message'] == ("Access denied: You're " "only allowed to have 3 " "editors")
def test_dataset_showcase_page_lists_showcases_two_associations(self): ''' Two showcases are listed for dataset with two showcase associations. ''' app = self._get_test_app() sysadmin = factories.Sysadmin() dataset = factories.Dataset(name='my-dataset') showcase_one = factories.Dataset(name='my-first-showcase', type='showcase') showcase_two = factories.Dataset(name='my-second-showcase', type='showcase') factories.Dataset(name='my-third-showcase', type='showcase') context = {'user': sysadmin['name']} helpers.call_action('ckanext_showcase_package_association_create', context=context, package_id=dataset['id'], showcase_id=showcase_one['id']) helpers.call_action('ckanext_showcase_package_association_create', context=context, package_id=dataset['id'], showcase_id=showcase_two['id']) response = app.get( url=url_for(controller='ckanext.showcase.controller:ShowcaseController', action='dataset_showcase_list', id=dataset['id']) ) nosetools.assert_equal(len(response.html.select('li.media-item')), 2) nosetools.assert_true('my-first-showcase' in response) nosetools.assert_true('my-second-showcase' in response) nosetools.assert_true('my-third-showcase' not in response)
def test_dataset_showcase_page_add_to_showcase_dropdown_list(self): ''' Add to showcase dropdown only lists showcases that aren't already associated with dataset. ''' app = self._get_test_app() sysadmin = factories.Sysadmin() dataset = factories.Dataset(name='my-dataset') showcase_one = factories.Dataset(name='my-first-showcase', type='showcase') showcase_two = factories.Dataset(name='my-second-showcase', type='showcase') showcase_three = factories.Dataset(name='my-third-showcase', type='showcase') context = {'user': sysadmin['name']} helpers.call_action('ckanext_showcase_package_association_create', context=context, package_id=dataset['id'], showcase_id=showcase_one['id']) response = app.get( url=url_for(controller='ckanext.showcase.controller:ShowcaseController', action='dataset_showcase_list', id=dataset['id']), extra_environ={'REMOTE_USER': str(sysadmin['name'])} ) showcase_add_form = response.forms['showcase-add'] showcase_added_options = [value for (value, _) in showcase_add_form['showcase_added'].options] nosetools.assert_true(showcase_one['id'] not in showcase_added_options) nosetools.assert_true(showcase_two['id'] in showcase_added_options) nosetools.assert_true(showcase_three['id'] in showcase_added_options)
def test_resource_schema_field_update_does_not_affect_other_fields(self): '''Updating a resource schema field should not affect any of the resource's other fields. ''' resource_fields = { 'url': 'http://www.example_resource.com', 'description': 'Just a test resource', 'format': 'CSV', 'hash': 'xxx', 'name': 'test-resource', 'mimetype': 'text/csv', 'size': '10', } resource = factories.Resource(dataset=factories.Dataset(), **resource_fields) field = helpers.call_action('resource_schema_field_create', resource_id=resource['id'], index=0, name='foo', title='bar') field['name'] = 'bar' field['title'] = 'foo' helpers.call_action('resource_schema_field_update', resource_id=resource['id'], **field) resource = helpers.call_action('resource_show', id=resource['id']) for key, value in resource_fields.items(): assert resource[key] == value, (key, value)
def test_resource_schema_field_update_many(self): '''Test updating many field attributes at once. Pass all recommended params and test they all get updated correctly. ''' original_attributes = { 'name': 'original-name', 'title': 'original-title', 'description': 'original-description', 'type': 'string', 'format': 'original-format', } new_attributes = { 'name': 'updated-name', 'title': 'updated-title', 'description': 'updated-description', 'type': 'any', 'format': 'updated-format', } resource = factories.Resource(dataset=factories.Dataset()) helpers.call_action('resource_schema_field_create', resource_id=resource['id'], index=0, **original_attributes) helpers.call_action('resource_schema_field_update', resource_id=resource['id'], index=0, **new_attributes) field = helpers.call_action('resource_schema_field_show', resource_id=resource['id'], index=0) for key, value in new_attributes.items(): assert field[key] == value, "Attribute wasn't updated: " + key
def _run_jobs(self, harvest_source_id=None): try: h.call_action('harvest_jobs_run', {}, source_id=harvest_source_id) except Exception, e: if (str(e) == 'There are no new harvesting jobs'): pass
def test_dataset_showcase_page_remove_showcase_button_submit(self): ''' Submitting 'Remove' form with selected showcase value deletes a sc/pkg association. ''' app = self._get_test_app() sysadmin = factories.Sysadmin() dataset = factories.Dataset(name='my-dataset') showcase_one = factories.Dataset(name='my-first-showcase', type='showcase') context = {'user': sysadmin['name']} helpers.call_action('ckanext_showcase_package_association_create', context=context, package_id=dataset['id'], showcase_id=showcase_one['id']) nosetools.assert_equal(model.Session.query(ShowcasePackageAssociation).count(), 1) env = {'REMOTE_USER': sysadmin['name'].encode('ascii')} response = app.get( url=url_for(controller='ckanext.showcase.controller:ShowcaseController', action='dataset_showcase_list', id=dataset['id']), extra_environ=env ) # Submit the remove form. form = response.forms[1] nosetools.assert_equal(form['remove_showcase_id'].value, showcase_one['id']) showcase_remove_response = submit_and_follow(app, form, env) # returns to the correct page nosetools.assert_equal(showcase_remove_response.request.path, "/dataset/showcases/my-dataset") # the association is deleted nosetools.assert_equal(model.Session.query(ShowcasePackageAssociation).count(), 0)
def test_not_authorized_if_user_has_no_permissions_on_dataset(self): org = factories.Organization() user = factories.User() member = {'username': user['name'], 'role': 'admin', 'id': org['id']} helpers.call_action('organization_member_create', **member) user_2 = factories.User() dataset = factories.Dataset(owner_org=org['id']) resource = factories.Resource(package_id=dataset['id']) resource_view = {'resource_id': resource['id'], 'title': u'Resource View', 'view_type': u'image_view', 'image_url': 'url'} context = {'user': user_2['name'], 'model': core_model} nose.tools.assert_raises(logic.NotAuthorized, helpers.call_auth, 'resource_view_create', context=context, **resource_view)
def test_invalid_permission(self): ''' organization_list_for_user() should return an empty list if passed a non-existent or invalid permission. Note that we test this with a user who is an editor of one organization. If the user was an admin of the organization then it would return that organization - admins have all permissions, including permissions that don't exist. ''' user = factories.User() context = {'user': user['name']} organization = factories.Organization() factories.Organization() helpers.call_action('member_create', id=organization['id'], object=user['id'], object_type='user', capacity='editor') for permission in ('', ' ', 'foo', 27.3, 5, True, False, None): organizations = helpers.call_action('organization_list_for_user', permission=permission, context=context) assert organizations == []
def test_resource_schema_field_create_when_schema_already_exists(self): '''Test creating a new schema field in a schema that already exists. (The tests above have been testing with resources that had no schema to begin with.) ''' resource = factories.Resource(dataset=factories.Dataset()) helpers.call_action('resource_schema_field_create', resource_id=resource['id'], index=0, name='foo') # The field attributes we will pass. name = 'test-field' title = 'Test Field' helpers.call_action('resource_schema_field_create', resource_id=resource['id'], index=1, name=name, title=title) schema = helpers.call_action('resource_schema_show', resource_id=resource['id']) assert 'fields' in schema fields = schema['fields'] assert len(fields) == 2 assert fields[0]['name'] == 'foo' assert fields[1]['name'] == name assert fields[1]['title'] == title
def test_resource_view_list_reorder(self): resource_view_1 = factories.ResourceView(title='View 1') resource_id = resource_view_1['resource_id'] resource_view_2 = factories.ResourceView(resource_id=resource_id, title='View 2') resource_view_list = helpers.call_action('resource_view_list', id=resource_id) assert_equals(resource_view_list[0]['title'], 'View 1') assert_equals(resource_view_list[1]['title'], 'View 2') # Reorder views result = helpers.call_action('resource_view_reorder', id=resource_id, order=[resource_view_2['id'], resource_view_1['id']]) assert_equals(result['order'], [resource_view_2['id'], resource_view_1['id']]) resource_view_list = helpers.call_action('resource_view_list', id=resource_id) assert_equals(resource_view_list[0]['title'], 'View 2') assert_equals(resource_view_list[1]['title'], 'View 1')
def test_c2_delete_translation_resource_column(self): resource = self._get_initial_datastore(package_data.get('name')) context = self.get_context() resource_en_id = json.loads(resource.get('has_translations')).get('en') #resource_el = p.toolkit.get_action('datastore_search')(context, {'id':resource_el_id}) # Should delete translation resource correctly trans_data = [{ 'resource_id': resource.get('id'), 'language': 'en', 'column_name': 'name' }, # should not change sth but not fail either { 'resource_id': resource.get('id'), 'language': 'en', 'column_name': 'name' }, ] for d in trans_data: pprint.pprint(helpers.call_action('resource_translation_delete', context=context, **d)) res_en = helpers.call_action('datastore_search', context=context, resource_id=resource_en_id) print "RESULT" pprint.pprint(res_en) for fld in res_en.get('fields'): # assert deleted column does not exist in resource assert not fld.get('id') == 'name'
def test_default_views_created_on_resource_update(self): dataset_dict = factories.Dataset( resources=[{ 'url': 'http://not.for.viewing', 'format': 'xxx', }] ) resource_id = dataset_dict['resources'][0]['id'] views_list = helpers.call_action('resource_view_list', id=resource_id) eq_(len(views_list), 0) resource_dict = { 'id': resource_id, 'package_id': dataset_dict['id'], 'url': 'http://some.image.png', 'format': 'png', } updated_resource_dict = helpers.call_action('resource_update', **resource_dict) views_list = helpers.call_action('resource_view_list', id=updated_resource_dict['id']) eq_(len(views_list), 1) eq_(views_list[0]['view_type'], 'image_view')
def test_all_params_work_with_fields_with_whitespaces(self): resource = factories.Resource() data = { 'resource_id': resource['id'], 'force': True, 'records': [ {'the year': 2014}, {'the year': 2013}, ], } result = helpers.call_action('datastore_create', **data) search_data = { 'resource_id': resource['id'], 'fields': 'the year', 'sort': 'the year', 'filters': { 'the year': 2013 }, 'q': { 'the year': '2013' }, } result = helpers.call_action('datastore_search', **search_data) result_years = [r['the year'] for r in result['records']] assert_equals(result_years, [2013])
def test_user_get(self): user = factories.User() ## auth_ignored got_user = helpers.call_action("user_show", id=user["id"]) assert "password" not in got_user assert "reset_key" not in got_user assert "apikey" not in got_user assert "email" not in got_user got_user = helpers.call_action("user_show", context={"keep_email": True}, id=user["id"]) assert got_user["email"] == user["email"] assert "apikey" not in got_user assert "password" not in got_user assert "reset_key" not in got_user got_user = helpers.call_action("user_show", context={"keep_apikey": True}, id=user["id"]) assert "email" not in got_user assert got_user["apikey"] == user["apikey"] assert "password" not in got_user assert "reset_key" not in got_user sysadmin = factories.User(sysadmin=True) got_user = helpers.call_action("user_show", context={"user": sysadmin["name"]}, id=user["id"]) assert got_user["email"] == user["email"] assert got_user["apikey"] == user["apikey"] assert "password" not in got_user assert "reset_key" not in got_user
def test_when_user_is_an_admin_of_one_organization(self): """ When the user is an admin of one organization organization_list_for_user() should return a list of just that one organization. """ user = factories.User() context = {'user': user['name']} organization = factories.Organization() # Create a second organization just so we can test that it does not get # returned. factories.Organization() helpers.call_action('member_create', id=organization['id'], object=user['id'], object_type='user', capacity='admin') organizations = helpers.call_action('organization_list_for_user', context=context) assert len(organizations) == 1 assert organizations[0]['id'] == organization['id']
def test_when_user_is_an_admin_of_three_organizations(self): """ When the user is an admin of three organizations organization_list_for_user() should return a list of all three organizations. """ user = factories.User() context = {"user": user["name"]} organization_1 = factories.Organization() organization_2 = factories.Organization() organization_3 = factories.Organization() # Create a second organization just so we can test that it does not get # returned. factories.Organization() # Make the user an admin of all three organizations: for organization in (organization_1, organization_2, organization_3): helpers.call_action( "member_create", id=organization["id"], object=user["id"], object_type="user", capacity="admin" ) organizations = helpers.call_action("organization_list_for_user", context=context) assert len(organizations) == 3 ids = [organization["id"] for organization in organizations] for organization in (organization_1, organization_2, organization_3): assert organization["id"] in ids
def test_b2_update_translation_resource(self): resource = self._get_initial_datastore(package_data.get('name')) context = self.get_context() # Should create translation resource correctly res = helpers.call_action('resource_show', context=context, id=resource.get('id')) res_el = helpers.call_action('resource_show', context=context, id=json.loads(res.get('has_translations')).get('el')) assert res_el.get('id') assert res_el.get('translation_parent_id') == res.get('id') # Update same column twice to make sure no conflicts arise trans_data = [{ 'resource_id': res_el.get('id'), 'mode':'manual', 'column_name':'address', }, { 'resource_id': res_el.get('id'), 'mode':'manual', 'column_name':'address', }] for d in trans_data: helpers.call_action('translate_resource_update', context=context, **d) updated_ds = helpers.call_action('datastore_search', context=context, id=res_el.get('id')) assert updated_ds.get('resource_id') == res_el.get('id') assert updated_ds.get('total') == 3
def setup(self): self.ec_dict = { "UserName": "******", "About": "", "DisplayName": "", "Roles": [ "OrganisationAdmin" ], "FirstName": "", "LastName": "", "UserId": "e350cb61-ed72-4335-b915-7617b5e931f0", "IsRegistered": False, "OrganisationId": "f8c84440-24c6-40ce-a0b0-eafacd15ac59", "Email": "" } self.org_owner = helpers.call_action('user_create', name='org_owner', email='*****@*****.**', password='******') self.test_org = helpers.call_action('organization_create', context={ 'user': '******', 'local_action': True, }, name='test_org', id=u'f8c84440-24c6-40ce-a0b0-eafacd15ac59')
def setup(self): self.ec_dict = { "UserName": "******", "About": "", "DisplayName": "", "Roles": [ "ExternalService" ], "FirstName": "", "LastName": "", "UserId": "e350cb61-ed72-4335-b915-7617b5e931f0", "IsRegistered": False, "OrganisationId": None, "Email": "" } self.org_owner = helpers.call_action('user_create', name='org_owner', email='*****@*****.**', password='******') self.test_org = helpers.call_action('organization_create', context={ 'user': '******', 'local_action': True, }, name='test_org', id=u'de0f2f6e-58ca-4a7b-95b1-7fd6e8df1f69')
def test_user_update_name(self): '''Test that updating a user's name works successfully.''' # The canonical form of a test has four steps: # 1. Setup any preconditions needed for the test. # 2. Call the function that's being tested, once only. # 3. Make assertions about the return value and/or side-effects of # of the function that's being tested. # 4. Do nothing else! # 1. Setup. user = factories.User() # 2. Call the function that's being tested, once only. # FIXME we have to pass the email address and password to user_update # even though we're not updating those fields, otherwise validation # fails. helpers.call_action('user_update', id=user['name'], email=user['email'], password=factories.User.attributes()['password'], name='updated', ) # 3. Make assertions about the return value and/or side-effects. updated_user = helpers.call_action('user_show', id=user['id']) # Note that we check just the field we were trying to update, not the # entire dict, only assert what we're actually testing. assert updated_user['name'] == 'updated'
def test_user_update_activity_stream(self): """Test that the right activity is emitted when updating a user.""" user = factories.User() before = datetime.datetime.now() # FIXME we have to pass the email address and password to user_update # even though we're not updating those fields, otherwise validation # fails. helpers.call_action( "user_update", id=user["name"], email=user["email"], password=factories.User.attributes()["password"], name="updated", ) activity_stream = helpers.call_action("user_activity_list", id=user["id"]) latest_activity = activity_stream[0] assert latest_activity["activity_type"] == "changed user" assert latest_activity["object_id"] == user["id"] assert latest_activity["user_id"] == user["id"] after = datetime.datetime.now() timestamp = datetime_from_string(latest_activity["timestamp"]) assert timestamp >= before and timestamp <= after
def test_user_update_with_empty_password(self): '''If an empty password is passed to user_update, nothing should happen. No error (e.g. a validation error) is raised, but the password is not changed either. ''' user_dict = factories.User.attributes() original_password = user_dict['password'] user_dict = factories.User(**user_dict) user_dict['password'] = '' helpers.call_action('user_update', **user_dict) import ckan.model as model updated_user = model.User.get(user_dict['id']) assert updated_user.validate_password(original_password)
def test_resource_schema_field_update_name(self): '''Simple test that updating a schema field's name works.''' resource = factories.Resource(dataset=factories.Dataset()) field = helpers.call_action('resource_schema_field_create', resource_id=resource['id'], index=0, name='original-name') field['name'] = 'new-name' helpers.call_action('resource_schema_field_update', resource_id=resource['id'], **field) field = helpers.call_action('resource_schema_field_show', resource_id=resource['id'], index=0) assert field == {'index': 0, 'name': 'new-name'}
def test_organization_show(self): org = factories.Organization() org_dict = helpers.call_action('organization_show', id=org['id']) # FIXME: Should this be returned by organization_create? org_dict.pop('num_followers', None) assert org_dict == org
def test_package_search_on_resource_name(self): ''' package_search() should allow searching on resource name field. ''' resource_name = 'resource_abc' package = factories.Resource(name=resource_name) search_result = helpers.call_action('package_search', q='resource_abc') eq(search_result['results'][0]['resources'][0]['name'], resource_name)
def test_showcase_admin_remove_deletes_showcase_admin_user(self): ''' Calling ckanext_showcase_admin_remove deletes ShowcaseAdmin object. ''' user = factories.User() helpers.call_action('ckanext_showcase_admin_add', context={}, username=user['name']) # There's a ShowcaseAdmin obj nosetools.assert_equal(model.Session.query(ShowcaseAdmin).count(), 1) helpers.call_action('ckanext_showcase_admin_remove', context={}, username=user['name']) # There's no ShowcaseAdmin obj nosetools.assert_equal(model.Session.query(ShowcaseAdmin).count(), 0) nosetools.assert_equal(ShowcaseAdmin.get_showcase_admin_ids(), [])
def test_datastore_delete_can_create_custom_filters(self): records = [ {'age': 20}, {'age': 30}, {'age': 40} ] resource = self._create_datastore_resource(records) filters = {'age_between': [25, 35]} helpers.call_action('datastore_delete', resource_id=resource['id'], force=True, filters=filters) result = helpers.call_action('datastore_search', resource_id=resource['id']) new_records_ages = [r['age'] for r in result['records']] new_records_ages.sort() assert_equals(new_records_ages, [20, 40])
def test_group_show(self): group = factories.Group() group_dict = helpers.call_action('group_show', id=group['id']) # FIXME: Should this be returned by group_create? group_dict.pop('num_followers', None) assert group_dict == group
def test_group_list(self): group1 = factories.Group() group2 = factories.Group() group_list = helpers.call_action('group_list') assert (sorted(group_list) == sorted( [g['name'] for g in [group1, group2]]))
def test_help_show_basic(self): function_name = 'package_search' result = helpers.call_action('help_show', name=function_name) function = logic.get_action(function_name) eq(result, function.__doc__)
def test_group_list_extras_returned(self): group = factories.Group(extras=[{'key': 'key1', 'value': 'val1'}]) group_list = helpers.call_action('group_list', all_fields=True, include_extras=True) eq(group_list[0]['extras'], group['extras']) eq(group_list[0]['extras'][0]['key'], 'key1')
def _create(cls, target_class, *args, **kwargs): if args: assert False, "Positional args aren't supported, use keyword args." context = {'user': _get_action_user_name(kwargs)} related_dict = helpers.call_action('related_create', context=context, **kwargs) return related_dict
def _create(cls, target_class, *args, **kwargs): if args: assert False, "Positional args aren't supported, use keyword args." context = {'user': factories._get_action_user_name(kwargs)} issue_comment_dict = helpers.call_action('issue_comment_create', context=context, **kwargs) return issue_comment_dict
def test_organization_list(self): org1 = factories.Organization() org2 = factories.Organization() org_list = helpers.call_action('organization_list') assert (sorted(org_list) == sorted([g['name'] for g in [org1, org2]]))
def test_resource_schema_show(self): '''resource_schema_show should return the resource's schema.''' resource, field = _create_resource_and_field() schema = helpers.call_action('resource_schema_show', resource_id=resource['id']) assert schema == {'fields': [field]}
def test_group_show_does_not_show_private_datasets(self): '''group_show() should never show private datasets. If a dataset is a private member of an organization and also happens to be a member of a group, group_show() should not return the dataset as part of the group dict, even if the user calling group_show() is a member or admin of the group or the organization or is a sysadmin. ''' org_member = factories.User() org = factories.Organization(user=org_member) private_dataset = factories.Dataset(user=org_member, owner_org=org['name'], private=True) group = factories.Group() # Add the private dataset to the group. helpers.call_action('member_create', id=group['id'], object=private_dataset['id'], object_type='package', capacity='public') # Create a member user and an admin user of the group. group_member = factories.User() helpers.call_action('member_create', id=group['id'], object=group_member['id'], object_type='user', capacity='member') group_admin = factories.User() helpers.call_action('member_create', id=group['id'], object=group_admin['id'], object_type='user', capacity='admin') # Create a user who isn't a member of any group or organization. non_member = factories.User() sysadmin = factories.Sysadmin() # None of the users should see the dataset when they call group_show(). for user in (org_member, group_member, group_admin, non_member, sysadmin, None): if user is None: context = None # No user logged-in. else: context = {'user': user['name']} group = helpers.call_action('group_show', id=group['id'], context=context) assert private_dataset['id'] not in [ dataset['id'] for dataset in group['packages'] ], ("group_show() should never show private datasets")
def test_not_authorized_if_user_has_no_permissions_on_dataset(self): org = factories.Organization() user = factories.User() member = {'username': user['name'], 'role': 'admin', 'id': org['id']} helpers.call_action('organization_member_create', **member) user_2 = factories.User() dataset = factories.Dataset(owner_org=org['id']) context = {'user': user_2['name'], 'model': core_model} nose.tools.assert_raises(logic.NotAuthorized, helpers.call_auth, 'package_create_default_resource_views', context=context, package=dataset)
def test_resource_update_with_missing_name(self): '''If a user updates a resource and does not pass a name field, the name should be changed to the name of the resource's uploaded file. ''' user = factories.User() dataset = factories.Dataset(user=user) api = ckanapi.TestAppCKAN(self.app, apikey=user['apikey']) resource = api.action.resource_create( package_id=dataset['id'], name='test-resource', upload=custom_helpers.get_csv_file( 'test-data/lahmans-baseball-database/AllstarFull.csv')) del resource['name'] helpers.call_action('resource_update', **resource) resource = helpers.call_action('resource_show', id=resource['id']) assert resource['name'] == 'AllstarFull.csv'
def test_resource_view_create(self): context = {} params = self._default_resource_view_attributes() result = helpers.call_action('resource_view_create', context, **params) result.pop('id') result.pop('package_id') assert_equals(params, result)
def test_filterable_views_converts_filter_fields_and_values_to_list( self, datapreview_mock): self._configure_datapreview_to_return_filterable_view(datapreview_mock) context = {} filters = {'filter_fields': 'country', 'filter_values': 'Brazil'} params = self._default_resource_view_attributes(**filters) result = helpers.call_action('resource_view_create', context, **params) assert_equals(result['filter_fields'], ['country']) assert_equals(result['filter_values'], ['Brazil']) assert_equals(result['filters'], {'country': ['Brazil']})
def test_user_show_default_values(self): user = factories.User() got_user = helpers.call_action('user_show', id=user['id']) assert 'password' not in got_user assert 'reset_key' not in got_user assert 'apikey' not in got_user assert 'email' not in got_user
def test_user_update_password(self): '''Test that updating a user's password works successfully.''' user = factories.User() # FIXME we have to pass the email address to user_update even though # we're not updating it, otherwise validation fails. helpers.call_action( 'user_update', id=user['name'], email=user['email'], password='******', ) # user_show() never returns the user's password, so we have to access # the model directly to test it. import ckan.model as model updated_user = model.User.get(user['id']) assert updated_user.validate_password('new password')
def test_update_organization_cant_change_type(self): user = factories.User() context = {'user': user['name']} org = factories.Organization( type='organization', name='unchanging', user=user) org = helpers.call_action( 'organization_update', context=context, id=org['id'], name='unchanging', type='ragtagband') assert_equals(org['type'], 'organization') assert_equals(helpers.call_action( 'organization_show', id='unchanging')['type'], 'organization')
def test_package_patch_updating_single_field(self): user = factories.User() dataset = factories.Dataset( name='annakarenina', notes='some test now', user=user) dataset = helpers.call_action( 'package_patch', id=dataset['id'], name='somethingnew') assert_equals(dataset['name'], 'somethingnew') assert_equals(dataset['notes'], 'some test now') dataset2 = helpers.call_action('package_show', id=dataset['id']) assert_equals(dataset2['name'], 'somethingnew') assert_equals(dataset2['notes'], 'some test now')
def test_does_not_return_editors(self): """ By default organization_list_for_user() should not return organizations that the user is just an editor (not an admin) of. """ user = factories.User() context = {'user': user['name']} organization = factories.Organization() helpers.call_action('member_create', id=organization['id'], object=user['id'], object_type='user', capacity='editor') organizations = helpers.call_action('organization_list_for_user', context=context) assert organizations == []
def test_group_list_in_presence_of_custom_group_types(self): '''Getting the group_list shouldn't return custom group types.''' group1 = factories.Group() group2 = factories.Group() factories.Group(type='custom') group_list = helpers.call_action('group_list') assert (sorted(group_list) == sorted([g['name'] for g in [group1, group2]]))
def test_related_list_featured(self): ''' Test related_list with no featured filter ''' user = factories.User() related1 = factories.Related(user=user, featured=True) related2 = factories.Related(user=user, type='application') related_list = helpers.call_action('related_list', featured=True) assert ([related1] == related_list)
def test_related_list_invalid_sort_parameter(self): ''' Test related_list with invalid value for sort parameter ''' user = factories.User() related1 = factories.Related(user=user, featured=True) related2 = factories.Related(user=user, type='application') related_list = helpers.call_action('related_list', sort='invalid') assert ([related1, related2] == related_list)
def test_related_list_sorted(self): ''' Test related_list with sort parameter ''' user = factories.User() related1 = factories.Related(user=user, featured=True) related2 = factories.Related(user=user, type='application') related_list = helpers.call_action('related_list', sort='created_desc') assert ([related2, related1] == related_list)
def test_related_list_with_no_params(self): ''' Test related_list with no parameters and default sort ''' user = factories.User() related1 = factories.Related(user=user, featured=True) related2 = factories.Related(user=user, type='application') related_list = helpers.call_action('related_list') assert ([related1, related2] == related_list)
def test_user_list_excludes_deleted_users(self): user = factories.User() factories.User(state='deleted') got_users = helpers.call_action('user_list') remove_pseudo_users(got_users) assert len(got_users) == 1 assert got_users[0]['name'] == user['name']