示例#1
0
文件: test_follow.py 项目: 1sha1/ckan
    def test_dataset_follow_logged_in(self):
        offset = url_for(controller='package', action='followers',
                id='warandpeace')
        extra_environ = {'Authorization': str(self.testsysadmin.apikey)}
        result = self.app.get(offset, extra_environ=extra_environ)
        assert 'id="dataset_follow_button"' in result
        assert 'Followers (0)' in result
        assert 'id="dataset_follow_button"' in result
        assert '<li class="user">' not in result

        offset = url_for(controller='package', action='followers',
                id='annakarenina')
        extra_environ = {'Authorization': str(self.testsysadmin.apikey)}
        result = self.app.get(offset, extra_environ=extra_environ)
        assert 'href="/dataset/followers/annakarenina"' in result
        assert 'Followers (3)' in result
        assert 'id="dataset_follow_button"' in result
        assert str(result).count('<li class="user">') == 3
        assert self.joeadmin.display_name in result
        assert self.annafan.display_name in result
        assert self.russianfan.display_name in result

        # joeadmin is following annakarenina so he should see an Unfollow
        # button.
        offset = url_for(controller='package', action='followers',
                id='annakarenina')
        extra_environ = {'Authorization': str(self.testsysadmin.apikey)}
        result = self.app.get(offset, extra_environ=extra_environ)
        assert 'Unfollow' in result
示例#2
0
    def update_app(self, client_id):
        """
        Update an application
        """
        user = pylons.request.environ['fts3.User.Credentials']
        app = Session.query(OAuth2Application).get(client_id)
        if not app:
            raise HTTPNotFound('Application not found')
        if app.owner != user.user_dn:
            raise HTTPForbidden()
        if pylons.request.headers['Content-Type'].startswith('application/json'):
            fields = json.loads(pylons.request.body)
        else:
            fields = pylons.request.POST

        try:
            if 'delete' not in fields:
                app.description = fields.get('description', '')
                app.website = fields.get('website', '')
                app.redirect_to = fields.get('redirect_to', '')
                Session.merge(app)
                Session.commit()
                redirect(url_for(controller='oauth2', action='get_app'), code=HTTPSeeOther.code)
            else:
                Session.delete(app)
                Session.query(OAuth2Token).filter(OAuth2Token.client_id == client_id).delete()
                Session.query(OAuth2Code).filter(OAuth2Code.client_id == client_id).delete()
                Session.commit()
                redirect(url_for(controller='oauth2', action='get_my_apps'), code=HTTPSeeOther.code)
        except:
            Session.rollback()
            raise
示例#3
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
示例#4
0
    def test_group_index(self):
        app = self._get_test_app()

        for i in xrange(1, 26):
            _i = "0" + str(i) if i < 10 else i
            factories.Group(name="test-group-{0}".format(_i), title="Test Group {0}".format(_i))

        url = url_for(controller="group", action="index")
        response = app.get(url)

        for i in xrange(1, 22):
            _i = "0" + str(i) if i < 10 else i
            assert_in("Test Group {0}".format(_i), response)

        assert "Test Group 22" not in response

        url = url_for(controller="group", action="index", page=1)
        response = app.get(url)

        for i in xrange(1, 22):
            _i = "0" + str(i) if i < 10 else i
            assert_in("Test Group {0}".format(_i), response)

        assert "Test Group 22" not in response

        url = url_for(controller="group", action="index", page=2)
        response = app.get(url)

        for i in xrange(22, 26):
            assert_in("Test Group {0}".format(i), response)

        assert "Test Group 21" not in response
示例#5
0
    def view(self):
        c.name = config['app_conf']['site_name']
        c.title = 'View'
        c.messages = []
        c.session = Session()

        file = request.params.get('file', None)
        if file is None:
            return redirect_to(url_for(controller="moderation"))

        #Get the image/FILE
        file = fetch_file(file)

        if 'error' in file:
            session['messages'] = ["Invalid file"]
            session.save()
            return redirect_to(url_for(controller="moderation"))

        if 'scr' in file:
            c.scr = file['scr']
        elif 'href' in file:
            c.href = file['href']
        c.filename = file['filename']
        c.new_name = file['new_name']
        c.description = file['description']
        c.destination = file['destination']
        c.author = file['author']
        c.status = file['status']


        return render('/derived/moderation/view.html')
示例#6
0
    def hogetest_create(self):
        """Tests that valid data is saved to the database, that the response
        redirects to the view() action that a flash message is set in the session"""
        response = self.app.post(
            url = url_for(controller = 'phone', action = 'create'),
            params = {'mobile_number': u'Created',
                      'name': u'Created',
                      'address': u'Created',
                      'home_number': u'Created',
                      'dob': u'2000/01/01'},
            )            

        mc = memcache.Client([config['app_conf']['memcachedb.servers']], debug = 0)
        ser = mc.get('2')

        u = Unpickler()
        c = u.restore(ser)

        assert c.__class__.__name__ == 'Phone'
        assert c.mobile_number == u'Created'
        assert c.name == u'Created'
        assert c.address == u'Created'
        assert c.home_number == u'Created'
        assert c.dob == u'2000/01/01'

        assert urlparse(response.response.location).path == url_for(
            controller = 'phone', action = 'view', id = '2')
        assert response.status_int == 302
示例#7
0
    def test_edit_user_logged_in_username_change_by_id(self):
        user_pass = "******"
        user = factories.User(password=user_pass)
        app = self._get_test_app()

        # Have to do an actual login as this test relys on repoze cookie handling.
        # get the form
        response = app.get("/user/login")
        # ...it's the second one
        login_form = response.forms[1]
        # fill it in
        login_form["login"] = user["name"]
        login_form["password"] = user_pass
        # submit it
        login_form.submit()

        # Now the cookie is set, run the test
        response = app.get(url=url_for(controller="user", action="edit", id=user["id"]))
        # existing values in the form
        form = response.forms["user-edit-form"]

        # new values
        form["name"] = "new-name"
        response = submit_and_follow(app, form, name="save")
        response = helpers.webtest_maybe_follow(response)

        expected_url = url_for(controller="user", action="read", id="new-name")
        assert response.request.path == expected_url
示例#8
0
def partners_img(mossmatch):
    if mossmatch is None or not isinstance(mossmatch,MossMatch):
        abort(404)
    def is_partner_of(student, partner):
        if student.row_type != "studentsubmission" or partner.row_type != "studentsubmission":
            return False
        if partner.student in student.partners:
            return True
        return False
    left_url = url_for("/crystal_project/16x16/actions/1leftarrow.png")
    right_url = url_for("/crystal_project/16x16/actions/1rightarrow.png")
    no_url = url_for("/crystal_project/16x16/actions/cancel.png")
    title = "Partners"
    if is_partner_of(mossmatch.submission1, mossmatch.submission2) and is_partner_of(mossmatch.submission2, mossmatch.submission1):
        str = "<img src='"+left_url+"'/><img src='"+right_url+"'/>"
        #return literal(str)
        text = mossmatch.submission1.student.netid + " and "+mossmatch.submission2.student.netid+" declared each other as partners"
        return cluetip_img(str,title,text)
    elif is_partner_of(mossmatch.submission1, mossmatch.submission2):
        str = "<img src='"+right_url+"'/>"
        #return literal(str)
        text = mossmatch.submission1.student.netid + " declared "+mossmatch.submission2.student.netid+" as a partner, but not in reverse"
        return cluetip_img(str,title,text)
    elif is_partner_of(mossmatch.submission2, mossmatch.submission1):
        str = "<img src='"+left_url+"'/>"
        #return literal(str)
        text = mossmatch.submission2.student.netid + " declared "+mossmatch.submission1.student.netid+" as a partner, but not in reverse"
        return cluetip_img(str,title,text)
    else:
        str = "<img src='"+no_url+"'/>"
        #return literal(str)
        text = "Neither "+mossmatch.submission1.student.netid+" nor "+mossmatch.submission2.student.netid+" declared each other as partners"
        return cluetip_img(str, title, text)
示例#9
0
    def commit(self):
        s = Session()
        session['messages'] = []
        paths = []

        message = request.params.get("message", "Web commit")
        db_files = s.query(Upload).filter(Upload.status == u"Moderated").all()
        for db_file in db_files:

            destination = get_path(None, db_file.destination)
            if destination == "Invalid path":
                session['messages'] += ["Invalid destination for the file %s" % db_file.name]
                session.save()
                return redirect_to(url_for(controller="moderation"))

            currentpath = os.path.join(get_path("moderation"), db_file.new_name)
            #os.sep is to fix a bug
            shutil.move(currentpath, destination+os.sep)

            oldpath = os.path.join(destination, db_file.new_name)
            path = os.path.join(destination, db_file.name)
            os.rename(oldpath, path)

            #TODO error handling
            path = os.path.join(db_file.destination, db_file.name)
            add(path, Session())
            paths += [path]
            session['messages'] += ["%s is commit" % db_file.name]
            session.save()
            s.delete(db_file)
            s.commit()

        commit(paths, message, session['user'], Session())

        return redirect_to(url_for(controller="moderation"))
示例#10
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
示例#11
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
示例#12
0
    def test_user_follow_logged_in(self):
        offset = url_for(controller='user', action='followers',
                id='joeadmin')
        extra_environ = {'Authorization': str(self.tester.apikey)}
        result = self.app.get(offset, extra_environ=extra_environ)
        assert 'href="/user/followers/joeadmin"' in result
        assert 'Followers (0)' in result
        assert '<li class="user">' not in result
        assert 'id="user_follow_button"' in result

        offset = url_for(controller='user', action='followers',
                id='annafan')
        extra_environ = {'Authorization': str(self.tester.apikey)}
        result = self.app.get(offset, extra_environ=extra_environ)
        assert 'href="/user/followers/annafan"' in result
        assert 'Followers (2)' in result
        assert 'id="user_follow_button"' in result
        assert str(result).count('<li class="user">') == 2
        assert self.tester.display_name in result
        assert self.russianfan.display_name in result

        # russianfan is following annafan so he should see an Unfollow
        # button.
        offset = url_for(controller='user', action='followers',
                id='annafan')
        extra_environ = {'Authorization': str(self.russianfan.apikey)}
        result = self.app.get(offset, extra_environ=extra_environ)
        assert 'Unfollow' in result
示例#13
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
示例#14
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
示例#15
0
    def rejected(self):
        s = Session()

        new_name = request.params.get('name', None)
        if new_name is None:
            abort(404)

        db_file = s.query(Upload).get(new_name)

        if db_file is None:
            session['messages'] = ["Invalid file"]
            session.save()
            return redirect_to(url_for(controller="moderation"))

        path = os.path.join(get_path("moderation"), db_file.new_name)
        #TODO error handeling
        if os.path.exists(path):
            os.remove(path)

        s.delete(db_file)
        s.commit()

        session['messages'] = ["File rejected"]
        session.save()
        return redirect_to(url_for(controller="moderation"))
示例#16
0
文件: test_user.py 项目: Psykar/ckan
    def test_edit_user_logged_in_username_change_by_id(self):
        user_pass = '******'
        user = factories.User(password=user_pass)
        app = self._get_test_app()

        # Have to do an actual login as this test relys on repoze cookie handling.
        # get the form
        response = app.get('/user/login')
        # ...it's the second one
        login_form = response.forms[1]
        # fill it in
        login_form['login'] = user['name']
        login_form['password'] = user_pass
        # submit it
        login_form.submit()

        # Now the cookie is set, run the test
        response = app.get(
            url=url_for(controller='user', action='edit', id=user['id']),
        )
        # existing values in the form
        form = response.forms['user-edit-form']

        # new values
        form['name'] = 'new-name'
        response = submit_and_follow(app, form, name='save')
        response = helpers.webtest_maybe_follow(response)

        expected_url = url_for(controller='user', action='read', id='new-name')
        assert response.request.path == expected_url
示例#17
0
    def __init__(self, session, mail, name, *args, **kwargs):
        self.session = session
        self.mail = mail
        self.name = name

        controller = "ckanext.repoze.who.shibboleth.controller:ShibbolethController"
        self.login_url = url_for(controller=controller, action="shiblogin")
        self.logout_url = url_for(controller="user", action="logout")
    def test_data_creation_csv(self):
        """Test CSV report."""
        app = self._get_test_app()
        # dr = self._get_dr(app, DC_REPORT)
        admin = factories.Sysadmin()
        url = '/report/{0}'.format(DC_REPORT)
        kwpost = dict(
            headers={'Authorization': admin['apikey'].encode('ascii')}
        )
        csv_file1 = StringIO.StringIO()
        fields = ['title', 'url', 'owner', 'created_at']
        csv_writer = csv.DictWriter(csv_file1, fields, quoting=csv.QUOTE_ALL)
        csv_writer.writerow(dict(zip(fields, fields)))

        org = factories.Organization()
        d1 = factories.Dataset(owner_org=org['id'])
        csv_writer.writerow(dict(
            title=d1['title'],
            url=config.get('ckan.site_url') + url_for(
                controller='package', action='read', id=d1['id']),
            owner=org['title'],
            created_at=d1['metadata_created']
        ))

        org = factories.Organization()
        d2 = factories.Dataset(owner_org=org['id'])
        csv_writer.writerow(dict(
            title=d2['title'],
            url=config.get('ckan.site_url') + url_for(
                controller='package', action='read', id=d2['id']),
            owner=org['title'],
            created_at=d2['metadata_created']
        ))

        csv_file1.seek(0)
        required_report = csv_file1.read()

        app.post(url, **kwpost)
        csv_report = app.get(url + '?format=csv')

        nt.assert_equal(csv_report.body, required_report)

        d3 = factories.Dataset(owner_org=org['id'])
        csv_writer.writerow(dict(
            title=d3['title'],
            url=config.get('ckan.site_url') + url_for(
                controller='package', action='read', id=d3['id']),
            owner=org['title'],
            created_at=d3['metadata_created']
        ))

        app.post(url, **kwpost)
        csv_report = app.get(url + '?format=csv')
        nt.assert_not_equal(csv_report.body, required_report)

        csv_file1.seek(0)
        new_required_report = csv_file1.read()
        nt.assert_equal(csv_report.body, new_required_report)
示例#19
0
        def _pagerlink(pagenr, text):
            """
            Create a URL that links to another page using url_for()

            Parameters:
                
            pagenr
                Number of the page that the link points to

            text
                Text to be printed in the A-HREF tag
            """
            # Let the url_for() from webhelpers create a new link and set
            # the variable called 'link_var'. Example:
            # You are in '/foo/bar' (controller='foo', action='bar')
            # and you want to add a parameter 'pagenr'. Then you
            # call the navigator method with link_var='pagenr' and
            # the url_for() call will create a link '/foo/bar?pagenr=...'
            # with the respective page number added.
            link_params = {}
            # Use the instance kwargs from Page.__init__ as URL parameters
            link_params.update(self.kwargs)
            # Add keyword arguments from pager() to the link as parameters
            link_params.update(kwargs)
            link_params[link_var] = pagenr
            # Create the URL to load a certain page
            link_url = routes.url_for(**link_params)
            log.debug("link_url(**%r) => %r", link_params, link_url)
            # Create the URL to load the page area part of a certain page (AJAX updates)
            link_params[partial_var] = 1
            partial_url = routes.url_for(**link_params)
            log.debug("partial_url(**%r) => %r", link_params, partial_url)
            if ajax_id:
                # Return an AJAX link that will update the HTML element
                # named by ajax_id.
                # Degrade gracefully if Javascript is not available by using
                # 'partial_url' in the onclick URLs while using 'link_url'
                # in the A-HREF URL.
                if framework == 'jquery':
                    return tags.link_to(text, url=link_url,
                        onclick="""%s$('#%s').load('%s'); return false""" % \
                                (javascript_before, ajax_id, partial_url), **link_attr)
                elif framework == 'yui':
                    js = """%sYAHOO.util.Connect.asyncRequest('GET','%s',{
                        success:function(o){YAHOO.util.Dom.get('%s').innerHTML=o.responseText;}
                        },null); return false;""" % (javascript_before, partial_url, ajax_id)
                    return tags.link_to(text, url=link_url, onclick=js, **link_attr)
                elif framework == 'extjs':
                    js = """%sExt.get('%s').load({url:'%s'}); return false;""" % (javascript_before, ajax_id, partial_url)
                    return tags.link_to(text, url=link_url, onclick=js, **link_attr)
                else:
                    raise Exception, "Unsupported Javascript framework: %s" % framework

            else:
                # Return a normal a-href link that will call the same
                # controller/action with the link_var set to the new
                # page number.
                return tags.link_to(text, link_url, **link_attr)
示例#20
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
示例#21
0
def classifier_url(classifier, **kwargs):
    if len(classifier.get('name', '')):
        return url_for(controller='classifier',
                       action='view_by_taxonomy_name',
                       name=classifier.get('name'),
                       taxonomy=classifier.get('taxonomy'), **kwargs)
    else:
        return url_for(controller='classifier',
                       action='view', id=str(classifier.get('_id')), **kwargs)
示例#22
0
    def test_07_private_dataset(self):
        '''Test private datasets.'''

        # Get the 'new dataset' form.
        offset = routes.url_for(controller='package', action='new')
        extra_environ = {'Authorization': str(self.annafan.apikey)}
        response = self.app.get(offset, extra_environ=extra_environ)
        form = response.forms['dataset-edit']

        # Fill out the form and submit it, creating a private dataset.
        form['name'] = 'test_private_dataset'
        form['title'] = "Test Private Dataset"
        form['groups__0__id'] = self.id_for_group('municipality_test_group')
        form['groups__0__capacity'] = 'private'
        response = form.submit('save', extra_environ=extra_environ)

        # The response from submitting the form should be 302 redirect.
        assert response.status == 302
        response = response.follow(extra_environ=extra_environ)

        # It should have redirected us to the read page for the dataset
        # we just created.
        assert response.status == 200
        assert response.request.url.endswith('/dataset/test_private_dataset')

        self.check_that_dataset_is_private()

        # Update the dataset, making it public.
        offset = routes.url_for(controller='package', action='edit',
                id='test_private_dataset')
        extra_environ = {'Authorization': str(self.annafan.apikey)}
        response = self.app.get(offset, extra_environ=extra_environ)
        form = response.forms['dataset-edit']
        form['groups__0__capacity'] = 'public'
        response = form.submit('save', extra_environ=extra_environ)
        assert response.status == 302
        response = response.follow(extra_environ=extra_environ)
        assert response.status == 200
        assert response.request.url.endswith('/dataset/test_private_dataset')

        self.check_that_dataset_is_public()

        # Update the dataset again, making it private again.
        offset = routes.url_for(controller='package', action='edit',
                id='test_private_dataset')
        extra_environ = {'Authorization': str(self.annafan.apikey)}
        response = self.app.get(offset, extra_environ=extra_environ)
        form = response.forms['dataset-edit']
        form['groups__0__capacity'] = 'private'
        response = form.submit('save', extra_environ=extra_environ)
        assert response.status == 302
        response = response.follow(extra_environ=extra_environ)
        assert response.status == 200
        assert response.request.url.endswith('/dataset/test_private_dataset')

        self.check_that_dataset_is_private()
示例#23
0
    def test_proposal_withdraw_lockdown(self, app, db_session):
        prop = ProposalFactory()
        pers1 = PersonFactory(proposals = [prop])
        pers2 = PersonFactory()
        db_session.commit()

        # try to delete the proposal as the other person
        do_login(app, pers2)
        resp = app.get(url_for(controller='proposal', action='withdraw', id=prop.id), status=403)
        resp = app.post(url_for(controller='proposal', action='withdraw', id=prop.id), params={}, status=403)
示例#24
0
    def test_proposal_view_lockdown(self, app, db_session):
        prop = ProposalFactory()
        pers1 = PersonFactory(proposals = [prop])
        pers2 = PersonFactory()
        db_session.commit()

        # try to view the proposal as the other person
        do_login(app, pers2)
        resp = app.get(url_for(controller='proposal', action='edit', id=prop.id), status=403)
        resp = app.get(url_for(controller='proposal', action='view', id=prop.id), status=403)
示例#25
0
def test_unicode_static():
    hoge = u'\u30c6\u30b9\u30c8' # the word test in Japanese
    hoge_enc = urllib.quote(hoge.encode('utf-8'))
    m = Mapper()
    m.minimization = False
    m.connect('google-jp', 'http://www.google.co.jp/search', _static=True)
    m.create_regs(['messages'])
    eq_("http://www.google.co.jp/search?q=" + hoge_enc,
                     url_for('google-jp', q=hoge))
    assert isinstance(url_for('google-jp', q=hoge), str)
示例#26
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")
示例#27
0
    def upload(self):

        c.session = Session()
        session['messages'] = []
        author = c.session.query(UserData).get(session['user']).name
        VALID_CHARS="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

        uri_dir = request.params.get('path', None)
        if uri_dir is None:
            abort(404)
        destination = c.session.query(Dir).get(uri_dir)
        if destination is None:
            abort(404)
        else:
            destination = destination.path

        myfiles = request.POST.getall('myfile')

        for myfile in myfiles:
            if myfile == "":
               return redirect_to(url_for(controller="upload") + '?path=' + str(uri_dir))

            original_name = myfile.filename
            myfile.filename = u"".join(random.sample(VALID_CHARS, 16))
            permanent_file = open(os.path.join(config['app_conf']['upload_dir'], myfile.filename), 'w')

            shutil.copyfileobj(myfile.file, permanent_file)

            #add it to the Upload database
            p = re.compile("^[A-Za-z0-9_.][A-Za-z0-9_.-]{0,99}$")
            if not p.match(original_name):
                session['messages'] += ['ERROR invalid filename : %s' % (original_name)]
                session.save()
            else:
                filename = original_name
                ext = os.path.splitext(filename)[1].lower()
                db_file = Upload(name = filename,
                                file_type = ext,
                                destination = destination,
                                description = request.POST.get('description', ''),
                                new_name = myfile.filename,
                                author = author)

                Session.add(db_file)
                Session.commit()

                myfile.file.close()
                permanent_file.close()

                #Security?
                session['messages'] += ['Successfully uploaded: %s' % (original_name)]
                session.save()

        return redirect_to(url_for(controller="upload") + '?path=' + str(uri_dir))
示例#28
0
文件: test_user.py 项目: 6779660/ckan
    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')
示例#29
0
 def test_button_to_with_img(self):
     self.assertEqual(
         u'<form action="/content/edit/3" class="button-to" method="POST"><div><input alt="Edit" src="/images/icon_delete.gif" type="image" value="Edit" /></div></form>',
         button_to("Edit", url_for(action="edit", id=3), type="image", src="/images/icon_delete.gif"),
     )
     self.assertEqual(
         u'<form action="/content/submit/3" class="button-to" method="POST"><div><input alt="Complete the form" src="submit.png" type="image" value="Submit" /></div></form>',
         button_to(
             "Submit", url_for(action="submit", id=3), type="image", src="submit.png", alt="Complete the form"
         ),
     )
    def test_view(self, app, db_session):
        # Redirects to edit page
        target = ScheduleFactory()
        user = PersonFactory(roles = [RoleFactory(name = 'organiser')])
        db_session.commit()

        do_login(app, user)
        resp = app.get(url_for(controller='schedule', action='view', id=target.id))
        
        # Check for redirect
        assert resp.status_code == 302
        assert url_for(controller='schedule', action='edit', id=target.id) in resp.location
示例#31
0
    def test_user_activity(self):
        """Test user activity streams HTML rendering."""

        # Register a new user.
        user_dict = {'name': 'billybeane',
                'fullname': 'Billy Beane',
                'about': 'General Manager, Oakland Athletics',
                'email': '*****@*****.**',
                'password': '******'}
        context = {
            'model': ckan.model,
            'session': ckan.model.Session,
            'user': self.sysadmin_user.name,
            'allow_partial_update': True,
            }
        user = user_create(context, user_dict)
        offset = url_for(controller='user', action='activity', id=user['id'])
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s signed up' % user['fullname'] in stripped, stripped

        # Create a new package.
        package = {
            'name' : 'baseball_stats',
            'title' : "Billy's Stats about Baseball Players",
        }
        context['user'] = user['name']
        # FIXME This test use an old way to get at the schema to
        # recreate this we need to pretend to be using the api. We
        # should not be calling package_create like this we should be
        # going via the api or package controllers
        context['api_version'] = 3
        context['ignore_auth'] = True
        package = package_create(context, package)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s created the dataset %s ' % (
                user['fullname'], package['title']) in stripped, stripped

        # Add a resource to the package.
        resource = {
            'url': 'http://www.example.com',
            'description': "Chad Bradford's OBP Stats`",
            'format': 'cvs',
            'name': 'Chad Bradford Stats',
            }
        package['resources'].append(resource)
        request_data = {
                'id': package['id'],
                'resources': package['resources'],
                }
        package = package_update(context, request_data)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s added the resource %s to the dataset %s' % \
                (user['fullname'], resource['name'], package['title']) \
                in stripped, stripped

        # Update the package.
        package['title'] =  "Billy's Updated Stats about Baseball Players"
        package = package_update(context, package)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s updated the dataset %s' \
                % (user['fullname'], package['title']) \
                in stripped, stripped

        # Update the resource.
        resource = package['resources'][0]
        resource['name'] = 'Chad Bradford Updated Stats'
        resource = resource_update(context, resource)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s updated the resource %s in the dataset %s' \
                % (user['fullname'], resource['name'], package['title']) \
                in stripped, stripped

        # Delete the resource.
        context['allow_partial_update'] = False
        package['resources'] = []
        package_update(context, package)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s deleted the resource %s from the dataset %s' % \
                (user['fullname'], resource['name'], package['title']) \
                in stripped, stripped

        # Follow the package.
        follow_dataset(context, {'id': package['id']})
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s started following %s' % (user['fullname'],
                package['title']) not in stripped, stripped

        # Follow another user.
        follow_user(context, {'id': 'joeadmin'})
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s started following %s' % (user['fullname'],
                'joeadmin') not in stripped, stripped

        # Create a new group.
        group = {
            'name': 'baseball-stats-group',
            'title': 'A Group for Datasets about Baseball'
            }
        context['allow_partial_update'] = True
        group = group_create(context, group)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s created the group %s' % (user['fullname'], group['title']) \
                in stripped, stripped

        # Update the group.
        group['title'] = 'updated'
        group = group_update(context, group)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s updated the group %s' % (user['fullname'], group['title']) \
                in stripped, stripped

        # Delete the group.
        group['state'] = 'deleted'
        group_update(context, group)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s deleted the group %s' % (user['fullname'], group['title']) \
                in stripped, stripped

        # Add a new tag to the package.
        tag = {'name': 'baseball'}
        package['tags'].append(tag)
        package = package_update(context, package)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s added the tag %s to the dataset %s' % \
                (user['fullname'], tag['name'], package['title']) \
                in stripped, stripped

        # Remove the tag from the package.
        package['tags'] = []
        context['allow_partial_update'] = False
        package_update(context, package)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s removed the tag %s from the dataset %s' % \
                (user['fullname'], tag['name'], package['title']) \
                in stripped, stripped

        # Add an extra to the package.
        package['extras'].append({'key': 'quality', 'value': '10000'})
        package = package_update(context, package)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s added the extra "%s" to the dataset %s' % \
                (user['fullname'], 'quality', package['title']) \
                in stripped, stripped

        # Update the extra.
        package['extras'][0]['value'] = 'updated'
        package = package_update(context, package)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s changed the extra "%s" of the dataset %s' % \
                (user['fullname'], 'quality', package['title']) \
                in stripped, stripped

        # Delete the extra.
        del package['extras'][0]
        package = package_update(context, package)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s deleted the extra "%s" from the dataset %s' % \
                (user['fullname'], 'quality', package['title']) \
                in stripped, stripped

        # Delete the package.
        # we need to get round the delete permission
        context['ignore_auth'] = True
        package_delete(context, package)
        del context['ignore_auth']
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s deleted the dataset %s' % \
                (user['fullname'], package['title']) \
                in stripped, stripped

        # Update the user's profile.
        user['about'] = ''
        user_update(context, user)
        result = self.app.get(offset, status=200)
        stripped = self.strip_tags(result)
        assert '%s updated their profile' % user['fullname'] \
                in stripped, stripped

        # By now we've created >15 activities, but only the latest 15 should
        # appear on the page.
        result = self.app.get(offset, status=200)
        assert result.body.count('<span class="actor">') \
                == 15, result.body.count('<span class="actor">')

        # The user's dashboard page should load successfully and have the
        # latest 15 activities on it.
        offset = url_for(controller='user', action='dashboard')
        extra_environ = {'Authorization':
                str(ckan.model.User.get('billybeane').apikey)}
        result = self.app.post(offset, extra_environ=extra_environ,
                status=200)
        assert result.body.count('<span class="actor">') == 15, \
            result.body.count('<span class="actor">')
示例#32
0
 def test_maintainer_email_not_exists(self):
     response = self.app.get(
         url=url_for(controller='package', action='new'))
     field_text = "field-maintainer-email"
     assert field_text not in response.body
示例#33
0
 def test_bulk_process_throws_404_for_nonexistent_org(self):
     app = self._get_test_app()
     bulk_process_url = url_for(controller='organization',
                                action='bulk_process',
                                id='does-not-exist')
     app.get(url=bulk_process_url, status=404)
示例#34
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
示例#35
0
 def test_not_logged_in(self):
     app = self._get_test_app()
     app.get(url=url_for(controller='group', action='new'), status=403)
示例#36
0
 def test_user_edit_no_user(self):
     offset = url_for(controller='user', action='edit', id=None)
     res = self.app.get(offset, status=400)
     assert 'No user specified' in res, res
示例#37
0
 def test_home_login(self):
     offset = url_for('home')
     res = self.app.get(offset)
     res = res.click('Login')
     assert 'Login to CKAN' in res, res.body
示例#38
0
 def delete_url(self):
     return url_for("delete_keyword", key=self.key())
示例#39
0
 def delete_url(self):
     return url_for("delete_site", key=self.key())
示例#40
0
 def test_series_plugin_can_be_configured(self):
     _, response = self.get_page_response(url_for('/configurar/series'),
                                          admin_required=True)
     forms = response.forms
     nt.assert_true(isinstance(forms[0]['featured'].value, basestring))
示例#41
0
 def test_url_exists(self):
     _, response = self.get_page_response(url_for('/series/api'),
                                          admin_required=True)
     nt.assert_equals(response.status_int, 200)
示例#42
0
 def apps_url_for(self, *args, **kargs):
     """Like url_for, but starts with "http://apps.facebook.com"."""
     return "http://apps.facebook.com" + url_for(*args, **kargs)
 def test_group_doesnt_exist(self):
     url = url_for(controller='organization',
                   action='edit',
                   id='doesnt_exist')
     self.app.get(url=url, extra_environ=self.user_env,
                  status=404)
 def test_not_logged_in(self):
     self.app.get(url=url_for(controller='group', action='new'),
                  status=302)
示例#45
0
    def test_user_delete_by_unauthorized_user(self):
        user = model.User.by_name(u'annafan')
        url = url_for(controller='user', action='delete', id=user.id)
        extra_environ = {'REMOTE_USER': '******'}

        self.app.get(url, status=401, extra_environ=extra_environ)
示例#46
0
 def report_url(self):
     return url_for("site", key=self.key())
示例#47
0
 def test_user_edit_unknown_user(self):
     offset = url_for(controller='user', action='edit', id='unknown_person')
     res = self.app.get(offset, status=302)  # redirect to login page
     res = res.follow()
     assert 'Login' in res, res
     })
     self.set_state( trans, {
         self.generatorcmd.name: { 'pdbid': 'True',
                                   'params': {'fofc_as': fofc_ass,
                                              'fofc_al': fofc_all,
                                              'tfofc_as': tfofc_ass,
                                              'tfofc_al': tfofc_all,
                                              'omit': omitt,
                                              'sfcheck': sfcheckk,
                                              'mapext': form['mapext'],
                                              'BASE': BASE,
                                              'MTZ': MTZ } }
     })
     self.start_jobs( trans )
     LOG.debug('generator jobs started')
     return redirect_to( url_for( '/tools/eda/generator/task', task_id=trans.task_id ) )
 else:
     data_cif = self.save_uploaded_file( trans, form['data_cif'] )
     data_pdb = self.save_uploaded_file( trans, form['data_pdb'] )
     self.init_state( trans, pdbid=False )
     BASE = form['data_cif']['filename']
     BASE = BASE[::-1]
     BASE = re.sub("/.*$", "", BASE)
     EXT = re.sub("\..*$", "", BASE)
     EXT = EXT[::-1]
     BASE = BASE[::-1]
     BASE = re.sub("\..*$", "", BASE)
     BASE = re.sub("-sf.*$", "", BASE)
     EXT = string.upper(EXT)
     MTZ='False'
     if (EXT == 'MTZ'): MTZ='True'
示例#49
0
 def teardown_class(self):
     # clear routes 'id' so that next test to run doesn't get it
     self.app.get(url_for(controller='user', action='login', id=None))
     SmtpServerHarness.teardown_class()
     model.repo.rebuild_db()
示例#50
0
    def show(self):
        if not (c.services['freemium'].configured
                and c.services['freemium'].enabled):
            # Disallow access.
            return redirect(url_for('status'))

        # Return a rendered template
        page = 0
        limit = 25
        email_criteria = ''
        license_criteria = ''

        order_by = 'email'
        order_dir = 'asc'

        if 'order_by' in request.params:
            order_by = request.params['order_by']

        if 'order_dir' in request.params:
            order_dir = request.params['order_dir']

        if order_by == 'license':
            order_clause = User.license
        elif order_by == 'email':
            order_clause = User.email
        elif order_by == 'created':
            order_clause = User.created_on

        if order_dir == 'asc':
            order_clause = asc(order_clause)
        else:
            order_clause = desc(order_clause)

        if 'page' in request.params:
            try:
                tmp_page = int(request.params['page'])
                if tmp_page > 0:
                    page = tmp_page - 1
            except:
                pass

        if 'limit' in request.params:
            try:
                tmp_limit = int(request.params['limit'])
                if tmp_limit > 0:
                    limit = tmp_limit
            except:
                pass

        if 'email_criteria' in request.params and request.params[
                'email_criteria'].strip():
            email_criteria = request.params['email_criteria'].strip()

        if 'license_criteria' in request.params:
            license_criteria = request.params['license_criteria']

        offset = page * limit
        query = User.query

        if email_criteria:
            query = query.filter(User.email.like('%' + email_criteria + '%'))

        if (not license_criteria) or license_criteria == 'all':
            pass
        elif license_criteria == 'except_none':
            query = query.filter(User.license != 'none')
        else:
            query = query.filter(User.license == license_criteria)

        query = query.filter(User.org_id == self.getFreemiumOrgId())

        c.users = query.order_by(order_clause).limit(limit).offset(offset)
        c.users_count = query.count()
        c.page_count = int(math.ceil(c.users_count / float(limit)))
        c.select_license_criteria = {
            'all': '',
            'except_none': '',
            'none': '',
            'confirm': '',
            'gold': '',
            'freemium': '',
            'bronze': '',
            'silver': ''
        }
        c.license_criteria = license_criteria
        c.select_license_criteria[license_criteria] = 'selected'
        c.email_criteria = email_criteria
        c.page = page + 1
        c.order_by = order_by
        c.order_dir = order_dir

        c.limit = limit

        return render('/user_management/show.mako')
示例#51
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()

        identifiers = self._get_repoze_identifiers()

        if 'auth_tkt' in identifiers:
            # 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()
        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']

        if 'auth_tkt' in identifiers:
            assert 'auth_tkt=' in cookie, cookie
            assert 'testlogin!userid_type:unicode' in cookie, cookie
        elif 'use_beaker' in identifiers:
            assert 'ckan=' in cookie, cookie
        else:
            raise Exception('Unknown cookie identification type')

        # navigate to another page and check username still displayed
        res = res.click('Search')
        assert 'testlogin' in res.body, res.body
示例#52
0
 def return_value_to_default(self, url, form_name, field_name, value):
     # Restauro la información default, tal y como estaba antes de testear
     _, response = self.get_page_response(url_for(url), admin_required=True)
     self.edit_form_value(response, form_name, field_name, value)
示例#53
0
    def test_create(self, app, db_session, smtplib):
        data = {
            'person': {
                'address1': 'Somewhere',
                'address2': 'Over the rainbow',
                'city': 'Way up high',
                'state': 'And the dreams that you dreamed of',
                'postcode': 'Once in',  # a lullaby
                'country': 'AUSTRALIA',
                'phone': 123456789,
                'mobile': 987654321,
            },
            'registration': {
                'over18': '1',
                'keyid':
                'Bob',  # TODO: Shouldn't be required with pgp_collection == "no" but fails sometimes
            },
        }

        CompletePersonFactory.reset_sequence()
        ProductCategoryFactory.reset_sequence()
        ProductFactory.reset_sequence()
        CeilingFactory.reset_sequence()

        p = CompletePersonFactory()

        # Required by templates
        CeilingFactory(name='conference-earlybird')
        CeilingFactory(name='conference-paid')

        # Required for processing registration
        ConfigFactory(category="rego",
                      key="silly_description",
                      value={
                          "adverbs": ['my'],
                          "adjectives": ['cat'],
                          "nouns": ["is"],
                          "starts": ["in"]
                      })
        # TODO: There are issues if pgp_collection is yes but lca_optional_stuff is no
        ConfigFactory(category="rego", key="lca_optional_stuff", value="yes")
        ConfigFactory(category="rego", key="pgp_collection",
                      value="yes")  # TODO: Try no, there are some issues

        ticket_cat = ProductCategoryFactory(name='Ticket',
                                            display_mode='accommodation',
                                            display='qty',
                                            min_qty=0,
                                            max_qty=55)
        shirt_cat = ProductCategoryFactory(name='T-Shirt',
                                           display_mode='shirt',
                                           display='qty',
                                           min_qty=0,
                                           max_qty=55)
        dinner_cat = ProductCategoryFactory(name='Penguin Dinner Ticket',
                                            display_mode='accommodation',
                                            display='qty',
                                            min_qty=0,
                                            max_qty=55)
        accom_cat = ProductCategoryFactory(name='Accommodation',
                                           display_mode='accommodation',
                                           display='qty',
                                           min_qty=0,
                                           max_qty=55)

        ticket = ProductFactory(category=ticket_cat)
        shirt = ProductFactory(category=shirt_cat, description="Men's Small")
        dinner = ProductFactory(category=dinner_cat)
        accom = ProductFactory(category=accom_cat)

        db_session.commit()

        # TODO: Test different conference_status values

        do_login(app, p)
        resp = app.get(url_for(controller='/registration', action='new'))
        resp = resp.maybe_follow()
        f = resp.forms[0]

        for cat in data:
            for elem in data[cat]:
                f[cat + '.' + elem] = data[cat][elem]

        f['products.product_T_Shirt_Mens Small_qty'] = 2
        f['products.product_' + dinner_cat.name + '_' + dinner.description +
          '_qty'] = 3
        f['products.product_' + ticket_cat.name + '_' + ticket.description +
          '_qty'] = 4
        f['products.product_' + accom_cat.name + '_' + accom.description +
          '_qty'] = 5

        resp = f.submit()
        resp = resp.follow()  # Failure indicates form validation error

        assert 'Missing value' not in unicode(resp.body, 'utf-8')

        # Test we have an email that is suitable
        assert smtplib.existing is not None
        assert p.email_address in smtplib.existing.to_addresses

        message = smtplib.existing.message
        assert re.match(r'^.*To:.*%s.*' % p.email_address, message, re.DOTALL)
        assert re.match(r'^.*%s %s' % (p.firstname, p.lastname), message,
                        re.DOTALL)
        assert not re.match(r'^.*<!DOCTYPE', message, re.DOTALL)  # No HTML

        # test that we have a registration
        pid = p.id
        db_session.expunge_all()

        regs = Registration.find_all()
        assert len(regs) == 1
        assert regs[0].person.id == pid
        assert regs[0].over18 == (data['registration']['over18'] == '1')
        assert regs[0].person.address1 == data['person']['address1']
        assert regs[0].person.address2 == data['person']['address2']
        assert regs[0].person.city == data['person']['city']
        assert regs[0].person.state == data['person']['state']
        assert regs[0].person.postcode == data['person']['postcode']
        assert regs[0].person.country == data['person']['country']
        assert regs[0].person.phone == str(data['person']['phone'])
        assert regs[0].person.mobile == str(data['person']['mobile'])
示例#54
0
 def graph_url(self):
     return url_for("keyword_graph", key=self.key())
示例#55
0
def subnav_link(c, text, action, **kwargs):
    return link_to(text,
                   url_for(action=action, **kwargs),
                   class_=('active' if c.action == action else ''))
示例#56
0
 def delete(self, id):
     c.srv = meta.Session.query(Server).filter(Server.id == id).first()
     if c.srv:
         meta.Session.delete(c.srv)
         meta.Session.commit()
     return redirect_to(url_for(action='list', id=None))
示例#57
0
 def test_no_source_url_field_in_add_dataset_form(self):
     response = self.app.get(
         url=url_for(controller='package', action='new'))
     field = 'id="field-url"'
     assert field not in response.body
示例#58
0
 def add_nic(self):
     srv_id = request.params.get('srv_id')
     nic = self.get_nic()
     meta.Session.add(nic)
     meta.Session.commit()
     return redirect_to(url_for(action='edit', id=srv_id))
示例#59
0
 def _get_group_add_member_page(self, app, user, group_name):
     env = {'REMOTE_USER': user['name'].encode('ascii')}
     url = url_for(controller='group', action='member_new', id=group_name)
     response = app.get(url=url, extra_environ=env)
     return env, response
示例#60
0
 def test_group_doesnt_exist(self):
     app = self._get_test_app()
     user = factories.User()
     env = {'REMOTE_USER': user['name'].encode('ascii')}
     url = url_for(controller='group', action='edit', id='doesnt_exist')
     app.get(url=url, extra_environ=env, status=404)