Example #1
0
 def setup_class(cls):
     MockPackageSearchPlugin().activate()
     MockPackageSearchPlugin().enable()
     setup_test_search_index()
     CreateTestData.create()
     MockPackageSearchPlugin().disable()
     cls.sysadmin_user = model.User.get('testsysadmin')
Example #2
0
    def setup_class(cls):
        """Setup for all tests."""

        model.repo.rebuild_db()
        kata_model.setup()
        CreateTestData.create()

        cls.user_sysadmin = model.User.get('testsysadmin')  # Org admin
        cls.user_normal = model.User.get('tester')          # Org editor
        cls.user_anna = model.User.get('annafan')
        cls.user_joe = model.User.get('joeadmin')           # Org member

        wsgiapp = make_app(config['global_conf'], **config['app_conf'])
        cls.app = paste.fixture.TestApp(wsgiapp)

        # Set up API callers

        cls.api_user_normal = ckanapi.TestAppCKAN(cls.app, apikey=cls.user_normal.apikey)
        cls.api_user_sysadmin = ckanapi.TestAppCKAN(cls.app, apikey=cls.user_sysadmin.apikey)
        cls.api_user_anna = ckanapi.TestAppCKAN(cls.app, apikey=cls.user_anna.apikey)
        cls.api_user_joe = ckanapi.TestAppCKAN(cls.app, apikey=cls.user_joe.apikey)
        cls.api = ckanapi.TestAppCKAN(cls.app)

        cls.TEST_DATADICT = copy.deepcopy(TEST_DATADICT)

        try:
            output = cls.api_user_sysadmin.action.organization_create(**TEST_ORGANIZATION_COMMON)
            cls.TEST_DATADICT['owner_org'] = output.get('id')
        except AppError:
            print 'Failed to create a common organization. Perhaps it exists already.'
Example #3
0
 def setup_class(self):
     CreateTestData.create()
     self.ab = 'http://site.com/a/b.txt'
     self.cd = 'http://site.com/c/d.txt'
     self.package_fixture_data = {
         'name' : u'testpkg',
         'title': 'Some Title',
         'url': u'http://blahblahblah.mydomain',
         'resources':[
             {'url':self.ab,
              'description':'This is site ab.',
              'format':'Excel spreadsheet',
              'alt_url':'alt',
              'extras':{'size':'100'},
              'hash':'abc-123'},
             {'url':self.cd,
              'description':'This is site cd.',
              'format':'Office spreadsheet',
              'alt_url':'alt',
              'extras':{'size':'100'},
              'hash':'qwe-456'},
             ],
         'tags': ['russion', 'novel'],
         'license_id': u'gpl-3.0',
         'extras': {'national_statistic':'yes',
                    'geographic_coverage':'England, Wales'},
     }
     CreateTestData.create_arbitrary(self.package_fixture_data)
     self.base_url = self.offset('/search/resource')
    def setup_class(cls):
        harvest_model.setup()
        CreateTestData.create()

        sysadmin_user = ckan.model.User.get('testsysadmin')
        cls.sysadmin = {
                'id': sysadmin_user.id,
                'apikey': sysadmin_user.apikey,
                'name': sysadmin_user.name,
                }


        cls.app = paste.fixture.TestApp(pylons.test.pylonsapp)

        cls.default_source_dict =  {
          "url": "http://test.action.com",
          "name": "test-source-action",
          "title": "Test source action",
          "notes": "Test source action desc",
          "source_type": "test-for-action",
          "frequency": "MANUAL",
          "config": json.dumps({"custom_option":["a","b"]})
        }

        if not p.plugin_loaded('test_action_harvester'):
            p.load('test_action_harvester')
    def setup(self):
        # need to do this for every test since we mess with System rights
        CreateTestData.create()
        model.repo.new_revision()
        model.Session.add(model.User(name=u'testadmin'))
        model.Session.add(model.User(name=u'testsysadmin'))
        model.Session.add(model.User(name=u'notadmin'))
        model.repo.commit_and_remove()

        pkg = model.Package.by_name(u'annakarenina')
        admin = model.User.by_name(u'testadmin')
        sysadmin = model.User.by_name(u'testsysadmin')
        model.add_user_to_role(admin, model.Role.ADMIN, pkg)
        model.add_user_to_role(sysadmin, model.Role.ADMIN, model.System())
        model.repo.commit_and_remove()

        self.pkg = model.Package.by_name(u'annakarenina')
        self.admin = model.User.by_name(u'testadmin')
        self.sysadmin = model.User.by_name(u'testsysadmin')
        self.notadmin = model.User.by_name(u'notadmin')

        self.package_fillers = {'title': 'test title',
                                'notes': 'test notes',
                                'license_id': 'mit-license',
                                }
Example #6
0
 def setup_class(cls):
     search.clear_all()
     CreateTestData.create()
     cls.testsysadmin = model.User.by_name(u'testsysadmin')
     cls.comment = u'Comment umlaut: \xfc.'
     cls.user_name = u'annafan' # created in CreateTestData
     cls.init_extra_environ(cls.user_name)
 def setup_class(self):
     # create test data
     CreateTestData.create()
     username = '******'
     user = model.User.by_name(unicode(username))
     assert user
     self.testclient = WsgiCkanClient(self.app, api_key=user.apikey, base_location='/api/2')
Example #8
0
    def setup_class(self):
        model.Session.remove()
        CreateTestData.create()
        self.name = u"revisiontest1"

        # create pkg
        self.description = [
            u"Written by Puccini",
            u"Written by Rossini",
            u"Not written at all",
            u"Written again",
            u"Written off",
        ]
        rev = model.repo.new_revision()
        self.grp = model.Group(name=self.name)
        self.grp.description = self.description[0]
        model.Session.add(self.grp)
        model.setup_default_user_roles(self.grp)
        model.repo.commit_and_remove()

        # edit pkg
        for i in range(5)[1:]:
            rev = model.repo.new_revision()
            grp = model.Group.by_name(self.name)
            grp.description = self.description[i]
            model.repo.commit_and_remove()

        self.grp = model.Group.by_name(self.name)
Example #9
0
    def setup_class(cls):
        MockVocabTagsPlugin().set_active(True)
        CreateTestData.create(package_type='mock_vocab_tags_plugin')
        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.dset = model.Package.get('warandpeace')
        cls.tag1_name = 'vocab-tag-1'
        cls.tag2_name = 'vocab-tag-2'

        # use our custom select class for this test suite
        cls.old_select = paste.fixture.Field.classes['select']
        paste.fixture.Field.classes['select'] = Select

        # create a test vocab
        params = json.dumps({'name': TEST_VOCAB_NAME})
        extra_environ = {'Authorization' : str(cls.sysadmin_user.apikey)}
        response = cls.app.post('/api/action/vocabulary_create', params=params,
                                extra_environ=extra_environ)
        assert json.loads(response.body)['success']
        vocab_id = json.loads(response.body)['result']['id']

        # add tags to the vocab
        extra_environ = {'Authorization' : str(cls.sysadmin_user.apikey)}
        params = json.dumps({'name': cls.tag1_name, 'vocabulary_id': vocab_id})
        response = cls.app.post('/api/action/tag_create', params=params,
                                 extra_environ=extra_environ)
        assert json.loads(response.body)['success']
        params = json.dumps({'name': cls.tag2_name, 'vocabulary_id': vocab_id})
        response = cls.app.post('/api/action/tag_create', params=params,
                                 extra_environ=extra_environ)
        assert json.loads(response.body)['success']
Example #10
0
 def setup_class(cls):
     model.repo.rebuild_db()
     search.clear_all()
     CreateTestData.create()
     cls.sysadmin_user = model.User.get('testsysadmin')
     cls.normal_user = model.User.get('annafan')
     CreateTestData.make_some_vocab_tags()
Example #11
0
 def setup_class(cls):
     search.clear()
     CreateTestData.create()
     cls.testsysadmin = model.User.by_name(u"testsysadmin")
     cls.comment = u"Comment umlaut: \xfc."
     cls.user_name = u"annafan"  # created in CreateTestData
     cls.init_extra_environ(cls.user_name)
Example #12
0
    def _reset_data(self):
        model.Session.remove()
        model.repo.rebuild_db()
        CreateTestData.create()
        CreateTestData.create_arbitrary(
            {'name':self.editpkg_name,
             'url':u'editpkgurl.com',
             'tags':[u'mytesttag'],
             'resources':[{'url':u'url escape: & umlaut: \xfc quote: "',
                          'description':u'description escape: & umlaut: \xfc quote "',
                          }],
             'admins':[u'testadmin'],
             })

        self.editpkg = model.Package.by_name(self.editpkg_name)
        self.pkgid = self.editpkg.id
        self.offset = url_for(controller='package', action='edit', id=self.editpkg_name)

        self.editpkg = model.Package.by_name(self.editpkg_name)
        self.admin = model.User.by_name(u'testsysadmin')

        self.extra_environ_admin = {'REMOTE_USER': self.admin.name.encode('utf8')}
        self.extra_environ_russianfan = {'REMOTE_USER': '******'}
        self.res = None #get's refreshed by setup
        model.Session.remove()
Example #13
0
    def setup_class(cls):
        model.repo.rebuild_db()
        CreateTestData.create()
        plugins.load('drupal')
        from ckan.plugins import PluginImplementations
        from ckan.plugins.interfaces import IConfigurer
        for plugin in PluginImplementations(IConfigurer):
            plugin.update_config(config)

        url = config['drupal.db_url'] 
        cls.engine = create_engine(url, echo=True)
        cls.metadata = MetaData(cls.engine)
        cls.node = Table('node',
                          cls.metadata,
                          autoload = True)
        cls.node = Table('node_revisions',
                          cls.metadata,
                          autoload = True)
        cls.package_table = Table('ckan_package',
                                  cls.metadata,
                                  autoload = True)
        cls.extra_table = Table('ckan_package_extra',
                                  cls.metadata,
                                  autoload = True)
        cls.resource_table = Table('ckan_resource',
                                  cls.metadata,
                                  autoload = True)
        cls.engine.execute('delete from ckan_package')
        cls.engine.execute('delete from ckan_resource')
        cls.engine.execute('delete from ckan_package_extra')
        cls.engine.execute('delete from ckan_package_tag')
        cls.engine.execute('delete from node')
        cls.engine.execute('delete from node_revisions')
 def setup(cls):
     CreateTestData.create()
     for ag_name in [u'anauthzgroup', u'anotherauthzgroup']:
         ag=model.AuthorizationGroup.by_name(ag_name) 
         if not ag: #may already exist, if not create
             ag=model.AuthorizationGroup(name=ag_name)
             model.Session.add(ag)
     model.Session.commit()
Example #15
0
 def setup_class(cls):
     CreateTestData.create()
     cls._original_config = config.copy()
     wsgiapp = ckan.config.middleware.make_app(config['global_conf'],
                                               **config)
     cls.app = paste.fixture.TestApp(wsgiapp)
     cls.sysadmin_user = model.User.get('testsysadmin')
     PylonsTestCase.setup_class()
Example #16
0
    def setup_class(self):
        model.Session.remove()
        CreateTestData.create()

        self.packagename = u'testpkg'
        model.repo.new_revision()
        model.Session.add(model.Package(name=self.packagename))
        model.repo.commit_and_remove()
Example #17
0
 def setup_class(self):
     try:
         CreateTestData.delete()
     except:
         pass
     model.repo.init_db()
     model.Session.remove()
     CreateTestData.create()
Example #18
0
 def setup_class(cls):
     CreateTestData.create()
     cls._original_config = config.copy()
     wsgiapp = ckan.config.middleware.make_app(
         config['global_conf'], **config)
     cls.app = paste.fixture.TestApp(wsgiapp)
     cls.sysadmin_user = model.User.get('testsysadmin')
     PylonsTestCase.setup_class()
Example #19
0
    def setup_class(cls):
        cls.db = ManageDb('db')
        CreateTestData.create()

        # delete warandpeace
        rev = model.repo.new_revision()
        model.Package.by_name(u'warandpeace').delete()
        model.repo.commit_and_remove()
 def initial_data(self):
     # clean the db so we can run these tests on their own
     model.repo.rebuild_db()
     search.clear_all()
     CreateTestData.create()
     yield
     model.repo.rebuild_db()
     model.Session.remove()
Example #21
0
    def setup_class(self):
        search.clear()
        model.Session.remove()
        CreateTestData.create()

        # reduce extraneous logging
        from ckan.lib import activity_streams_session_extension
        activity_streams_session_extension.logger.level = 100
    def setup_class(cls):
        search.clear()
        CreateTestData.create()
        cls.sysadmin_user = model.User.get("testsysadmin")

        cls.sysadmin_action = TestAppCKAN(cls.app, str(cls.sysadmin_user.apikey)).action

        cls.example_pkg = [json.loads(j) for j in EXAMPLE_JSON_LINES.strip().split("\n")]
Example #23
0
    def setup_class(cls):
        cls.db = ManageDb('db')
        CreateTestData.create()

        # delete warandpeace
        rev = model.repo.new_revision()
        model.Package.by_name(u'warandpeace').delete()
        model.repo.commit_and_remove()
Example #24
0
    def setup_class(cls):
        """Set up testing environment."""

        kata_model.setup()
        CreateTestData.create()

        wsgiapp = make_app(config['global_conf'], **config['app_conf'])
        cls.app = paste.fixture.TestApp(wsgiapp)
Example #25
0
    def setup_class(self):
        search.clear_all()
        model.Session.remove()
        CreateTestData.create()

        # reduce extraneous logging
        from ckan.lib import activity_streams_session_extension
        activity_streams_session_extension.logger.level = 100
Example #26
0
    def setup_class(self):
        model.Session.remove()
        CreateTestData.create()

        self.packagename = u'testpkg'
        model.repo.new_revision()
        model.Session.add(model.Package(name=self.packagename))
        model.repo.commit_and_remove()
Example #27
0
 def setup_class(cls):
     CreateTestData.create()
     cls._original_config = config.copy()
     config['ckan.auth.create_user_via_web'] = True
     wsgiapp = ckan.config.middleware.make_app(
         config['global_conf'], **config)
     cls.app = helpers._get_test_app()
     cls.sysadmin_user = model.User.get('testsysadmin')
     PylonsTestCase.setup_class()
Example #28
0
 def setup_class(self):
     setup_test_search_index()
     model.Session.remove()
     CreateTestData.create()
     self.groupname = u'david'
     self.packagename = u'testpkg'
     model.repo.new_revision()
     model.Session.add(model.Package(name=self.packagename))
     model.repo.commit_and_remove()
Example #29
0
    def setup_class(self):
        model.repo.init_db()
        CreateTestData.create()
        CreateTestData.create_test_user()

        self.admin = model.User.by_name(u'testsysadmin')

        self.extra_environ_admin = {'REMOTE_USER': self.admin.name.encode('utf8')}
        self.extra_environ_tester = {'REMOTE_USER': '******'}
Example #30
0
 def setup_class(self):
     setup_test_search_index()
     model.Session.remove()
     CreateTestData.create()
     self.groupname = u'david'
     self.packagename = u'testpkg'
     model.repo.new_revision()
     model.Session.add(model.Package(name=self.packagename))
     model.repo.commit_and_remove()
Example #31
0
 def setup_class(self):
     # create test data
     CreateTestData.create()
     username = '******'
     user = model.User.by_name(unicode(username))
     assert user
     self.testclient = WsgiCkanClient(self.app,
                                      api_key=user.apikey,
                                      base_location='/api/2')
Example #32
0
    def setup_class(cls):
        cls.username = '******'
        cls.groupname = 'david'

        model.repo.new_revision()
        CreateTestData.create()
        cls.pkgs = [
            model.Package.by_name('warandpeace'),
            model.Package.by_name('annakarenina'),
        ]
Example #33
0
 def setup_class(cls):
     CreateTestData.create()
     cls._original_config = config.copy()
     config['ckan.auth.create_user_via_web'] = True
     new_authz.clear_auth_functions_cache()
     wsgiapp = ckan.config.middleware.make_app(
         config['global_conf'], **config)
     cls.app = paste.fixture.TestApp(wsgiapp)
     cls.sysadmin_user = model.User.get('testsysadmin')
     PylonsTestCase.setup_class()
Example #34
0
 def setup_class(cls):
     CreateTestData.create()
     cls._original_config = config.copy()
     config['ckan.auth.create_user_via_web'] = True
     new_authz.clear_auth_functions_cache()
     wsgiapp = ckan.config.middleware.make_app(config['global_conf'],
                                               **config)
     cls.app = paste.fixture.TestApp(wsgiapp)
     cls.sysadmin_user = model.User.get('testsysadmin')
     PylonsTestCase.setup_class()
Example #35
0
    def _create_test_data(cls):
        CreateTestData.create()

        # Remove visitor and logged in roles
        roles = []
        q = model.Session.query(model.UserObjectRole).\
            filter(model.UserObjectRole.user==model.User.by_name(u"visitor"))
        roles.extend(q.all())
        q = model.Session.query(model.UserObjectRole).\
            filter(model.UserObjectRole.user==model.User.by_name(u"logged_in"))
        roles.extend(q.all())
        for role in roles:
            model.Session.delete(role)

        rev = model.repo.new_revision()
        model.Session.add_all([
            model.User(name=u'pkggroupadmin'),
            model.User(name=u'site_reader'),
            model.User(name=u'outcast'),
            model.Package(name=cls.ENTITY_NAME),
            model.Package(name=u'deleted'),
            model.Group(name=cls.ENTITY_NAME),
            model.Group(name=u'deleted'),
            model.Tag(name=cls.ENTITY_NAME),
            model.RoleAction(role=cls.TRUSTED_ROLE,
                             context=u'',
                             action=model.Action.SITE_READ),
            model.RoleAction(role=cls.TRUSTED_ROLE,
                             context=u'',
                             action=model.Action.READ),
        ])
        model.repo.commit_and_remove()

        # testsysadmin is sysadmin
        # annafan is package admin for annakarenina
        rev = model.repo.new_revision()
        site_reader = model.User.by_name(u'site_reader')
        pkggroupadmin = model.User.by_name(u'pkggroupadmin')
        pkg = model.Package.by_name(cls.ENTITY_NAME)
        group = model.Group.by_name(cls.ENTITY_NAME)
        tag = model.Tag.by_name(cls.ENTITY_NAME)
        pkg.add_tag(tag)
        model.add_user_to_role(site_reader, cls.TRUSTED_ROLE, model.System())
        model.add_user_to_role(site_reader, cls.TRUSTED_ROLE, pkg)
        model.add_user_to_role(site_reader, cls.TRUSTED_ROLE, group)
        model.add_user_to_role(pkggroupadmin, model.Role.ADMIN, pkg)
        model.add_user_to_role(pkggroupadmin, model.Role.ADMIN, group)
        model.Package.by_name(u'deleted').delete()
        model.Group.by_name(u'deleted').delete()
        model.repo.commit_and_remove()

        cls.testsysadmin = model.User.by_name(u'testsysadmin')
        cls.pkggroupadmin = model.User.by_name(u'pkggroupadmin')
        cls.site_reader = model.User.by_name(u'site_reader')
        cls.outcast = model.User.by_name(u'outcast')
Example #36
0
    def setup_class(cls):
        search.clear()
        CreateTestData.create()
        cls.sysadmin_user = model.User.get('testsysadmin')

        cls.sysadmin_action = TestAppCKAN(cls.app,
                                          str(cls.sysadmin_user.apikey)).action

        cls.example_pkg = [
            json.loads(j) for j in EXAMPLE_JSON_LINES.strip().split('\n')
        ]
Example #37
0
    def setup_class(self):
        from ckan.tests.mock_publisher_auth import MockPublisherAuth
        self.auth = MockPublisherAuth()

        model.Session.remove()
        CreateTestData.create(auth_profile='publisher')
        self.groupname = u'david'
        self.packagename = u'testpkg'
        model.repo.new_revision()
        model.Session.add(model.Package(name=self.packagename))
        model.repo.commit_and_remove()
Example #38
0
    def setup_class(self):
        from ckan.tests.mock_publisher_auth import MockPublisherAuth
        self.auth = MockPublisherAuth()

        model.Session.remove()
        CreateTestData.create(auth_profile='publisher')
        self.groupname = u'david'
        self.packagename = u'testpkg'
        model.repo.new_revision()
        model.Session.add(model.Package(name=self.packagename))
        model.repo.commit_and_remove()
Example #39
0
    def setup_class(cls):
        search.clear()
        CreateTestData.create()
        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.normal_user = model.User.get('annafan')
        cls.publisher_user = model.User.get('russianfan')

        cls.sysadmin_action = TestAppCKAN(cls.app,
                                          str(cls.sysadmin_user.apikey)).action
        cls.normal_action = TestAppCKAN(cls.app,
                                        str(cls.normal_user.apikey)).action
        cls.publisher_action = TestAppCKAN(
            cls.app, str(cls.publisher_user.apikey)).action
        cls.action = TestAppCKAN(cls.app).action

        cls.sysadmin_action.organization_member_create(username='******',
                                                       id='nrcan-rncan',
                                                       role='editor')

        cls.sysadmin_action.organization_member_create(username='******',
                                                       id='tb-ct',
                                                       role='editor')

        cls.incomplete_pkg = {
            'title':
            u'A Novel By Tolstoy',
            'license_id':
            'ca-ogl-lgo',
            'resources': [{
                'name': u'Full text.',
                'name_fra': u'Full text.',
                'format': u'TXT',
                'url': u'http://www.annakarenina.com/download/',
                'size': 42,
                'resource_type': 'file',
                'language': 'zxx; CAN',
            }],
        }

        cls.override_possible_pkg = dict(cls.incomplete_pkg,
                                         owner_org='nrcan-rncan')

        cls.complete_pkg = dict(
            cls.override_possible_pkg,
            catalog_type=u'Data | Données',
            title_fra=u'Un novel par Tolstoy',
            maintenance_and_update_frequency=u'As Needed | Au besoin',
            notes=u'...',
            notes_fra=u'...',
            subject=[u'Persons  Personnes'],
            date_published=u'2013-01-01',
            keywords=u'book',
            keywords_fra=u'livre')
Example #40
0
    def _create_test_data(cls):
        CreateTestData.create()

        # Remove visitor and logged in roles
        roles = []
        q = model.Session.query(model.UserObjectRole).\
            filter(model.UserObjectRole.user==model.User.by_name(u"visitor"))
        roles.extend(q.all())
        q = model.Session.query(model.UserObjectRole).\
            filter(model.UserObjectRole.user==model.User.by_name(u"logged_in"))
        roles.extend(q.all())
        for role in roles:
            model.Session.delete(role)

        rev = model.repo.new_revision()
        model.Session.add_all([
            model.User(name=u'pkggroupadmin'),
            model.User(name=u'site_reader'),
            model.User(name=u'outcast'),
            model.Package(name=cls.ENTITY_NAME),
            model.Package(name=u'deleted'),
            model.Group(name=cls.ENTITY_NAME),
            model.Group(name=u'deleted'),
            model.Tag(name=cls.ENTITY_NAME),
            model.RoleAction(role=cls.TRUSTED_ROLE, context=u'',
                             action=model.Action.SITE_READ),
            model.RoleAction(role=cls.TRUSTED_ROLE, context=u'',
                             action=model.Action.READ),
            ])
        model.repo.commit_and_remove()

        # testsysadmin is sysadmin
        # annafan is package admin for annakarenina
        rev = model.repo.new_revision()
        site_reader = model.User.by_name(u'site_reader')
        pkggroupadmin = model.User.by_name(u'pkggroupadmin')
        pkg = model.Package.by_name(cls.ENTITY_NAME)
        group = model.Group.by_name(cls.ENTITY_NAME)
        tag = model.Tag.by_name(cls.ENTITY_NAME)
        pkg.add_tag(tag)
        model.add_user_to_role(site_reader, cls.TRUSTED_ROLE, model.System())
        model.add_user_to_role(site_reader, cls.TRUSTED_ROLE, pkg)
        model.add_user_to_role(site_reader, cls.TRUSTED_ROLE, group)
        model.add_user_to_role(pkggroupadmin, model.Role.ADMIN, pkg)
        model.add_user_to_role(pkggroupadmin, model.Role.ADMIN, group)
        model.Package.by_name(u'deleted').delete()
        model.Group.by_name(u'deleted').delete()
        model.repo.commit_and_remove()

        cls.testsysadmin = model.User.by_name(u'testsysadmin')
        cls.pkggroupadmin = model.User.by_name(u'pkggroupadmin')
        cls.site_reader = model.User.by_name(u'site_reader')
        cls.outcast = model.User.by_name(u'outcast')
Example #41
0
    def test_package_to_api2(self):
        CreateTestData.create()
        context = {"model": model, "session": model.Session}

        pkg = model.Package.get("annakarenina")
        as_dict = pkg.as_dict(ref_package_by="id", ref_group_by="id")
        dictize = package_to_api2(pkg, context)

        as_dict_string = pformat(as_dict)
        dictize_string = pformat(dictize)

        assert package_to_api2(pkg, context) == dictize, "\n".join(
            unified_diff(as_dict_string.split("\n"),
                         dictize_string.split("\n")))
Example #42
0
    def test_tag_autocomplete(self):
        CreateTestData.create()

        url = url_for(controller='api', action='tag_autocomplete')
        assert_equal(url, '/api/2/util/tag/autocomplete')
        response = self.app.get(
            url=url,
            params={
               'incomplete': u'ru',
            },
            status=200,
        )
        assert_equal(response.body, '{"ResultSet": {"Result": [{"Name": "russian"}]}}')
        assert_equal(response.header('Content-Type'), 'application/json;charset=utf-8')
Example #43
0
    def test_package_to_api1(self):
        CreateTestData.create()
        context = {"model": model, "session": model.Session}
        pkg = model.Package.get("annakarenina")
        asdict = pkg.as_dict()
        asdict["download_url"] = asdict["resources"][0]["url"]
        asdict["license_title"] = u"Other (Open)"
        asdict["num_tags"] = 3
        asdict["num_resources"] = 2

        dictize = package_to_api1(pkg, context)
        # the is_dict method doesn't care about organizations
        del dictize["organization"]
        assert dictize == asdict
Example #44
0
    def test_get_pkg_dict_extra(self):

        from ckan.lib.create_test_data import CreateTestData
        from ckan import model
        from ckan.logic import get_action

        CreateTestData.create()

        pkg_dict = get_action('package_show')({'model': model, 'user': u'tester'}, {'id': 'annakarenina'})

        assert_equal(h.get_pkg_dict_extra(pkg_dict, 'genre'), '"romantic novel"')

        assert_equal(h.get_pkg_dict_extra(pkg_dict, 'extra_not_found'), None)

        assert_equal(h.get_pkg_dict_extra(pkg_dict, 'extra_not_found', 'default_value'), 'default_value')
Example #45
0
    def test_get_pkg_dict_extra(self):

        from ckan.lib.create_test_data import CreateTestData
        from ckan import model
        from ckan.logic import get_action

        CreateTestData.create()

        pkg_dict = get_action("package_show")({"model": model, "user": u"tester"}, {"id": "annakarenina"})

        assert_equal(h.get_pkg_dict_extra(pkg_dict, "genre"), "romantic novel")

        assert_equal(h.get_pkg_dict_extra(pkg_dict, "extra_not_found"), None)

        assert_equal(h.get_pkg_dict_extra(pkg_dict, "extra_not_found", "default_value"), "default_value")
Example #46
0
    def initial_data(self, clean_db):
        CreateTestData.create()
        pkg = model.Package(name=self.non_active_name)
        model.Session.add(pkg)
        model.repo.commit_and_remove()

        pkg = (model.Session.query(
            model.Package).filter_by(name=self.non_active_name).one())
        admin = model.User.by_name(u"joeadmin")
        model.repo.commit_and_remove()

        pkg = (model.Session.query(
            model.Package).filter_by(name=self.non_active_name).one())
        pkg.delete()  # becomes non active
        model.repo.commit_and_remove()
Example #47
0
    def setup_class(cls):

        CreateTestData.create()
        cls.tester_user = model.User.by_name(u'tester')
        cls.extra_environ_admin = {'REMOTE_USER': '******'}
        cls.extra_environ_tester = {'REMOTE_USER': '******'}
        cls.extra_environ_someone_else = {'REMOTE_USER': '******'}

        tests.call_action_api(cls.app, 'organization_create',
                                        name='test_org_2',
                                        apikey=cls.tester_user.apikey)

        tests.call_action_api(cls.app, 'package_create',
                                        name='crimeandpunishment',
                                        owner_org='test_org_2',
                                        apikey=cls.tester_user.apikey)
Example #48
0
    def setup_class(self):
        CreateTestData.create()
        self.non_active_name = u'test_nonactive'
        pkg = model.Package(name=self.non_active_name)
        model.repo.new_revision()
        model.Session.add(pkg)
        model.repo.commit_and_remove()

        pkg = model.Session.query(model.Package).filter_by(name=self.non_active_name).one()
        admin = model.User.by_name(u'joeadmin')
        model.repo.commit_and_remove()

        model.repo.new_revision()
        pkg = model.Session.query(model.Package).filter_by(name=self.non_active_name).one()
        pkg.delete() # becomes non active
        model.repo.commit_and_remove()
Example #49
0
    def initial_data(self, clean_db, app):
        CreateTestData.create()
        users = {}
        tester = model.User.by_name(u"tester")
        tests.call_action_api(app,
                              "organization_create",
                              name="test_org_2",
                              apikey=tester.apikey)

        tests.call_action_api(
            app,
            "package_create",
            name="crimeandpunishment",
            owner_org="test_org_2",
            apikey=tester.apikey,
        )
Example #50
0
    def test_tag_autocomplete(self):
        CreateTestData.create()

        url = url_for(controller='api', action='tag_autocomplete')
        assert_equal(url, '/api/2/util/tag/autocomplete')
        response = self.app.get(
            url=url,
            params={
                'incomplete': u'ru',
            },
            status=200,
        )
        assert_equal(response.body,
                     '{"ResultSet": {"Result": [{"Name": "russian"}]}}')
        assert_equal(response.header('Content-Type'),
                     'application/json;charset=utf-8')
Example #51
0
    def test_table_simple_save(self):
        CreateTestData.create()
        context = {"model": model, "session": model.Session}
        anna1 = model.Package.get("annakarenina")

        anna_dictized = self.remove_changable_columns(
            table_dictize(anna1, context))

        anna_dictized["name"] = "annakarenina2"

        table_dict_save(anna_dictized, model.Package, context)
        model.Session.commit()
        pkg = model.Package.get("annakarenina2")
        assert (self.remove_changable_columns(table_dictize(
            pkg, context)) == anna_dictized), self.remove_changable_columns(
                table_dictize(pkg, context))
Example #52
0
    def test_get_pkg_dict_extra(self):

        from ckan.lib.create_test_data import CreateTestData
        from ckan import model
        from ckan.logic import get_action

        CreateTestData.create()

        pkg_dict = get_action('package_show')({'model': model, 'user': u'tester'}, {'id': 'annakarenina'})

        assert_equal(h.get_pkg_dict_extra(pkg_dict, 'genre'), 'romantic novel')

        assert_equal(h.get_pkg_dict_extra(pkg_dict, 'extra_not_found'), None)

        assert_equal(h.get_pkg_dict_extra(pkg_dict, 'extra_not_found', 'default_value'), 'default_value')

        model.repo.rebuild_db()
Example #53
0
    def setup(self):
        model.repo.init_db()
        CreateTestData.create()
        self.package_name = u'formsapi'
        self.package_name_alt = u'formsapialt'
        self.package_name_alt2 = u'formsapialt2'
        self.apikey_header_name = config.get('apikey_header_name',
                                             'X-CKAN-API-Key')

        self.user = self.get_user_by_name(u'tester')
        if not self.user:
            self.user = self.create_user(name=u'tester')
        self.user = self.get_user_by_name(u'tester')
        model.add_user_to_role(self.user, model.Role.ADMIN, model.System())
        model.repo.commit_and_remove()
        self.extra_environ = {self.apikey_header_name: str(self.user.apikey)}
        self.create_package(name=self.package_name)
Example #54
0
def test_get_pkg_dict_extra():

    from ckan.lib.create_test_data import CreateTestData
    from ckan import model

    CreateTestData.create()

    pkg_dict = helpers.call_action("package_show", id="annakarenina")

    assert h.get_pkg_dict_extra(pkg_dict, "genre") == "romantic novel"

    assert h.get_pkg_dict_extra(pkg_dict, "extra_not_found") is None

    assert (h.get_pkg_dict_extra(pkg_dict, "extra_not_found",
                                 "default_value") == "default_value")

    model.repo.rebuild_db()
Example #55
0
    def test_overall(self):
        CreateTestData.create()
        query = search.query_for(model.Package)
        assert query.run({"q": "annakarenina"})["count"] == 1
        assert query.run({"q": "warandpeace"})["count"] == 1
        assert query.run({"q": ""})["count"] == 2

        assert query.run({"q": "Tolstoy"})["count"] == 1
        assert query.run({"q": "title:Novel"})["count"] == 1
        assert query.run({"q": "title:peace"})["count"] == 0
        assert query.run({"q": "name:warandpeace"})["count"] == 1
        assert query.run({"q": "groups:david"})["count"] == 2
        assert query.run({"q": "groups:roger"})["count"] == 1
        assert query.run({"q": "groups:lenny"})["count"] == 0
        assert query.run({"q": 'tags:"russian"'})["count"] == 2
        assert query.run({"q": 'tags:"Flexible \u30a1"'})["count"] == 2
        assert query.run({"q": "Flexible \u30a1"})["count"] == 2
        assert query.run({"q": "Flexible"})["count"] == 2
        assert query.run({"q": "flexible"})["count"] == 2
Example #56
0
    def test_resource_no_id(self):
        CreateTestData.create()
        context = {"model": model, "session": model.Session}

        new_resource = {
            "mimetype": None,
            u"alt_url": u"empty resource group id",
            "hash": u"abc123",
            "description": u'Full text. Needs escaping: " Umlaut: \xfc',
            "format": u"plain text",
            "url": u"http://test_new",
            "cache_url": None,
            "cache_last_updated": None,
            "state": u"active",
            "mimetype_inner": None,
            "url_type": None,
            "last_modified": None,
            "position": 0,
            "size": None,
            "size_extra": u"123",
            "resource_type": None,
            "name": None,
            "package_id": "",  # Just so we can save
        }

        resource_dict_save(new_resource, context)
        model.Session.commit()
        model.Session.remove()

        # Remove the package id
        del new_resource["package_id"]

        res = (
            model.Session.query(model.Resource)
            .filter_by(url=u"http://test_new")
            .one()
        )

        res_dictized = self.remove_changable_columns(
            resource_dictize(res, context), True
        )

        assert res_dictized == new_resource, res_dictized
Example #57
0
    def test_user_dictize_as_anonymous(self):
        """Anonymous should not be able to see other's sensitive data."""
        CreateTestData.create()
        context = {"model": model, "session": model.Session, "user": ""}

        user = model.User.by_name("tester")

        user_dict = user_dictize(user, context)

        # Check some of the non-sensitive data
        assert "name" in user_dict
        assert "about" in user_dict

        # Check sensitive data is not available
        assert "apikey" not in user_dict
        assert "reset_key" not in user_dict
        assert "email" not in user_dict

        # Passwords should never be available
        assert "password" not in user_dict
Example #58
0
    def test_user_dictize_as_same_user(self):
        """User should be able to see their own sensitive data."""
        CreateTestData.create()
        context = {"model": model, "session": model.Session, "user": "******"}

        user = model.User.by_name("tester")

        user_dict = user_dictize(user, context)

        # Check some of the non-sensitive data
        assert "name" in user_dict
        assert "about" in user_dict

        # Check sensitive data is available
        assert "apikey" in user_dict
        assert "email" in user_dict

        # Passwords and reset keys should never be available
        assert "password" not in user_dict
        assert "reset_key" not in user_dict