Ejemplo n.º 1
0
    def test_invitations_are_sent(self):

        with mock.patch.object(AskAppDispatcherMiddleware, 'send_invitations') as \
                mock_send_invitations:

            # This will create the whole WSGI stack
            helpers._get_test_app()

            assert mock_send_invitations.called
            eq_(len(mock_send_invitations.call_args[0]), 1)

            eq_(sorted(mock_send_invitations.call_args[0][0].keys()),
                ['flask_app', 'pylons_app'])
Ejemplo n.º 2
0
    def test_registered_user_login(self):
        '''
        Registered user can submit valid login details at /user/login and
        be returned to appropriate place.
        '''
        app = helpers._get_test_app()

        # make a user
        user = factories.User()

        # get the form
        response = app.get('/user/login')
        # ...it's the second one
        login_form = response.forms[1]

        # fill it in
        login_form['login'] = user['name']
        login_form['password'] = '******'

        # submit it
        submit_response = login_form.submit()
        # let's go to the last redirect in the chain
        final_response = helpers.webtest_maybe_follow(submit_response)

        # the response is the user dashboard, right?
        final_response.mustcontain('<a href="/dashboard/">Dashboard</a>',
                                   '<span class="username">{0}</span>'
                                   .format(user['fullname']))
        # and we're definitely not back on the login page.
        final_response.mustcontain(no='<h1 class="page-heading">Login</h1>')
Ejemplo n.º 3
0
    def test_translation_works_on_flask_and_pylons(self):

        app = helpers._get_test_app()
        if not p.plugin_loaded(u'test_routing_plugin'):
            p.load(u'test_routing_plugin')
        try:
            plugin = p.get_plugin(u'test_routing_plugin')
            app.flask_app.register_extension_blueprint(
                plugin.get_blueprint())

            resp = app.get(u'/flask_translated')

            eq_(resp.body, u'Dataset')

            resp = app.get(u'/es/flask_translated')

            eq_(resp.body, u'Conjunto de datos')

            resp = app.get(u'/pylons_translated')

            eq_(resp.body, u'Groups')

            resp = app.get(u'/es/pylons_translated')

            eq_(resp.body, u'Grupos')

        finally:

            if p.plugin_loaded(u'test_routing_plugin'):
                p.unload(u'test_routing_plugin')
Ejemplo n.º 4
0
 def test_read(self):
     dataset = factories.Dataset()
     app = helpers._get_test_app()
     response = app.get(url_for(controller='package', action='read',
                                id=dataset['name']))
     response.mustcontain('Test Dataset')
     response.mustcontain('Just another test dataset')
Ejemplo n.º 5
0
    def test_confirm_cancel_delete(self):
        '''Test confirmation of deleting datasets

        When package_delete is made as a get request, it should return a
        'do you want to delete this dataset? confirmation page'''
        user = factories.User()
        owner_org = factories.Organization(
            users=[{'name': user['id'], 'capacity': 'admin'}]
        )
        dataset = factories.Dataset(owner_org=owner_org['id'])

        app = helpers._get_test_app()
        env = {'REMOTE_USER': user['name'].encode('ascii')}
        response = app.get(
            url_for(controller='package', action='delete', id=dataset['name']),
            extra_environ=env,
        )
        assert_equal(200, response.status_int)
        message = 'Are you sure you want to delete dataset - {name}?'
        response.mustcontain(message.format(name=dataset['title']))

        form = response.forms['confirm-dataset-delete-form']
        response = form.submit('cancel')
        response = helpers.webtest_maybe_follow(response)
        assert_equal(200, response.status_int)
Ejemplo n.º 6
0
    def test_confirm_and_cancel_deleting_a_resource(self):
        '''Test confirmation of deleting resources

        When resource_delete is made as a get request, it should return a
        'do you want to delete this reource? confirmation page'''
        user = factories.User()
        owner_org = factories.Organization(
            users=[{'name': user['id'], 'capacity': 'admin'}]
        )
        dataset = factories.Dataset(owner_org=owner_org['id'])
        resource = factories.Resource(package_id=dataset['id'])
        app = helpers._get_test_app()
        env = {'REMOTE_USER': user['name'].encode('ascii')}
        response = app.get(
            url_for(controller='package', action='resource_delete',
                    id=dataset['name'], resource_id=resource['id']),
            extra_environ=env,
        )
        assert_equal(200, response.status_int)
        message = 'Are you sure you want to delete resource - {name}?'
        response.mustcontain(message.format(name=resource['name']))

        # cancelling sends us back to the resource edit page
        form = response.forms['confirm-resource-delete-form']
        response = form.submit('cancel')
        response = response.follow()
        assert_equal(200, response.status_int)
Ejemplo n.º 7
0
    def test_custom_search(self):
        app = helpers._get_test_app()

        helpers.call_action('package_create', name='test_package_a',
                            custom_text='z')
        helpers.call_action('package_create', name='test_package_b',
                            custom_text='y')

        response = app.get('/dataset/')

        # change the sort by form to our custom_text ascending
        response.forms[1].fields['sort'][0].value = 'custom_text asc'

        response = response.forms[1].submit()
        # check that package_b appears before package a (y < z)
        a = response.body.index('test_package_a')
        b = response.body.index('test_package_b')
        nt.assert_true(b < a)

        response = app.get('/dataset/')
        response.forms[1].fields['sort'][0].value = 'custom_text desc'
        # check that package_a appears before package b (z is first in
        # descending order)
        response = response.forms[1].submit()
        a = response.body.index('test_package_a')
        b = response.body.index('test_package_b')
        nt.assert_true(a < b)
Ejemplo n.º 8
0
    def test_editor_users_cannot_add_members(self):

        user = factories.User()
        organization = factories.Organization(users=[{
            'name': user['name'],
            'capacity': 'editor'
        }])

        app = helpers._get_test_app()

        env = {'REMOTE_USER': user['name'].encode('ascii')}

        with app.flask_app.test_request_context():
            app.get(
                url_for(
                    'organization.member_new',
                    id=organization['id'], ),
                extra_environ=env,
                status=403, )

            app.post(
                url_for(
                    'organization.member_new',
                    id=organization['id'], ),
                {
                    'id': 'test',
                    'username': '******',
                    'save': 'save',
                    'role': 'test'
                },
                extra_environ=env,
                status=403, )
Ejemplo n.º 9
0
    def test_member_users_cannot_add_members(self):

        user = factories.User()
        group = factories.Group(
            users=[{'name': user['name'], 'capacity': 'member'}]
        )

        app = helpers._get_test_app()

        env = {'REMOTE_USER': user['name'].encode('ascii')}

        with app.flask_app.test_request_context():
            app.get(
                url_for(
                    controller='group',
                    action='member_new',
                    id=group['id'],
                ),
                extra_environ=env,
                status=403,
            )

            app.post(
                url_for(
                    controller='group',
                    action='member_new',
                    id=group['id'],
                ),
                {'id': 'test', 'username': '******', 'save': 'save', 'role': 'test'},
                extra_environ=env,
                status=403,
            )
Ejemplo n.º 10
0
 def setup(self):
     super(TestOrganizationEdit, self).setup()
     self.app = helpers._get_test_app()
     self.user = factories.User()
     self.user_env = {"REMOTE_USER": self.user["name"].encode("ascii")}
     self.organization = factories.Organization(user=self.user)
     self.organization_edit_url = url_for(controller="organization", action="edit", id=self.organization["id"])
Ejemplo n.º 11
0
 def setup_class(cls):
     cls._original_config = config.copy()
     cls.app = _get_test_app()
     if not p.plugin_loaded('resource_proxy'):
         p.load('resource_proxy')
     config['ckan.plugins'] = 'resource_proxy'
     create_test_data.CreateTestData.create()
Ejemplo n.º 12
0
    def test_setting_a_key_sets_it_on_flask_config_if_app_context(self):

        app = helpers._get_test_app()
        with app.flask_app.app_context():

            ckan_config[u'ckan.site_title'] = u'Example title'
            eq_(flask.current_app.config[u'ckan.site_title'], u'Example title')
Ejemplo n.º 13
0
    def test_other_missing_attributes_raise_attributeerror_exceptions(self):

        app = helpers._get_test_app()

        with app.flask_app.test_request_context(u'/hello?a=1'):

            assert_raises(AttributeError, getattr, ckan_request, u'not_here')
Ejemplo n.º 14
0
    def test_accessing_missing_key_raises_error_on_flask_request(self):

        app = helpers._get_test_app()

        with app.flask_app.test_request_context():

            assert_raises(AttributeError, getattr, ckan_g, u'user')
Ejemplo n.º 15
0
    def setup_class(cls):
        if not tests.is_datastore_supported():
            raise nose.SkipTest("Datastore not supported")
        cls.app = helpers._get_test_app()
        p.load('datastore')
        ctd.CreateTestData.create()
        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.normal_user = model.User.get('annafan')
        resource = model.Package.get('annakarenina').resources[0]
        cls.data = {
            'resource_id': resource.id,
            'aliases': u'b\xfck2',
            'fields': [{'id': 'book', 'type': 'text'},
                       {'id': 'author', 'type': 'text'},
                       {'id': 'rating with %', 'type': 'text'}],
            'records': [{'book': 'annakarenina', 'author': 'tolstoy',
                         'rating with %': '90%'},
                        {'book': 'warandpeace', 'author': 'tolstoy',
                         'rating with %': '42%'}]
        }

        engine = db.get_write_engine()

        cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
        set_url_type(
            model.Package.get('annakarenina').resources, cls.sysadmin_user)
Ejemplo n.º 16
0
 def setup(self):
     super(TestOrganizationList, self).setup()
     self.app = helpers._get_test_app()
     self.user = factories.User()
     self.user_env = {'REMOTE_USER': self.user['name'].encode('ascii')}
     self.organization_list_url = url_for(controller='organization',
                                          action='index')
Ejemplo n.º 17
0
    def test_import_v2_style_register_i18n(self):

        sysadmin = factories.Sysadmin()
        app = helpers._get_test_app()

        resp = app.get('/dataset/new', extra_environ={'REMOTE_USER': str(sysadmin['name'])})
        assert_in('Altres (Oberta)', resp.body)
Ejemplo n.º 18
0
    def test_registered_user_login_bad_password(self):
        '''
        Registered user is redirected to appropriate place if they submit
        invalid login details at /user/login.
        '''
        app = helpers._get_test_app()

        # make a user
        user = factories.User()

        # get the form
        response = app.get('/user/login')
        # ...it's the second one
        login_form = response.forms[1]

        # fill it in
        login_form['login'] = user['name']
        login_form['password'] = '******'

        # submit it
        submit_response = login_form.submit()
        # let's go to the last redirect in the chain
        final_response = helpers.webtest_maybe_follow(submit_response)

        # the response is the login page again
        final_response.mustcontain('<h1 class="page-heading">Login</h1>',
                                   'Login failed. Bad username or password.')
        # and we're definitely not on the dashboard.
        final_response.mustcontain(no='<a href="/dashboard">Dashboard</a>'),
        final_response.mustcontain(no='<span class="username">{0}</span>'
                                   .format(user['fullname']))
Ejemplo n.º 19
0
    def setup_class(cls):
        cls.app = helpers._get_test_app()
        super(TestDatastoreInsertLegacyTests, cls).setup_class()
        ctd.CreateTestData.create()
        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.normal_user = model.User.get('annafan')
        set_url_type(
            model.Package.get('annakarenina').resources, cls.sysadmin_user)
        resource = model.Package.get('annakarenina').resources[0]
        cls.data = {
            'resource_id': resource.id,
            'fields': [{'id': u'b\xfck', 'type': 'text'},
                       {'id': 'author', 'type': 'text'},
                       {'id': 'nested', 'type': 'json'},
                       {'id': 'characters', 'type': 'text[]'},
                       {'id': 'published'}],
            'primary_key': u'b\xfck',
            'records': [{u'b\xfck': 'annakarenina', 'author': 'tolstoy',
                        'published': '2005-03-01', 'nested': ['b', {'moo': 'moo'}]},
                        {u'b\xfck': 'warandpeace', 'author': 'tolstoy',
                        'nested': {'a':'b'}}
                       ]
            }
        postparams = '%s=1' % json.dumps(cls.data)
        auth = {'Authorization': str(cls.sysadmin_user.apikey)}
        res = cls.app.post('/api/action/datastore_create', params=postparams,
                           extra_environ=auth)
        res_dict = json.loads(res.body)
        assert res_dict['success'] is True

        engine = db.get_write_engine()
        cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
Ejemplo n.º 20
0
 def test_resource_url(self):
     app = helpers._get_test_app()
     p.load(u'example_theme_v15_fanstatic')
     content = app.get(u'/en/base.html')
     assert u'example_theme.css' in content
     assert u'href="/data/fanstatic/example_theme' in content
     p.unload(u'example_theme_v15_fanstatic')
Ejemplo n.º 21
0
 def setup(self):
     super(TestOrganizationBulkProcess, self).setup()
     self.app = helpers._get_test_app()
     self.user = factories.User()
     self.user_env = {'REMOTE_USER': self.user['name'].encode('ascii')}
     self.organization = factories.Organization(user=self.user)
     self.organization_bulk_url = url_for(
         'organization.bulk_process', id=self.organization['id'])
Ejemplo n.º 22
0
 def test_delete_on_non_existing_dataset(self):
     app = helpers._get_test_app()
     response = app.post(
         url_for(controller='package', action='delete',
                 id='schrodingersdatset'),
         expect_errors=True,
     )
     assert_equal(404, response.status_int)
Ejemplo n.º 23
0
 def test_redirect_when_given_id(self):
     group = factories.Group()
     app = helpers._get_test_app()
     response = app.get(url_for('group.read', id=group['id']), status=302)
     # redirect replaces the ID with the name in the URL
     redirected_response = response.follow()
     expected_url = url_for('group.read', id=group['name'])
     assert_equal(redirected_response.request.path, expected_url)
Ejemplo n.º 24
0
    def setup(self):
        self.app = helpers._get_test_app()

        # Install plugin and register its blueprint
        if not plugins.plugin_loaded(u'example_flask_iblueprint'):
            plugins.load(u'example_flask_iblueprint')
            plugin = plugins.get_plugin(u'example_flask_iblueprint')
            self.app.flask_app.register_extension_blueprint(plugin.get_blueprint())
Ejemplo n.º 25
0
    def test_params_also_works_on_flask_request(self):

        app = helpers._get_test_app()

        with app.flask_app.test_request_context(u'/hello?a=1'):

            assert u'a' in ckan_request.args
            assert u'a' in ckan_request.params
Ejemplo n.º 26
0
    def setup_class(cls):

        if not tests.is_datastore_supported():
            raise nose.SkipTest("Datastore not supported")
        cls.app = helpers._get_test_app()
        p.load('datastore')
        ctd.CreateTestData.create()
        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.normal_user = model.User.get('annafan')
        cls.dataset = model.Package.get('annakarenina')
        cls.resource = cls.dataset.resources[0]
        cls.data = {
            'resource_id': cls.resource.id,
            'force': True,
            'aliases': 'books3',
            'fields': [{'id': u'b\xfck', 'type': 'text'},
                       {'id': 'author', 'type': 'text'},
                       {'id': 'published'},
                       {'id': u'characters', u'type': u'_text'},
                       {'id': 'rating with %'}],
            'records': [{u'b\xfck': 'annakarenina', 'author': 'tolstoy',
                        'published': '2005-03-01', 'nested': ['b', {'moo': 'moo'}],
                        u'characters': [u'Princess Anna', u'Sergius'],
                        'rating with %': '60%'},
                        {u'b\xfck': 'warandpeace', 'author': 'tolstoy',
                        'nested': {'a': 'b'}, 'rating with %': '99%'}
                       ]
        }
        postparams = '%s=1' % json.dumps(cls.data)
        auth = {'Authorization': str(cls.sysadmin_user.apikey)}
        res = cls.app.post('/api/action/datastore_create', params=postparams,
                           extra_environ=auth)
        res_dict = json.loads(res.body)
        assert res_dict['success'] is True

        # Make an organization, because private datasets must belong to one.
        cls.organization = tests.call_action_api(
            cls.app, 'organization_create',
            name='test_org',
            apikey=cls.sysadmin_user.apikey)

        cls.expected_records = [{u'published': u'2005-03-01T00:00:00',
                                 u'_id': 1,
                                 u'nested': [u'b', {u'moo': u'moo'}],
                                 u'b\xfck': u'annakarenina',
                                 u'author': u'tolstoy',
                                 u'characters': [u'Princess Anna', u'Sergius'],
                                 u'rating with %': u'60%'},
                                {u'published': None,
                                 u'_id': 2,
                                 u'nested': {u'a': u'b'},
                                 u'b\xfck': u'warandpeace',
                                 u'author': u'tolstoy',
                                 u'characters': None,
                                 u'rating with %': u'99%'}]

        engine = db.get_write_engine()
        cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
Ejemplo n.º 27
0
def call_action_api(action, apikey=None, status=200, **kwargs):
    '''POST an HTTP request to the CKAN API and return the result.

    Any additional keyword arguments that you pass to this function as **kwargs
    are posted as params to the API.

    Usage:

        package_dict = call_action_api('package_create', apikey=apikey,
                name='my_package')
        assert package_dict['name'] == 'my_package'

        num_followers = post(app, 'user_follower_count', id='annafan')

    If you are expecting an error from the API and want to check the contents
    of the error dict, you have to use the status param otherwise an exception
    will be raised:

        error_dict = call_action_api('group_activity_list', status=403,
                id='invalid_id')
        assert error_dict['message'] == 'Access Denied'

    :param action: the action to post to, e.g. 'package_create'
    :type action: string

    :param apikey: the API key to put in the Authorization header of the post
        (optional, default: None)
    :type apikey: string

    :param status: the HTTP status code expected in the response from the CKAN
        API, e.g. 403, if a different status code is received an exception will
        be raised (optional, default: 200)
    :type status: int

    :param **kwargs: any other keyword arguments passed to this function will
        be posted to the API as params

    :raises paste.fixture.AppError: if the HTTP status code of the response
        from the CKAN API is different from the status param passed to this
        function

    :returns: the 'result' or 'error' dictionary from the CKAN API response
    :rtype: dictionary

    '''
    params = json.dumps(kwargs)
    app = _get_test_app()
    response = app.post('/api/action/{0}'.format(action), params=params,
                        extra_environ={'Authorization': str(apikey)},
                        status=status)

    if status in (200,):
        assert response.json['success'] is True
        return response.json['result']
    else:
        assert response.json['success'] is False
        return response.json['error']
Ejemplo n.º 28
0
 def setup(self):
     super(TestOrganizationEdit, self).setup()
     self.app = helpers._get_test_app()
     self.user = factories.User()
     self.user_env = {'REMOTE_USER': self.user['name'].encode('ascii')}
     self.organization = factories.Organization(user=self.user)
     self.organization_edit_url = url_for(controller='organization',
                                          action='edit',
                                          id=self.organization['id'])
Ejemplo n.º 29
0
    def test_deleting_a_key_delets_it_on_flask_config(self):

        app = helpers._get_test_app()
        with app.flask_app.app_context():

            ckan_config[u'ckan.site_title'] = u'Example title'
            del ckan_config[u'ckan.site_title']

            assert u'ckan.site_title' not in flask.current_app.config
Ejemplo n.º 30
0
    def setup(self):
        self.app = helpers._get_test_app()

        # Install plugin and register its blueprint
        if not p.plugin_loaded(u'test_flash_plugin'):
            p.load(u'test_flash_plugin')
            plugin = p.get_plugin(u'test_flash_plugin')
            self.app.flask_app.register_extension_blueprint(
                plugin.get_blueprint())
Ejemplo n.º 31
0
    def test_update_works_on_flask_config(self):

        app = helpers._get_test_app()
        with app.flask_app.app_context():

            ckan_config[u'ckan.site_title'] = u'Example title'

            ckan_config.update({
                u'ckan.site_title': u'Example title 2',
                u'ckan.new_key': u'test'
            })

            eq_(flask.current_app.config[u'ckan.site_title'],
                u'Example title 2')
            eq_(flask.current_app.config[u'ckan.new_key'], u'test')
Ejemplo n.º 32
0
def datastore_job(res_id, value):
    """
    A background job that uses the Datastore.
    """
    app = helpers._get_test_app()
    if not p.plugin_loaded(u"datastore"):
        p.load("datastore")
    data = {
        "resource_id": res_id,
        "method": "insert",
        "records": [{"value": value}],
    }

    with app.flask_app.test_request_context():
        helpers.call_action("datastore_upsert", **data)
Ejemplo n.º 33
0
    def setup_class(cls):
        cls.app = _get_test_app()
        if not tests.is_datastore_supported():
            raise nose.SkipTest("Datastore not supported")
        p.load('datastore')
        p.load('datapusher')
        p.load('test_datapusher_plugin')

        resource = factories.Resource(url_type='datastore')
        cls.dataset = factories.Dataset(resources=[resource])

        cls.sysadmin_user = factories.User(name='testsysadmin', sysadmin=True)
        cls.normal_user = factories.User(name='annafan')
        engine = db.get_write_engine()
        cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
Ejemplo n.º 34
0
    def test_package_update_remove_org_error(self):
        import paste.fixture
        import pylons.test

        app = helpers._get_test_app()
        org = call_action_api(app, 'organization_create',
                apikey=self.sysadmin_user.apikey, name='myorganization')
        package = call_action_api(app, 'package_create',
                apikey=self.sysadmin_user.apikey, name='foobarbaz', owner_org=org['id'])

        assert package['owner_org']
        package['owner_org'] = ''
        res = call_action_api(app, 'package_update',
                apikey=self.sysadmin_user.apikey, **package)
        assert not res['owner_org'], res['owner_org']
Ejemplo n.º 35
0
    def setup_class(cls):
        cls._original_config = dict(config)
        config['ckan.plugins'] = 'datastore datapusher'

        cls.app = helpers._get_test_app()
        if not tests.is_datastore_supported():
            raise nose.SkipTest("Datastore not supported")

        ctd.CreateTestData.create()
        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.normal_user = model.User.get('annafan')
        engine = db.get_write_engine()
        cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
        set_url_type(
            model.Package.get('annakarenina').resources, cls.sysadmin_user)
Ejemplo n.º 36
0
    def test_package_update_duplicate_extras_error(self):

        # We need to create a package first, so that we can update it.
        app = helpers._get_test_app()
        package = call_action_api(app, 'package_create',
                apikey=self.sysadmin_user.apikey, name='foobar')

        # Posting a dataset dict to package_update containing two extras dicts
        # with the same key, should return a Validation Error.
        package['extras'] = [{'key': 'foo', 'value': 'bar'},
                    {'key': 'foo', 'value': 'gar'}]
        error = call_action_api(app, 'package_update',
                apikey=self.sysadmin_user.apikey, status=409, **package)
        assert error['__type'] == 'Validation Error'
        assert error['extras_validation'] == ['Duplicate key "foo"']
Ejemplo n.º 37
0
 def setup_class(cls):
     ckan.model.repo.rebuild_db()
     ckan.lib.search.clear_all()
     CreateTestData.create()
     cls.app = helpers._get_test_app()
     joeadmin = ckan.model.User.get('joeadmin')
     cls.joeadmin = {'id': joeadmin.id, 'apikey': joeadmin.apikey}
     annafan = ckan.model.User.get('annafan')
     cls.annafan = {'id': annafan.id, 'apikey': annafan.apikey}
     testsysadmin = ckan.model.User.get('testsysadmin')
     cls.testsysadmin = {
         'id': testsysadmin.id,
         'apikey': testsysadmin.apikey
     }
     cls.new_user = cls.user_create()
    def setup_class(cls):

        # Disable the email notifications feature.

        cls.app = helpers._get_test_app()
        model.repo.rebuild_db()
        tests.CreateTestData.create()

        joeadmin = model.User.get("joeadmin")
        cls.joeadmin = {"id": joeadmin.id, "apikey": joeadmin.apikey}
        testsysadmin = model.User.get("testsysadmin")
        cls.testsysadmin = {
            "id": testsysadmin.id,
            "apikey": testsysadmin.apikey,
        }
Ejemplo n.º 39
0
    def test_js_included(self):
        # Make a copy of the Pylons config, so we can restore it in teardown.
        original_config = dict(config)
        config['ckan.plugins'] = 'text_view'

        app = helpers._get_test_app()
        with app.flask_app.test_request_context():
            url = h.url_for('resource.view',
                            id=self.package.name, resource_id=self.resource_id,
                            view_id=self.resource_view['id'])
        result = app.get(url)
        assert (('text_view.js' in result.body) or  # Source file
                ('textview.js' in result.body))     # Compiled file
        # Restore the config to its original values
        config.clear()
        config.update(original_config)
Ejemplo n.º 40
0
    def test_non_authorized_user_trying_to_delete_fails(self):

        app = helpers._get_test_app()

        user = factories.User()
        extra_environ = {'REMOTE_USER': user['name'].encode('ascii')}
        with app.flask_app.test_request_context():
            url = url_for(controller='organization',
                          action='delete',
                          id=self.organization['id'])

        app.get(url=url, status=403, extra_environ=extra_environ)

        organization = helpers.call_action('organization_show',
                                           id=self.organization['id'])
        assert_equal(organization['state'], 'active')
Ejemplo n.º 41
0
def datastore_job(res_id, value):
    '''
    A background job that uses the Datastore.
    '''
    app = helpers._get_test_app()
    p.load('datastore')
    data = {
        'resource_id': res_id,
        'method': 'insert',
        'records': [{
            'value': value
        }],
    }

    with app.flask_app.test_request_context():
        helpers.call_action('datastore_upsert', **data)
Ejemplo n.º 42
0
    def test_all_fields_saved(self):
        app = helpers._get_test_app()
        response = app.get(url=self.organization_new_url,
                           extra_environ=self.user_env)

        form = response.forms['organization-edit-form']
        form['name'] = u'all-fields-saved'
        form['title'] = 'Science'
        form['description'] = 'Sciencey datasets'
        form['image_url'] = 'http://example.com/image.png'

        response = submit_and_follow(self.app, form, name='save',
                                     extra_environ=self.user_env)
        group = helpers.call_action('organization_show', id='all-fields-saved')
        assert_equal(group['title'], u'Science')
        assert_equal(group['description'], 'Sciencey datasets')
Ejemplo n.º 43
0
 def test_deleting_non_existing_resource_404s(self):
     user = factories.User()
     owner_org = factories.Organization(users=[{
         'name': user['id'],
         'capacity': 'admin'
     }])
     dataset = factories.Dataset(owner_org=owner_org['id'])
     env = {'REMOTE_USER': user['name'].encode('ascii')}
     app = helpers._get_test_app()
     response = app.post(url_for(controller='package',
                                 action='resource_delete',
                                 id=dataset['name'],
                                 resource_id='doesnotexist'),
                         extra_environ=env,
                         expect_errors=True)
     assert_equal(404, response.status_int)
Ejemplo n.º 44
0
    def setup_class(cls):

        cls.app = helpers._get_test_app()
        mock_mail_server.SmtpServerHarness.setup_class()
        tests.CreateTestData.create()

        joeadmin = model.User.get('joeadmin')
        cls.joeadmin = {
            'id': joeadmin.id,
            'apikey': joeadmin.apikey,
        }
        testsysadmin = model.User.get('testsysadmin')
        cls.testsysadmin = {
            'id': testsysadmin.id,
            'apikey': testsysadmin.apikey,
        }
Ejemplo n.º 45
0
    def test_saved(self):

        app = helpers._get_test_app()

        response = app.get(url=self.organization_edit_url,
                           extra_environ=self.user_env)

        form = response.forms['organization-edit-form']
        response = webtest_submit(form,
                                  name='save',
                                  extra_environ=self.user_env)
        group = helpers.call_action('organization_show',
                                    id=self.organization['id'])
        assert_equal(group['title'], u'Test Organization')
        assert_equal(group['type'], 'organization')
        assert_equal(group['state'], 'active')
Ejemplo n.º 46
0
    def test_organization_search(self):

        app = helpers._get_test_app()
        '''Requesting organization search (index) returns list of
        organizations and search form.'''

        index_response = app.get(self.search_url)
        index_response_html = BeautifulSoup(index_response.body)
        org_names = index_response_html.select('ul.media-grid '
                                               'li.media-item '
                                               'h3.media-heading')
        org_names = [n.string for n in org_names]

        assert_equal(len(org_names), 3)
        assert_true('AOrg One' in org_names)
        assert_true('AOrg Two' in org_names)
        assert_true('Org Three' in org_names)
Ejemplo n.º 47
0
    def test_title_description_iframe_shown(self):
        # Make a copy of the Pylons config, so we can restore it in teardown.
        original_config = dict(config)
        config['ckan.plugins'] = 'text_view'

        app = helpers._get_test_app()
        with app.flask_app.test_request_context():
            url = h.url_for('resource.read',
                            id=self.package.name, resource_id=self.resource_id)
        result = app.get(url)
        assert self.resource_view['title'] in result
        assert self.resource_view['description'] in result
        assert 'data-module="data-viewer"' in result.body

        # Restore the config to its original values
        config.clear()
        config.update(original_config)
Ejemplo n.º 48
0
    def setup(cls):

        cls.app = _get_test_app()
        ckan.plugins.load('multilingual_dataset')
        ckan.plugins.load('multilingual_group')
        ckan.plugins.load('multilingual_tag')
        ckan.tests.legacy.setup_test_search_index()
        _create_test_data.CreateTestData.create_translations_test_data()

        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.org = {
            'name': 'test_org',
            'title': 'russian',
            'description': 'Roger likes these books.'
        }
        ckan.tests.legacy.call_action_api(cls.app,
                                          'organization_create',
                                          apikey=cls.sysadmin_user.apikey,
                                          **cls.org)
        dataset = {
            'name': 'test_org_dataset',
            'title': 'A Novel By Tolstoy',
            'owner_org': cls.org['name']
        }
        ckan.tests.legacy.call_action_api(cls.app,
                                          'package_create',
                                          apikey=cls.sysadmin_user.apikey,
                                          **dataset)

        # Add translation terms that match a couple of group names and package
        # names. Group names and package names should _not_ get translated even
        # if there are terms matching them, because they are used to form URLs.
        for term in ('roger', 'david', 'annakarenina', 'warandpeace'):
            for lang_code in ('en', 'de', 'fr'):
                data_dict = {
                    'term': term,
                    'term_translation': 'this should not be rendered',
                    'lang_code': lang_code
                }
                context = {
                    'model': ckan.model,
                    'session': ckan.model.Session,
                    'user': '******'
                }
                ckan.logic.action.update.term_translation_update(
                    context, data_dict)
Ejemplo n.º 49
0
    def test_sysadmin_can_delete_any_dataset(self):
        owner_org = factories.Organization()
        dataset = factories.Dataset(owner_org=owner_org['id'])
        app = helpers._get_test_app()

        user = factories.Sysadmin()
        env = {'REMOTE_USER': user['name'].encode('ascii')}

        response = app.post(
            url_for(controller='package', action='delete', id=dataset['name']),
            extra_environ=env,
        )
        response = response.follow()
        assert_equal(200, response.status_int)

        deleted = helpers.call_action('package_show', id=dataset['id'])
        assert_equal('deleted', deleted['state'])
Ejemplo n.º 50
0
 def setup_class(cls):
     mock_mail_server.SmtpServerHarness.setup_class()
     pylons_controller.PylonsTestCase.setup_class()
     tests.CreateTestData.create()
     cls.app = helpers._get_test_app()
     joeadmin = model.User.get('joeadmin')
     cls.joeadmin = {'id': joeadmin.id,
             'apikey': joeadmin.apikey,
             }
     testsysadmin = model.User.get('testsysadmin')
     cls.testsysadmin = {'id': testsysadmin.id,
             'apikey': testsysadmin.apikey,
             }
     annafan = model.User.get('annafan')
     cls.annafan = {'id': annafan.id,
             'apikey': annafan.apikey,
             }
Ejemplo n.º 51
0
    def test_register_user_bad_password(self):
        app = helpers._get_test_app()

        with app.flask_app.test_request_context():
            url = url_for(controller='user', action='register')

        response = app.get(url)

        form = response.forms['user-register-form']
        form['name'] = 'newuser'
        form['fullname'] = 'New User'
        form['email'] = '*****@*****.**'
        form['password1'] = 'TestPassword1'
        form['password2'] = ''

        response = form.submit('save')
        assert_true('The passwords you entered do not match' in response)
Ejemplo n.º 52
0
    def test_owner_delete(self):

        app = helpers._get_test_app()

        with app.flask_app.test_request_context():
            url = url_for(controller='organization',
                          action='delete',
                          id=self.organization['id'])
        response = app.get(url, status=200, extra_environ=self.user_env)

        form = response.forms['organization-confirm-delete-form']
        response = submit_and_follow(app,
                                     form,
                                     name='delete',
                                     extra_environ=self.user_env)
        organization = helpers.call_action('organization_show',
                                           id=self.organization['id'])
        assert_equal(organization['state'], 'deleted')
Ejemplo n.º 53
0
    def test_as_dict(self):
        # Internally as_dict calls url_for so we need an application context
        app = helpers._get_test_app()
        with app.flask_app.test_request_context():

            pkg = model.Package.by_name(self.name)
            out = pkg.as_dict()
        assert out['name'] == pkg.name
        assert out['license'] == pkg.license.title
        assert out['license_id'] == pkg.license.id
        assert out['tags'] == [tag.name for tag in pkg.get_tags()]
        assert out['metadata_modified'] == pkg.metadata_modified.isoformat()
        assert out['metadata_created'] == pkg.metadata_created.isoformat()
        assert_equal(out['notes'], pkg.notes)
        assert_equal(
            out['notes_rendered'],
            '<p>A great package  like <a href="/dataset/pollution_stats">package:pollution_stats</a></p>'
        )
Ejemplo n.º 54
0
    def test_saved(self):

        app = helpers._get_test_app()

        response = app.get(url=self.organization_new_url,
                           extra_environ=self.user_env)

        form = response.forms['organization-edit-form']
        form['name'] = u'saved'

        response = submit_and_follow(app,
                                     form,
                                     name='save',
                                     extra_environ=self.user_env)
        group = helpers.call_action('organization_show', id='saved')
        assert_equal(group['title'], u'')
        assert_equal(group['type'], 'organization')
        assert_equal(group['state'], 'active')
Ejemplo n.º 55
0
    def test_only_own_search_shows_all(self):
        app = th._get_test_app()
        url = ch.url_for(
            controller='api', action='action',
            logic_function='user_show', ver=3)
        result = app.get(
            url, {'id': self.user['id'], 'include_datasets': True},
            extra_environ={'REMOTE_USER': str(self.user['name'])}
        ).json['result']

        nt.assert_equal(3, len(result['datasets']))

        result = app.get(
            url, {'id': self.user['id'], 'include_datasets': True},
            extra_environ={'REMOTE_USER': str(self.other_user['name'])}
        ).json['result']

        nt.assert_equal(1, len(result['datasets']))
Ejemplo n.º 56
0
    def setup_class(cls):
        search.clear_all()
        helpers.reset_db()

        cls.original_config = config.copy()
        cls._change_config(config)

        cls.m_s3 = mock_s3()
        cls.m_s3.start()

        cls.conn = boto3.resource(
            's3', region_name=config['ckanext.s3filestore.region_name'])
        cls.conn.create_bucket(Bucket=cls.bucket_name)

        app = helpers._get_test_app()

        factories.Sysadmin(name='testsysadmin')
        cls._create_packages_by_user(cls.dataset1_name, 'testsysadmin')
Ejemplo n.º 57
0
    def test_register_a_user(self):
        app = helpers._get_test_app()
        response = app.get(url=url_for(controller='user', action='register'))

        form = response.forms['user-register-form']
        form['name'] = 'newuser'
        form['fullname'] = 'New User'
        form['email'] = '*****@*****.**'
        form['password1'] = 'testpassword'
        form['password2'] = 'testpassword'
        response = submit_and_follow(app, form, name='save')
        response = response.follow()
        assert_equal(200, response.status_int)

        user = helpers.call_action('user_show', id='newuser')
        assert_equal(user['name'], 'newuser')
        assert_equal(user['fullname'], 'New User')
        assert_false(user['sysadmin'])
Ejemplo n.º 58
0
    def test_logged_in_user_cannot_delete_owned_dataset(self):
        owner = factories.User()
        owner_org = factories.Organization(users=[{
            'name': owner['id'],
            'capacity': 'admin'
        }])
        dataset = factories.Dataset(owner_org=owner_org['id'])

        app = helpers._get_test_app()
        user = factories.User()
        env = {'REMOTE_USER': user['name'].encode('ascii')}
        response = app.post(url_for(controller='package',
                                    action='delete',
                                    id=dataset['name']),
                            extra_environ=env,
                            expect_errors=True)
        assert_equal(401, response.status_int)
        response.mustcontain('Unauthorized to delete package')
Ejemplo n.º 59
0
    def test_anon_users_cannot_delete_owned_resources(self):
        user = factories.User()
        owner_org = factories.Organization(users=[{
            'name': user['id'],
            'capacity': 'admin'
        }])
        dataset = factories.Dataset(owner_org=owner_org['id'])
        resource = factories.Resource(package_id=dataset['id'])

        app = helpers._get_test_app()
        response = app.post(
            url_for(controller='package',
                    action='resource_delete',
                    id=dataset['name'],
                    resource_id=resource['id']), )
        response = response.follow()
        assert_equal(200, response.status_int)
        response.mustcontain('Unauthorized to delete package')
Ejemplo n.º 60
0
    def setup_class(cls):

        cls.app = helpers._get_test_app()
        if not tests.is_datastore_supported():
            raise nose.SkipTest("Datastore not supported")
        p.load('datastore')
        ctd.CreateTestData.create()
        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.normal_user = model.User.get('annafan')
        resource = model.Package.get('annakarenina').resources[0]
        cls.data = {
            'resource_id':
            resource.id,
            'aliases':
            u'b\xfck2',
            'fields': [{
                'id': 'book',
                'type': 'text'
            }, {
                'id': 'author',
                'type': 'text'
            }, {
                'id': 'rating with %',
                'type': 'text'
            }],
            'records': [{
                'book': 'annakarenina',
                'author': 'tolstoy',
                'rating with %': '90%'
            }, {
                'book': 'warandpeace',
                'author': 'tolstoy',
                'rating with %': '42%'
            }]
        }

        engine = db.get_write_engine()

        cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))

        with cls.app.flask_app.test_request_context():
            set_url_type(
                model.Package.get('annakarenina').resources, cls.sysadmin_user)