Пример #1
0
    def test_relogin(self):
        """Login as user A and then (try to) login as user B (without
        logout). #1799."""
        # create test users A & B
        password = u"letmein"
        CreateTestData.create_user(name=u"user_a", password=password)
        CreateTestData.create_user(name=u"user_b", password=password)
        userA = model.User.by_name(u"user_a")
        userB = model.User.by_name(u"user_b")

        # do the login
        offset = url_for(controller="user", action="login")
        res = self.app.get(offset)
        fv = res.forms["login"]
        fv["login"] = "******"
        fv["password"] = str(password)
        res = fv.submit()
        while res.status == 302:
            res = res.follow()
        assert_equal(res.status, 200)

        # login as userB
        offset = url_for(controller="user", action="login")
        res = self.app.get(offset)
        assert not res.forms.has_key("login")  # i.e. no login box is presented
        assert "To register or log in as another user" in res.body, res.body
        assert "logout" in res.body, res.body
Пример #2
0
    def test_login_wrong_password(self):
        # create test user
        username = u"testloginwrong"
        password = u"letmein"
        CreateTestData.create_user(name=username, password=password)
        user = model.User.by_name(username)

        # do the login
        offset = url_for(controller="user", action="login")
        res = self.app.get(offset)
        fv = res.forms["login"]
        fv["login"] = username
        fv["password"] = "******"
        res = fv.submit()

        # first get redirected to logged_in
        assert_equal(res.status, 302)
        assert res.header("Location").startswith("http://localhost/user/logged_in") or res.header(
            "Location"
        ).startswith("/user/logged_in")

        # then get redirected to login
        res = res.follow()
        assert_equal(res.status, 302)
        assert res.header("Location").startswith("http://localhost/user/login") or res.header("Location").startswith(
            "/user/login"
        )
        res = res.follow()
        assert_equal(res.status, 200)
        assert "Login failed. Bad username or password." in res.body
        assert "Login:" in res.body
Пример #3
0
    def setup_class(cls):
        smtp_server = config.get("test_smtp_server")
        if smtp_server:
            host, port = smtp_server.split(":")
            port = int(port) + int(str(hashlib.md5(cls.__name__).hexdigest())[0], 16)
            config["test_smtp_server"] = "%s:%s" % (host, port)

        PylonsTestCase.setup_class()
        SmtpServerHarness.setup_class()
        CreateTestData.create()

        # make 3 changes, authored by annafan
        for i in range(3):
            rev = model.repo.new_revision()
            pkg = model.Package.by_name(u"annakarenina")
            pkg.notes = u"Changed notes %i" % i
            rev.author = u"annafan"
            model.repo.commit_and_remove()

        CreateTestData.create_user("unfinisher", about='<a href="http://unfinished.tag')
        CreateTestData.create_user("uncloser", about='<a href="http://unclosed.tag">')
        CreateTestData.create_user(
            "spammer", about=u'<a href="http://mysite">mysite</a> <a href=\u201dhttp://test2\u201d>test2</a>'
        )
        CreateTestData.create_user(
            "spammer2",
            about=u'<a href="http://spamsite1.com\u201d>spamsite1</a>\r\n<a href="http://www.spamsite2.com\u201d>spamsite2</a>\r\n',
        )
Пример #4
0
    def test_login_wrong_password(self):
        # create test user
        username = u'testloginwrong'
        password = u'letmein'
        CreateTestData.create_user(name=username,
                                   password=password)
        user = model.User.by_name(username)

        # do the login
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fv = res.forms['login']
        fv['login'] = username
        fv['password'] = '******'
        res = fv.submit()

        # first get redirected to logged_in
        assert_equal(res.status, 302)
        assert res.header('Location').startswith('http://localhost/user/logged_in')

        # then get redirected to login
        res = res.follow()
        assert_equal(res.status, 302)
        assert res.header('Location').startswith('http://localhost/user/login')
        res = res.follow()
        assert_equal(res.status, 200)
        assert 'Login failed. Bad username or password.' in res.body
        assert 'Login:' in res.body
Пример #5
0
    def test_zharvester_import(self, mocked=True):
        harvest_object, harv = self._create_harvester()
        self.assert_(harv.info()['name'] == 'OAI-PMH')
        real_content = json.loads(harvest_object.content)
        self.assert_(real_content)
        self.assert_(harv.import_stage(harvest_object))

        the_package = Session.query(Package).filter(Package.title == u"homer")
        print the_package
        the_package = the_package[0]
        self.assert_(the_package)
        self.assert_(len(the_package.get_tags()) == 4)
        self.assert_(len(the_package.get_groups()) == 3)
        self.assert_(the_package.url == "http://helda.helsinki.fi/oai/request?verb=GetRecord&identifier=%s&metadataPrefix=oai_dc" % the_package.id)
        # Test with empty request
        Session.remove()
        CreateTestData.delete()
        Session.query(Package).delete()
        harvest_object, harv = self._create_harvester(config=False)
        real_content = json.loads(harvest_object.content)
        self.assert_(harv.import_stage(harvest_object) == False)
        errs = Session.query(HarvestGatherError).all()
        self.assert_(len(errs) == 2)
        errs = Session.query(HarvestObjectError).all()
        self.assert_(len(errs) == 3)
Пример #6
0
    def test_request_reset_user_password_using_search(self):
        CreateTestData.create_user(name='larry1', email='*****@*****.**')
        offset = url_for(controller='user',
                         action='request_reset')
        res = self.app.get(offset)
        fv = res.forms['user-password-reset']
        fv['user'] = '******'
        res = fv.submit()
        assert_equal(res.status, 302)
        assert_equal(res.header_dict['Location'], 'http://localhost/')

        CreateTestData.create_user(name='larry2', fullname='kittens')
        res = self.app.get(offset)
        fv = res.forms['user-password-reset']
        fv['user'] = '******'
        res = fv.submit()
        assert '&#34;kittens&#34; matched several users' in res, res
        assert 'larry1' not in res, res
        assert 'larry2' not in res, res

        res = self.app.get(offset)
        fv = res.forms['user-password-reset']
        fv['user'] = ''
        res = fv.submit()
        assert 'No such user:'******'user-password-reset']
        fv['user'] = '******'
        res = fv.submit()
        assert 'No such user:' in res, res
 def setup_class(cls):
     config = appconfig('config:test.ini', relative_to=conf_dir)
     config.local_conf['ckan.plugins'] = 'todo'
     wsgiapp = make_app(config.global_conf, **config.local_conf)
     cls.app = paste.fixture.TestApp(wsgiapp)
     CreateTestData.create()
     CreateTodoTestData.create()
Пример #8
0
    def setup(self):

        model.Session.remove()
        CreateTestData.create(auth_profile='publisher')
        self.sysadmin_user = model.User.get('testsysadmin')
        self.normal_user = model.User.get('annafan') # Does not belong to a publisher
        self.publisher1_user = model.User.by_name('russianfan')
        self.publisher2_user = model.User.by_name('tester')

        # Create two Publishers
        rev = model.repo.new_revision()
        self.publisher1 = model.Group(name=u'test-publisher1',title=u'Test Publihser 1',type=u'publisher')
        Session.add(self.publisher1)
        self.publisher2 = model.Group(name=u'test-publisher2',title=u'Test Publihser 2',type=u'publisher')
        Session.add(self.publisher2)

        member1 = model.Member(table_name = 'user',
                         table_id = self.publisher1_user.id,
                         group=self.publisher1,
                         capacity='admin')
        Session.add(member1)
        member2 = model.Member(table_name = 'user',
                         table_id = self.publisher2_user.id,
                         group=self.publisher2,
                         capacity='admin')
        Session.add(member2)

        Session.commit()
Пример #9
0
    def test_reset_user_password_link(self):
        # Set password
        CreateTestData.create_user(name="bob", email="*****@*****.**", password="******")

        # Set password to something new
        model.User.by_name(u"bob").password = "******"
        model.repo.commit_and_remove()
        test2_encoded = model.User.by_name(u"bob").password
        assert test2_encoded != "test2"
        assert model.User.by_name(u"bob").password == test2_encoded

        # Click link from reset password email
        create_reset_key(model.User.by_name(u"bob"))
        reset_password_link = get_reset_link(model.User.by_name(u"bob"))
        offset = reset_password_link.replace("http://test.ckan.net", "")
        res = self.app.get(offset)

        # Reset password form
        fv = res.forms["user-reset"]
        fv["password1"] = "test1"
        fv["password2"] = "test1"
        res = fv.submit("save", status=302)

        # Check a new password is stored
        assert model.User.by_name(u"bob").password != test2_encoded
Пример #10
0
    def test_register_whilst_logged_in(self):
        """Start registration form as user B then in another window login
        as user A, and then try and then submit form for user B. #1799."""
        # create user A
        password = u"letmein"
        CreateTestData.create_user(name=u"user_a__", password=password)
        userA = model.User.by_name(u"user_a__")
        # make him a sysadmin, to ensure he is allowed to create a user
        model.add_user_to_role(userA, model.Role.ADMIN, model.System())
        model.repo.commit_and_remove()
        userA = model.User.by_name(u"user_a__")

        # start to register user B
        offset = url_for(controller="user", action="register")
        res = self.app.get(offset)
        fvA = res.forms["user-edit"]
        fvA["name"] = "user_b_"
        fvA["fullname"] = "User B"
        fvA["email"] = "*****@*****.**"
        fvA["password1"] = password
        fvA["password2"] = password

        # login user A
        offset = url_for(controller="user", action="login")
        res = self.app.get(offset)
        fvB = res.forms["login"]
        fvB["login"] = "******"
        fvB["password"] = str(password)
        res = fvB.submit()
        while res.status == 302:
            res = res.follow()
        assert_equal(res.status, 200)

        # finish registration of user B
        res = fvA.submit("save")
        assert_equal(res.status, 200)
        assert "user_a__</a> is currently logged in" in res.body, res.body
        assert (
            'User "user_b_" is now registered but you are still logged in as "user_a__" from before'.replace(
                '"', "&#34;"
            )
            in res.body
        ), res.body
        assert "logout" in res.body, res.body

        # logout and login as user B
        res = self.app.get("/user/logout")
        res2 = res.follow()
        res2 = res2.follow()
        assert "You have logged out successfully." in res2, res2
        offset = url_for(controller="user", action="login")
        res = self.app.get(offset)
        fv = res.forms["login"]
        fv["login"] = "******"
        fv["password"] = str(password)
        res = fv.submit()
        while res.status == 302:
            res = res.follow()
        assert_equal(res.status, 200)
        assert "User B is now logged in" in res.body, res.body
Пример #11
0
    def setup_class(self):
        super(TestDeletedDecoyWhenAdmin, self).setup_class()
        try:
            self.orig_pkg_dict = {
                "name": u"quarterly_epidemiological_commentary",
                "title": "Quarterly Epidemiological Commentary",
                "version": None, "url": None, "author": None, "author_email": None, "maintainer": None, "maintainer_email": None,
                "notes": "Epidemiological analyses of Mandatory surveillance data on MRSA bacteraemia and C. difficile infection covering at least nine quarters\r\nSource agency: Health Protection Agency\r\nDesignation: Official Statistics not designated as National Statistics\r\nLanguage: English\r\nAlternative title: Quarterly Epi Commentary",
                "license_id": "uk-ogl",
                "tags": ["conditions-and-diseases", "health", "health-and-social-care", "health-of-the-population", "nhs-trust-hcai-pct-mrsa-mrsa-bacteraemia-c-difficile-c-diff-clostridium-difficile-healthcare-associa", "well-being-and-care"],
                "groups": ['health-protection-agency'],
                "extras": {
                    "geographic_coverage": "100000: England",
                    "geographic_granularity": "Other",
                    "external_reference": "ONSHUB",
                    "temporal_coverage-from": "",
                    "temporal_granularity": "",
                    "date_updated": "",
                    "precision": "",
                    "geographic_granularity": "",
                    "temporal_coverage_to": "",
                    "temporal_coverage_from": "",
                    "taxonomy_url": "",
                    "import_source": "ONS-ons_data_7_days_to_2010-06-23",
                    "date_released": "2010-06-18",
                    "temporal_coverage-to": "",
                    "update_frequency": "quarterly",
                    "national_statistic": "no",
                    "categories": "Health and Social Care"
                    },
                "resources": []            
                }
            self.deleted_decoy_pkg_dict = {
                "name": u"quarterly_epidemiological_commentary_-_none",
                "title": "Quarterly Epidemiological Commentary",
                "groups": ['health-protection-agency'],
                }
            CreateTestData.create_arbitrary([self.orig_pkg_dict])
            CreateTestData.create_arbitrary([self.deleted_decoy_pkg_dict],
                                            extra_user_names=[u'testsysadmin'])

            # make a sysadmin user
            rev = model.repo.new_revision()
            testsysadmin = model.User.by_name(u'testsysadmin')
            model.add_user_to_role(testsysadmin, model.Role.ADMIN, model.System())

            # delete decoy
            decoy_pkg = model.Package.by_name(self.deleted_decoy_pkg_dict['name'])
            assert decoy_pkg
            decoy_pkg.delete()
            model.repo.commit_and_remove()

            # same data is imported, but should find record and add department
            importer_ = importer.OnsImporter(sample_filepath(9), self.testclient)
            self.pkg_dict = [pkg_dict for pkg_dict in importer_.pkg_dict()][0]
        except:
            # ensure that mock_drupal is destroyed
            MockDrupalCase.teardown_class()
            model.repo.rebuild_db()
            raise
Пример #12
0
 def test_perform_reset_user_password_link_key_missing(self):
     CreateTestData.create_user(name='jack', password='******')
     user = model.User.by_name(u'jack')
     offset = url_for(controller='user',
                      action='perform_reset',
                      id=user.id)  # not, no key specified
     res = self.app.get(offset, status=403) # error
Пример #13
0
    def test_login_remembered(self):
        # create test user
        username = u'testlogin2'
        password = u'letmein'
        CreateTestData.create_user(name=username,
                                   password=password)
        user = model.User.by_name(username)

        # do the login
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fv = res.forms['login']
        fv['login'] = str(username)
        fv['password'] = str(password)
        fv['remember'] = True
        res = fv.submit()

        # check cookies set
        cookies = self._get_cookie_headers(res)
        assert cookies
        # check cookie is remembered via Max-Age and Expires
        # (both needed for cross-browser compatibility)
        for cookie in cookies:
            assert 'Max-Age=63072000;' in cookie, cookie
            assert 'Expires=' in cookie, cookie
Пример #14
0
    def test_relogin(self):
        '''Login as user A and then (try to) login as user B (without
        logout). #1799.'''
        # create test users A & B
        password = u'letmein'
        CreateTestData.create_user(name=u'user_a',
                                   password=password)
        CreateTestData.create_user(name=u'user_b',
                                   password=password)
        userA = model.User.by_name(u'user_a')
        userB = model.User.by_name(u'user_b')

        # do the login
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fv = res.forms['login']
        fv['login'] = '******'
        fv['password'] = str(password)
        res = fv.submit()
        while res.status == 302:
            res = res.follow()
        assert_equal(res.status, 200)

        # login as userB
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        assert not res.forms.has_key('login') # i.e. no login box is presented
        assert 'To register or log in as another user' in res.body, res.body
        assert 'logout' in res.body, res.body
Пример #15
0
    def test_try_to_register_whilst_logged_in(self):
        """Login as user A and then (try to) register user B (without
        logout). #1799."""
        # create user A
        password = u"letmein"
        CreateTestData.create_user(name=u"user_a_", password=password)
        userA = model.User.by_name(u"user_a_")

        # do the login
        offset = url_for(controller="user", action="login")
        res = self.app.get(offset)
        fv = res.forms["login"]
        fv["login"] = "******"
        fv["password"] = str(password)
        res = fv.submit()
        while res.status == 302:
            res = res.follow()
        assert_equal(res.status, 200)

        # try to register
        offset = url_for(controller="user", action="register")
        res = self.app.get(offset)
        assert not res.forms.has_key("Password")  # i.e. no registration form
        assert "To register or log in as another user" in res.body, res.body
        assert "logout" in res.body, res.body
Пример #16
0
    def test_try_to_register_whilst_logged_in(self):
        '''Login as user A and then (try to) register user B (without
        logout). #1799.'''
        # create user A
        password = u'letmein'
        CreateTestData.create_user(name=u'user_a_',
                                   password=password)
        userA = model.User.by_name(u'user_a_')

        # do the login
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fv = res.forms['login']
        fv['login'] = '******'
        fv['password'] = str(password)
        res = fv.submit()
        while res.status == 302:
            res = res.follow()
        assert_equal(res.status, 200)

        # try to register
        offset = url_for(controller='user', action='register')
        res = self.app.get(offset)
        assert not res.forms.has_key('Password') # i.e. no registration form
        assert 'To register or log in as another user' in res.body, res.body
        assert 'logout' in res.body, res.body
Пример #17
0
    def setup_class(self):
        super(TestOnsLoadMissingDept, self).setup_class()

        try:
            self.orig_pkg_dict = {
                 "name": u"measuring_subjective_wellbeing_in_the_uk",
                 "title": "Measuring Subjective Wellbeing in the UK",
                 "notes": "This report reviews:\n\nWhat is subjective wellbeing and why should we measure it?\n\nHow subjective wellbeing is currently measured in the UK - what subjective wellbeing questions are already being asked on major social surveys in the UK\n\nThe potential uses of subjective wellbeing data collected via these surveys\n\n\nIt concludes that subjective wellbeing is a valid construct that can be measured reliably. This is the first output of ONS' work on subjective wellbeing.\n\nSource agency: Office for National Statistics\n\nDesignation: Supporting material\n\nLanguage: English\n\nAlternative title: Working Paper: Measuring Subjective Wellbeing in the UK",
                 "license_id": "ukcrown-withrights",
                 "tags": ["communities", "health-well-being-and-care", "people-and-places", "societal-wellbeing", "subjective-wellbeing-subjective-well-being-objective-measures-subjective-measures", "well-being"],
                 "groups": ['office-for-national-statistics'],
                 "extras": {"geographic_coverage": "111100: United Kingdom (England, Scotland, Wales, Northern Ireland)", "geographic_granularity": "UK and GB", "external_reference": "ONSHUB", "temporal_granularity": "", "date_updated": "", "precision": "", "temporal_coverage_to": "", "temporal_coverage_from": "", "national_statistic": "no", "import_source": "ONS-ons_data_7_days_to_2010-09-17", "update_frequency": "", "date_released": "2010-09-14", "categories": "People and Places"},
                "resources": [{"url": "http://www.ons.gov.uk/about-statistics/measuring-equality/wellbeing/news-and-events/index.html", "format": "", "description": "2010", "extras":{"hub-id":"77-31166"}}],
                 }
            CreateTestData.create_arbitrary([self.orig_pkg_dict])

            # same data is imported, but should find record and add department
            importer_ = importer.OnsImporter(sample_filepath(5), self.testclient)
            self.pkg_dict = [pkg_dict for pkg_dict in importer_.pkg_dict()][0]
            loader = OnsLoader(self.testclient)
            self.res = loader.load_package(self.pkg_dict)
        except:
            # ensure that mock_drupal is destroyed
            MockDrupalCase.teardown_class()
            model.repo.rebuild_db()
            raise
Пример #18
0
    def test_request_reset_user_password_using_search(self):
        CreateTestData.create_user(name="larry1", email="*****@*****.**")
        offset = url_for(controller="user", action="request_reset")
        res = self.app.get(offset)
        fv = res.forms["user-password-reset"]
        fv["user"] = "******"
        res = fv.submit()
        assert_equal(res.status, 302)
        assert_equal(res.header_dict["Location"], "http://localhost/?__no_cache__=True")

        CreateTestData.create_user(name="larry2", fullname="kittens")
        res = self.app.get(offset)
        fv = res.forms["user-password-reset"]
        fv["user"] = "******"
        res = fv.submit()
        assert "&#34;kittens&#34; matched several users" in res, res
        assert "larry1" not in res, res
        assert "larry2" not in res, res

        res = self.app.get(offset)
        fv = res.forms["user-password-reset"]
        fv["user"] = ""
        res = fv.submit()
        assert "No such user:"******"user-password-reset"]
        fv["user"] = "******"
        res = fv.submit()
        assert "No such user:" in res, res
Пример #19
0
    def test_reset_user_password_link(self):
        # Set password
        CreateTestData.create_user(name='bob', email='*****@*****.**', password='******')

        # Set password to something new
        model.User.by_name(u'bob').password = '******'
        model.repo.commit_and_remove()
        test2_encoded = model.User.by_name(u'bob').password
        assert test2_encoded != 'test2'
        assert model.User.by_name(u'bob').password == test2_encoded

        # Click link from reset password email
        create_reset_key(model.User.by_name(u'bob'))
        reset_password_link = get_reset_link(model.User.by_name(u'bob'))
        offset = reset_password_link.replace('http://test.ckan.net', '')
        print offset
        res = self.app.get(offset)

        # Reset password form
        fv = res.forms['user-reset']
        fv['password1'] = 'test1'
        fv['password2'] = 'test1'
        res = fv.submit('save', status=302)

        # Check a new password is stored
        assert model.User.by_name(u'bob').password != test2_encoded
Пример #20
0
 def setup_class(self):
     """
     Remove any initial sessions.
     """
     Session.remove()
     # TODO: Should also remove test data
     CreateTestData.create()
     self.sysadmin = model.User.get('testsysadmin')
 def create_packages(cls):
     CreateTestData.create_user('tester', about='A tester', password='******')
     for dtype, packages in cls.packages.items(): 
         for source_lang, langs, name, pkg in packages:
             ctx = make_api_context('tester')
             pkg_result = create_action(ctx, pkg)
             pkg['id'] = pkg_result['id']
             pkg[dtype]['identifier'] = pkg_result[dtype].identifier
     return
Пример #22
0
 def setup_class(cls):
     setup_test_search_index()
     init_data = [
         {"name": "a", "extras": {"department": "abc", "agency": "ag-a"}},
         {"name": "b", "extras": {"department": "bcd", "agency": "ag-b"}},
         {"name": "c", "extras": {"department": "cde abc"}},
         {"name": "none", "extras": {"department": ""}},
     ]
     CreateTestData.create_arbitrary(init_data)
Пример #23
0
 def setup_class(cls):
     """
     Remove any initial sessions.
     """
     Session.remove()
     CreateTestData.create()
     url = url_for(controller="ckanext.sitemap.controller:SitemapController", action="view")
     cls.cont = cls.app.get(url)
     cls.content_file = StringIO(cls.cont.body)
Пример #24
0
    def test_register_whilst_logged_in(self):
        '''Start registration form as user B then in another window login
        as user A, and then try and then submit form for user B. #1799.'''
        # create user A
        password = u'letmein'
        CreateTestData.create_user(name=u'user_a__',
                                   password=password)
        userA = model.User.by_name(u'user_a__')
        # make him a sysadmin, to ensure he is allowed to create a user
        model.add_user_to_role(userA, model.Role.ADMIN, model.System())
        model.repo.commit_and_remove()
        userA = model.User.by_name(u'user_a__')

        # start to register user B
        offset = url_for(controller='user', action='register')
        res = self.app.get(offset)
        fvA = res.forms['user-edit']
        fvA['name'] = 'user_b_'
        fvA['fullname'] = 'User B'
        fvA['email'] = '*****@*****.**'
        fvA['password1'] = password
        fvA['password2'] = password

        # login user A
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fvB = res.forms['login']
        fvB['login'] = '******'
        fvB['password'] = str(password)
        res = fvB.submit()
        while res.status == 302:
            res = res.follow()
        assert_equal(res.status, 200)

        # finish registration of user B
        res = fvA.submit('save')
        assert_equal(res.status, 200)
        assert 'user_a__</a> is currently logged in' in res.body, res.body
        assert 'User "user_b_" is now registered but you are still logged in as "user_a__" from before'.replace('"', '&#34;') in res.body, res.body
        assert 'logout' in res.body, res.body

        # logout and login as user B
        res = self.app.get('/user/_logout')
        res2 = res.follow()
        while res2.status == 302:
            res2 = res2.follow()
        assert 'You have logged out successfully.' in res2, res2
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fv = res.forms['login']
        fv['login'] = '******'
        fv['password'] = str(password)
        res = fv.submit()
        while res.status == 302:
            res = res.follow()
        assert_equal(res.status, 200)
        assert 'User B is now logged in' in res.body, res.body
Пример #25
0
 def test_perform_reset_user_password_link_key_incorrect(self):
     CreateTestData.create_user(name='jack', password='******')
     # Make up a key - i.e. trying to hack this
     user = model.User.by_name(u'jack')
     offset = url_for(controller='user',
                      action='perform_reset',
                      id=user.id,
                      key='randomness') # i.e. incorrect
     res = self.app.get(offset, status=403) # error
Пример #26
0
 def setup_class(cls):
     config = appconfig('config:test.ini', relative_to=conf_dir)
     config.local_conf['ckan.storage.directory'] = '/tmp/'
     wsgiapp = make_app(config.global_conf, **config.local_conf)
     cls.app = paste.fixture.TestApp(wsgiapp)
     CreateTestData.create()
     model.Session.remove()
     user = model.User.by_name('tester')
     cls.extra_environ = {'Authorization': str(user.apikey)}
Пример #27
0
 def setup_class(self):
     super(TestSpatialApi,self).setup_class()
     setup_test_search_index()
     CreateTestData.create_test_user()
     self.package_fixture_data = {
         'name' : u'test-spatial-dataset-search-point',
         'title': 'Some Title',
         'extras': [{'key':'spatial','value':self.geojson_examples['point']}]
     }
     self.base_url = self.offset('/search/dataset/geo')
 def setup_class(cls):
     config = appconfig('config:test.ini', relative_to=conf_dir)
     config.local_conf['ckan.plugins'] = 'wordpresser'
     config.local_conf['wordpresser.proxy_host'] \
                           = 'http://localhost:6969/'
     wsgiapp = make_app(config.global_conf, **config.local_conf)
     env = {'HTTP_ACCEPT': 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'}
     cls.app = paste.fixture.TestApp(wsgiapp, extra_environ=env)
     CreateTestData.create()
     runmockserver()
    def setup_class(cls):
        
        # Note Testing package-scoped translation requires some existing datasets

        CreateTestData.create_user('tester', about='A tester', password='******')
        for pkg_name, pkg in cls.packages.items():
            ctx = make_api_context('tester')
            pkg_result = create_action(ctx, pkg)
            pkg.update({'id': pkg_result['id']})
        
        return
Пример #30
0
    def test_login(self):
        # create test user
        username = u'testlogin'
        password = u'letmein'
        CreateTestData.create_user(name=username,
                                   password=password)
        user = model.User.by_name(username)

        # do the login
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fv = res.forms['login']
        fv['login'] = str(username)
        fv['password'] = str(password)
        fv['remember'] = False
        res = fv.submit()

        # check cookies set
        cookies = self._get_cookie_headers(res)
        assert cookies
        for cookie in cookies:
            assert not 'max-age' in cookie.lower(), cookie

        # first get redirected to user/logged_in
        assert_equal(res.status, 302)
        assert res.header('Location').startswith('http://localhost/user/logged_in') or \
               res.header('Location').startswith('/user/logged_in')

        # then get redirected to user page
        res = res.follow()
        assert_equal(res.status, 302)
        assert res.header('Location').startswith('http://localhost/user/testlogin') or \
               res.header('Location').startswith('/user/testlogin')
        res = res.follow()
        assert_equal(res.status, 200)
        assert 'testlogin is now logged in' in res.body
        assert 'checkpoint:is-myself' in res.body

        # check user object created
        user = model.User.by_name(username)
        assert user
        assert_equal(user.name, username)
        assert len(user.apikey) == 36

        # check cookie created
        cookie = res.request.environ['HTTP_COOKIE']
        assert 'auth_tkt=' in cookie, cookie
        assert 'testlogin!userid_type:unicode' in cookie, cookie

        # navigate to another page and check username still displayed
        print res.body
        res = res.click('Search')
        print res
        assert 'testlogin' in res.body, res.body
Пример #31
0
    def test_login(self):
        # create test user
        username = u'testlogin'
        password = u'letmein'
        CreateTestData.create_user(name=username, password=password)
        user = model.User.by_name(username)

        # do the login
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fv = res.forms['login']
        fv['login'] = str(username)
        fv['password'] = str(password)
        fv['remember'] = False
        res = fv.submit()

        # check cookies set
        cookies = self._get_cookie_headers(res)
        assert cookies
        for cookie in cookies:
            assert not 'max-age' in cookie.lower(), cookie

        # first get redirected to user/logged_in
        assert_equal(res.status, 302)
        assert res.header('Location').startswith('http://localhost/user/logged_in') or \
               res.header('Location').startswith('/user/logged_in')

        # then get redirected to user's dashboard
        res = res.follow()
        assert_equal(res.status, 302)
        assert res.header('Location').startswith('http://localhost/dashboard') or \
               res.header('Location').startswith('/dashboard')
        res = res.follow()
        assert_equal(res.status, 200)
        assert 'testlogin is now logged in' in res.body
        assert 'checkpoint:my-dashboard' in res.body

        # check user object created
        user = model.User.by_name(username)
        assert user
        assert_equal(user.name, username)
        assert len(user.apikey) == 36

        # check cookie created
        cookie = res.request.environ['HTTP_COOKIE']
        assert 'auth_tkt=' in cookie, cookie
        assert 'testlogin!userid_type:unicode' in cookie, cookie

        # navigate to another page and check username still displayed
        res = res.click('Search')
        assert 'testlogin' in res.body, res.body
Пример #32
0
    def setup_class(cls):
        cls._original_config = config.copy()
        for key in config.keys():
            if key.startswith('ofs'):
                del config[key]
        config['ofs.impl'] = 'pairtree'
        config['ckan.storage.bucket'] = 'ckantest'
        config['ofs.storage_dir'] = '/tmp/ckan-test-ckanext-storage'

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

        CreateTestData.create_test_user()
Пример #33
0
    def test_login(self):
        # create test user
        username = u'testlogin'
        password = u'letmein'
        CreateTestData.create_user(name=username, password=password)
        user = model.User.by_name(username)

        # do the login
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fv = res.forms['login']
        fv['login'] = str(username)
        fv['password'] = str(password)
        res = fv.submit()

        # check cookies set
        cookies = self._get_cookie_headers(res)
        assert cookies

        # first get redirected to user/logged_in
        assert_equal(res.status, 302)
        assert res.header('Location').startswith(
            'http://localhost/user/logged_in')

        # then get redirected to user page
        res = res.follow()
        assert_equal(res.status, 302)
        assert_equal(res.header('Location'), 'http://localhost/user/testlogin')
        res = res.follow()
        assert_equal(res.status, 200)
        assert 'testlogin is now logged in' in res.body
        assert 'My Account' in res.body

        # check user object created
        user = model.User.by_name(username)
        assert user
        assert_equal(user.name, username)
        assert len(user.apikey) == 36

        # check cookie created
        cookie = res.request.environ['HTTP_COOKIE']
        # I think some versions of webob do not produce quotes, hence the 'or'
        assert 'ckan_display_name="testlogin"' in cookie or \
               'ckan_display_name=testlogin' in cookie, cookie
        assert 'auth_tkt=' in cookie, cookie
        assert 'testlogin!userid_type:unicode' in cookie, cookie

        # navigate to another page and check username still displayed
        res = res.click('Search')
        assert 'testlogin' in res.body, res.body
Пример #34
0
    def setup_class(cls):
        config = appconfig('config:test.ini', relative_to=conf_dir)
        for key in config.local_conf.keys():
            if key.startswith('ofs'):
                del config.local_conf[key]
        config.local_conf['ofs.impl'] = 'pairtree'
        config.local_conf['ckan.storage.bucket'] = 'ckantest'
        config.local_conf['ofs.storage_dir'] = '/tmp/ckan-test-ckanext-storage'

        create_pairtree_marker(config.local_conf['ofs.storage_dir'])
        wsgiapp = make_app(config.global_conf, **config.local_conf)
        cls.app = paste.fixture.TestApp(wsgiapp)

        CreateTestData.create_test_user()
Пример #35
0
 def setup_class(cls):
     # setup test data including testsysadmin user
     CreateTestData.create()
     # Creating a couple of authorization groups, which are enough to break
     # some things just by their existence
     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()
     #they are especially dangerous if they have a role on the System
     ag = model.AuthorizationGroup.by_name(u'anauthzgroup')
     model.add_authorization_group_to_role(ag, u'editor', model.System())
     model.Session.commit()
Пример #36
0
 def setup_class(cls):
     config = appconfig('config:test.ini', relative_to=conf_dir)
     for key in config.local_conf.keys():
         if key.startswith('ofs'):
             del config.local_conf[key]
     config.local_conf['ckan.storage.bucket'] = 'ckantest'
     config.local_conf['ofs.impl'] = 'pairtree'
     config.local_conf['ofs.storage_dir'] = '/tmp/ckan-test-ckanext-storage'
     create_pairtree_marker( config.local_conf['ofs.storage_dir'] )
     wsgiapp = make_app(config.global_conf, **config.local_conf)
     cls.app = paste.fixture.TestApp(wsgiapp)
     CreateTestData.create()
     model.Session.remove()
     user = model.User.by_name('tester')
     cls.extra_environ = {'Authorization': str(user.apikey)}
Пример #37
0
    def setup_class(self):
        super(TestDeathsOverwrite, self).setup_class()
        try:
            self.orig_pkg_dict = {
                "name": u"weekly_provisional_figures_on_deaths_registered_in_england_and_wales",
                "title": "Weekly provisional figures on deaths registered in England and Wales",
                "version": None, "url": None, "author": "Office for National Statistics", "author_email": None, "maintainer": None, "maintainer_email": None,
                "notes": "Weekly death figures provide provisional counts of the number of deaths registered in England and Wales in the latest four weeks for which data are available up to the end of 2009. From week one 2010 the latest eight weeks for which data are available will be published.\n\nSource agency: Office for National Statistics\n\nDesignation: National Statistics\n\nLanguage: English\n\nAlternative title: Weekly deaths",
                "license_id": "ukcrown-withrights",
                "tags": ["death", "deaths", "life-events", "life-in-the-community", "mortality-rates", "population", "weekly-deaths"],
                "groups": ['office-for-national-statistics'],
                "extras": {
                    "geographic_coverage": "101000: England, Wales",
                    "geographic_granularity": "Country",
                    "external_reference": "ONSHUB",
                    "temporal_coverage-from": "",
                    "temporal_granularity": "",
                    "date_updated": "",
                    "series": "Weekly provisional figures on deaths registered in England and Wales",
                    "precision": "",
                    "geographic_granularity": "",
                    "temporal_coverage_to": "",
                    "temporal_coverage_from": "",
                    "taxonomy_url": "",
                    "import_source": "ONS-ons_data_60_days_to_2010-09-22",
                    "date_released": "2010-08-03",
                    "temporal_coverage-to": "",
                    "update_frequency": "",
                    "national_statistic": "yes",
                    "categories": "Population"},
                "resources": [
                    {"url": "http://www.statistics.gov.uk/StatBase/Prep/9684.asp", "format": "", "description": "17/07/2009", "hash": "", "extras": {"hub-id": "77-27942"} }],
                }

            CreateTestData.create_arbitrary([self.orig_pkg_dict])

            # same data is imported, but should find record and add department
            importer_ = importer.OnsImporter(sample_filepath(7), self.testclient)
            self.pkg_dict = [pkg_dict for pkg_dict in importer_.pkg_dict()][0]
            loader = OnsLoader(self.testclient)
            print self.pkg_dict
            self.res = loader.load_package(self.pkg_dict)
            self.name = self.orig_pkg_dict['name']
        except:
            # ensure that mock_drupal is destroyed
            MockDrupalCase.teardown_class()
            model.repo.rebuild_db()
            raise
Пример #38
0
    def setup_class(cls):
        InitDB("initdb").run([])  # set up database tables

        config = appconfig('config:test.ini', relative_to=conf_dir)
        config.local_conf['ckan.plugins'] = 'googleanalytics'
        config.local_conf['googleanalytics.id'] = 'UA-borf-1'
        config.local_conf['googleanalytics.show_downloads'] = 'true'
        cls.config = config.local_conf
        wsgiapp = make_app(config.global_conf, **config.local_conf)
        env = {
            'HTTP_ACCEPT': ('text/html;q=0.9,text/plain;'
                            'q=0.8,image/png,*/*;q=0.5')
        }
        cls.app = paste.fixture.TestApp(wsgiapp, extra_environ=env)
        CreateTestData.create()
        runmockserver()
Пример #39
0
class TestDatastoreController(TestController):
    @classmethod
    def setup_class(cls):

        # Check if Elastic Search is available, otherwise skip tests
        try:
            res = requests.get('http://%s/_status' % ELASTIC_SEARCH_HOST,
                               timeout=2)
            if res.status_code == 200:
                try:
                    content = json.loads(res.content)
                    if not 'ok' in content or not '_shards' in content:
                        raise ValueError
                except ValueError:
                    raise SkipTest(
                        'This does not look like Elastic Search, skipping...')
            else:
                raise SkipTest('Could not reach Elastic Search, skipping...')

        except (requests.exceptions.RequestException, socket.timeout), e:
            raise SkipTest('Could not reach Elastic Search, skipping... (%r)' %
                           e)

        # Push dummy data to create the test index
        requests.put('http://%s/ckan-%s/' %
                     (ELASTIC_SEARCH_HOST, config.get('ckan.site_id')))

        model.repo.init_db()
        CreateTestData.create()
Пример #40
0
 def setup_class(cls):
     """
     Remove any initial sessions.
     """
     Session.remove()
     cls.original_config = config.copy()
     plugins = set(config['ckan.plugins'].strip().split())
     plugins.add('sitemap')
     config['ckan.plugins'] = ' '.join(plugins)
     cls.app = _get_test_app()
     CreateTestData.create()
     url = url_for(
         controller="ckanext.sitemap.controller:SitemapController",
         action='view')
     cls.cont = cls.app.get(url)
     cls.content_file = StringIO(cls.cont.body)
    def setup_class(cls):

        CreateTestData.create_user('tester',
                                   about='A tester',
                                   password='******')

        CreateTestData.create_groups([{
            'name': 'acme',
            'title': u'Acme',
            'description': u'A fictional organization',
            'type': 'organization',
            'is_organization': True,
        }],
                                     admin_user_name='tester')

        cls.find_translatable_fields()
        cls.default_lang = pylons.config['ckan.locale_default']
Пример #42
0
    def setup_class(self):
        PylonsTestCase.setup_class()
        SmtpServerHarness.setup_class()
        CreateTestData.create()

        # make 3 changes, authored by annafan
        for i in range(3):
            rev = model.repo.new_revision()
            pkg = model.Package.by_name(u'annakarenina')
            pkg.notes = u'Changed notes %i' % i
            rev.author = u'annafan'
            model.repo.commit_and_remove()

        CreateTestData.create_user('unfinisher', about='<a href="http://unfinished.tag')
        CreateTestData.create_user('uncloser', about='<a href="http://unclosed.tag">')
        CreateTestData.create_user('spammer', about=u'<a href="http://mysite">mysite</a> <a href=\u201dhttp://test2\u201d>test2</a>')
        CreateTestData.create_user('spammer2', about=u'<a href="http://spamsite1.com\u201d>spamsite1</a>\r\n<a href="http://www.spamsite2.com\u201d>spamsite2</a>\r\n')
Пример #43
0
    def setup_class(self):
        super(TestOnsLoadClashSource, self).setup_class()

        self.clash_name = u'cereals_and_oilseeds_production_harvest'
        CreateTestData.create_arbitrary([{
            'name': self.clash_name,
            'title': 'Test clash',
            'extras': {
                'published_by':
                'Department for Environment, Food and Rural Affairs',
                'import_source': 'DECC-Jan-09',
            },
        }])
        importer_ = importer.OnsImporter(sample_filepath(''))
        pkg_dicts = [pkg_dict for pkg_dict in importer_.pkg_dict()]
        loader = OnsLoader(self.testclient)
        self.res = loader.load_packages(pkg_dicts)
        assert self.res['num_errors'] == 0, self.res
Пример #44
0
    def setup_class(cls):
        InitDB("initdb").run([])  # set up database tables

        config = appconfig("config:test.ini", relative_to=conf_dir)
        config.local_conf["ckan.plugins"] = "googleanalytics"
        config.local_conf["googleanalytics.username"] = "******"
        config.local_conf["googleanalytics.password"] = "******"
        config.local_conf["googleanalytics.id"] = "UA-borf-1"
        config.local_conf["googleanalytics.show_downloads"] = "true"
        cls.config = config.local_conf
        wsgiapp = make_app(config.global_conf, **config.local_conf)
        env = {
            "HTTP_ACCEPT": ("text/html;q=0.9,text/plain;"
                            "q=0.8,image/png,*/*;q=0.5")
        }
        cls.app = paste.fixture.TestApp(wsgiapp, extra_environ=env)
        CreateTestData.create()
        runmockserver()
Пример #45
0
    def setup_class(self):
        setup_test_search_index()
        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.setup_default_user_roles(pkg, [admin])
        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()
 def setup_class(cls):
     setup_test_search_index()
     init_data = [
         {
             'name': u'test1-penguin-canary',
             'title': u'penguin',
             'tags': u'canary goose squirrel wombat wombat'.split()
         },
         {
             'name': u'test2-squirrel-squirrel-canary-goose',
             'title': u'squirrel goose',
             'tags': u'penguin wombat'.split()
         },
     ]
     CreateTestData.create_arbitrary(init_data)
     cls.pkg_names = [
         u'test1-penguin-canary', u'test2-squirrel-squirrel-canary-goose'
     ]
Пример #47
0
    def setup_class(cls):

        logging.basicConfig(level=logging.INFO)

        CreateTestData.create_user('tester',
                                   about='A tester',
                                   password='******')
        CreateTestData.create_groups(
            [{
                'name': cls.owner_org['name'],
                'title': cls.owner_org['title'],
                'description': cls.owner_org['description'],
                'type': 'organization',
                'is_organization': True,
            }],
            admin_user_name='tester')

        cls.extra_environ = {'REMOTE_USER': '******'}

        return
Пример #48
0
    def test_user_delete_redirects_to_user_index(self):
        user = CreateTestData.create_user('a_user')
        url = url_for(controller='user', action='delete', id=user.id)
        extra_environ = {'REMOTE_USER': '******'}

        redirect_url = url_for(controller='user', action='index',
                qualified=True)
        res = self.app.get(url, status=302, extra_environ=extra_environ)

        assert user.is_deleted(), user
        assert res.header('Location').startswith(redirect_url), res.header('Location')
Пример #49
0
 def setup_class(cls):
     config = appconfig('config:test.ini', relative_to=conf_dir)
     config.local_conf['ckan.storage.bucket'] = 'ckantest'
     config.local_conf['ofs.impl'] = 'google'
     if 'ofs.gs_secret_access_key' not in config.local_conf:
         raise Exception('You will need to configure access to google storage to run this test')
     # You will need these configured in your
     # config.local_conf['ofs.gs_access_key_id'] = 'GOOGCABCDASDASD'
     # config.local_conf['ofs.gs_secret_access_key'] = '134zsdfjkw4234addad'
     # need to ensure not configured for local as breaks google setup
     # (and cannot delete all ofs keys as need the gs access codes)
     if 'ofs.storage_dir' in config.local_conf:
         del config.local_conf['ofs.storage_dir']
     wsgiapp = make_app(config.global_conf, **config.local_conf)
     cls.app = paste.fixture.TestApp(wsgiapp)
     # setup test data including testsysadmin user
     CreateTestData.create()
     model.Session.remove()
     user = model.User.by_name('tester')
     cls.extra_environ = {'Authorization': str(user.apikey)}
    def setup_class(cls):
        setup_test_search_index()
        # Force a garbage collection to trigger issue #695
        import gc
        gc.collect()

        CreateTestData.create()

        cls.new_pkg_dict = {
            'name': 'council-owned-litter-bins',
            'notes': 'Location of Council owned litter bins within Borough.',
            'resources': [{'description': 'Resource locator',
                           'format': 'Unverified',
                           'url': 'http://www.barrowbc.gov.uk'}],
            'tags': ['Utility and governmental services'],
            'title': 'Council Owned Litter Bins',
            'extras': {
                'INSPIRE': 'True',
                'bbox-east-long': '-3.12442',
                'bbox-north-lat': '54.218407',
                'bbox-south-lat': '54.039634',
                'bbox-west-long': '-3.32485',
                'constraint': 'conditions unknown; (e) intellectual property rights;',
                'dataset-reference-date': json.dumps(
                                          [{'type': 'creation',
                                            'value': '2008-10-10'},
                                           {'type': 'revision',
                                            'value': '2009-10-08'}]),
                'guid': '00a743bf-cca4-4c19-a8e5-e64f7edbcadd',
                'metadata-date': '2009-10-16',
                'metadata-language': 'eng',
                'published_by': 0,
                'resource-type': 'dataset',
                'spatial-reference-system': 'test-spatial',
                'temporal_coverage-from': '1977-03-10T11:45:30',
                'temporal_coverage-to': '2005-01-15T09:10:00'
            }
        }
Пример #51
0
 def setup_class(cls):     
     
     script_path = os.path.join(os.path.dirname(os.path.abspath( __file__ )), 'scripts', 'create_tables.sql')
     script = open(script_path, 'r').read()
     cls._execute_sql(script)
     
     #CreateTestData.create_test_user()
     
     '''
     schema = default_create_package_schema()
     context = {
             'model': model,
             'session': Session,
             'user': '******',
             'schema': schema,
             'api_version': 2
         }
     '''
     package_fixture_data =  {
             'name': 'test-ngds',
             'title': 'test title',
             'resources': [
                     {
                         'name': 'test-resource',
                         'url': 'http://azgs.az.gov',
                         'format': 'plain text',
                         'description': 'This is a test description',
                         'hash': 'abc123',
                         'extras': {'size_extra': '123'}
                     }
                 ]
         }
     
     '''
     package_dict = package_create(context, package_fixture_data)
     cls.package_id = context.get('id') 
     '''
     CreateTestData.create_arbitrary(package_fixture_data)
Пример #52
0
    def setup_class(self):
        super(TestActionPackageSearch, self).setup_class()
        setup_test_search_index()
        self.package_fixture_data_1 = {
            'name': u'test-spatial-dataset-search-point-1',
            'title': 'Some Title 1',
            'extras': [{
                'key': 'spatial',
                'value': self.geojson_examples['point']
            }]
        }
        self.package_fixture_data_2 = {
            'name':
            u'test-spatial-dataset-search-point-2',
            'title':
            'Some Title 2',
            'extras': [{
                'key': 'spatial',
                'value': self.geojson_examples['point_2']
            }]
        }

        CreateTestData.create()
Пример #53
0
    def test_request_reset_user_password_using_search(self):
        offset = url_for(controller='user', action='request_reset')
        CreateTestData.create_user(name='larry1', fullname='kittens')
        CreateTestData.create_user(name='larry2', fullname='kittens')
        res = self.app.get(offset)
        fv = res.forms['user-password-reset']
        fv['user'] = '******'
        res = fv.submit()
        assert '&#34;kittens&#34; matched several users' in res, res
        assert 'larry1' not in res, res
        assert 'larry2' not in res, res

        res = self.app.get(offset)
        fv = res.forms['user-password-reset']
        fv['user'] = ''
        res = fv.submit()
        assert 'No such user:'******'user-password-reset']
        fv['user'] = '******'
        res = fv.submit()
        assert 'No such user:' in res, res
Пример #54
0
    def setup_class(cls):
        smtp_server = config.get('smtp.test_server')
        if smtp_server:
            host, port = smtp_server.split(':')
            port = int(port) + int(str(hashlib.md5(cls.__name__).hexdigest())[0], 16)
            config['smtp.test_server'] = '%s:%s' % (host, port)

        PylonsTestCase.setup_class()
        SmtpServerHarness.setup_class()
        CreateTestData.create()

        # make 3 changes, authored by annafan
        for i in range(3):
            rev = model.repo.new_revision()
            pkg = model.Package.by_name(u'annakarenina')
            pkg.notes = u'Changed notes %i' % i
            rev.author = u'annafan'
            model.repo.commit_and_remove()

        CreateTestData.create_user('unfinisher', about='<a href="http://unfinished.tag')
        CreateTestData.create_user('uncloser', about='<a href="http://unclosed.tag">')
        CreateTestData.create_user('spammer', about=u'<a href="http://mysite">mysite</a> <a href=\u201dhttp://test2\u201d>test2</a>')
        CreateTestData.create_user('spammer2', about=u'<a href="http://spamsite1.com\u201d>spamsite1</a>\r\n<a href="http://www.spamsite2.com\u201d>spamsite2</a>\r\n')
 def setup_class(cls):
     setup_test_search_index()
     init_data = [
         {
             'name': 'eng',
             'extras': {
                 'geographic_coverage': '100000: England'
             },
         },
         {
             'name': 'eng_ni',
             'extras': {
                 'geographic_coverage': '100100: England, Northern Ireland'
             },
         },
         {
             'name': 'uk',
             'extras': {
                 'geographic_coverage':
                 '111100: United Kingdom (England, Scotland, Wales, Northern Ireland'
             },
         },
         {
             'name': 'gb',
             'extras': {
                 'geographic_coverage':
                 '111000: Great Britain (England, Scotland, Wales)'
             },
         },
         {
             'name': 'none',
             'extras': {
                 'geographic_coverage': '000000:'
             },
         },
     ]
     CreateTestData.create_arbitrary(init_data)
Пример #56
0
    def test_login_remembered(self):
        # create test user
        username = u'testlogin2'
        password = u'letmein'
        CreateTestData.create_user(name=username, password=password)
        user = model.User.by_name(username)

        # do the login
        offset = url_for(controller='user', action='login')
        res = self.app.get(offset)
        fv = res.forms['login']
        fv['login'] = str(username)
        fv['password'] = str(password)
        fv['remember'] = True
        res = fv.submit()

        # check cookies set
        cookies = self._get_cookie_headers(res)
        assert cookies
        # check cookie is remembered via Max-Age and Expires
        # (both needed for cross-browser compatibility)
        for cookie in cookies:
            assert 'Max-Age=63072000;' in cookie, cookie
            assert 'Expires=' in cookie, cookie
Пример #57
0
    def setup_class(self):
        super(TestOnsLoadClashSource, self).setup_class()

        try:
            self.clash_name = u'cereals_and_oilseeds_production_harvest'
            CreateTestData.create_arbitrary([
                {'name':self.clash_name,
                 'title':'Test clash',
                 'groups':['department-for-environment-food-and-rural-affairs'],
                 'extras':{
                     'import_source':'DECC-Jan-09',
                     },
                 }
                ])
            importer_ = importer.OnsImporter(sample_filepath(''), self.testclient)
            pkg_dicts = [pkg_dict for pkg_dict in importer_.pkg_dict()]
            loader = OnsLoader(self.testclient)
            self.res = loader.load_packages(pkg_dicts)
            assert self.res['num_errors'] == 0, self.res
        except:
            # ensure that mock_drupal is destroyed
            MockDrupalCase.teardown_class()
            model.repo.rebuild_db()
            raise
    def test_map_shown(self):
        CreateTestData.create()

        extra_environ = {'REMOTE_USER': '******'}
        name = 'annakarenina'

        offset = url_for(controller='package', action='edit', id=name)
        res = self.app.get(offset, extra_environ=extra_environ)
        assert 'Edit - Datasets' in res
        fv = res.forms['dataset-edit']
        prefix = ''
        fv[prefix + 'extras__1__key'] = u'spatial'
        fv[prefix + 'extras__1__value'] = self.geojson_examples['point']

        res = fv.submit('save', extra_environ=extra_environ)
        assert not 'Error' in res, res

        # Load the dataset page and check if the libraries have been loaded
        offset = url_for(controller='package', action='read', id=name)
        res = self.app.get(offset)

        assert '<div class="dataset-map subsection">' in res, res
        assert '<script type="text/javascript" src="/ckanext/spatial/js/dataset_map.js"></script>' in res
        assert self.geojson_examples['point'] in res
Пример #59
0
    def test_perform_reset_doesnt_activate_deleted_user(self):
        password = '******'
        params = {'password1': password, 'password2': password}
        user = CreateTestData.create_user(name='deleted_user',
                                          email='*****@*****.**')
        user.delete()
        create_reset_key(user)
        assert user.is_deleted(), user.state

        offset = url_for(controller='user',
                         action='perform_reset',
                         id=user.id,
                         key=user.reset_key)
        res = self.app.post(offset, params=params, status=302)

        user = model.User.get(user.id)
        assert user.is_deleted(), user
Пример #60
0
 def teardown_class(cls):
     """
     Tear down, remove the session.
     """
     CreateTestData.delete()
     Session.remove()