def test_join_unvalidated(self): import ptahcrowd from ptahcrowd.provider import CrowdUser from ptahcrowd.registration import Registration user = CrowdUser(username='******', email='email') ptah.get_session().add(user) ptah.get_session().flush() CROWD = ptah.get_settings(ptahcrowd.CFG_ID_CROWD) CROWD['allow-unvalidated'] = False request = self.make_request( POST = {'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******'}) form = Registration(None, request) form.update_form() res = form.register_handler() self.assertIsInstance(res, HTTPFound) self.assertEqual(res.headers['location'], 'http://example.com') user = ptah.auth_service.get_principal_bylogin('*****@*****.**') self.assertIsInstance(user, CrowdUser) self.assertEqual(user.username, 'test') self.assertIn('Validation email has been sent.', request.render_messages())
def test_join(self): from ptahcrowd.provider import CrowdUser from ptahcrowd.registration import Registration user = CrowdUser(username='******', email='email') ptah.get_session().add(user) ptah.get_session().flush() request = self.make_request( POST = {'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******'}) request.environ['HTTP_HOST'] = 'example.com' form = Registration(None, request) form.update_form() res = form.register_handler() self.assertIsInstance(res, HTTPFound) self.assertEqual(res.headers['location'], 'http://example.com/login-success.html') user = ptah.auth_service.get_principal_bylogin('*****@*****.**') self.assertIsInstance(user, CrowdUser) self.assertEqual(user.name, 'test')
def enableUser(): email = sys.argv[1] ploud_config.initializeConfig() dsn = PLOUD.dsn models.initialize_sql(dsn) config = Configurator() config.manager.push({'registry': config.registry, 'request': None}) conn = ploud_config.PLOUD_POOL.getconn() cursor = conn.cursor() cursor.execute("SELECT email FROM waitinglist " "WHERE completed = %s and email=%s",(False,email)) row = cursor.fetchone() if row is None: print "Can't find email: %s"%email return transaction.begin() password = ''.join( [random.choice(ALLOWED_SITE_NAME_CHARS) for i in range(8)]) user = models.User(email, password) user.type = 0 token = user.token ptah.get_session().add(user) print email, token signup.send_activation(email, token) cursor.execute("UPDATE waitinglist SET completed = %s WHERE email=%s", (True, email)) cursor.close() conn.commit() transaction.commit()
def _create_content(self): import ptahcms factory = ptahcms.ApplicationFactory( ApplicationRoot, '/test', 'root', 'Root App') self.factory = factory class MyContent(ptahcms.Content): __mapper_args__ = {'polymorphic_identity': 'mycontent'} __uri_factory__ = ptah.UriFactory('test') root = factory() folder = MyContent( __name__ = 'folder', __parent__ = root, __path__ = '%sfolder/'%root.__path__) self.folder_uri = folder.__uri__ content = MyContent( __name__ = 'content', __parent__ = folder, __path__ = '%scontent/'%folder.__path__) self.content_uri = content.__uri__ ptah.get_session().add(folder) ptah.get_session().add(content) transaction.commit()
def test_sqla_table_view_model_nodes(self): from ptah.manage.sqla import SQLAModule rec = TestSqlaModuleContent(title='test') ptah.get_session().add(rec) ptah.get_session().flush() #uri = rec.__uri__ #type_uri = rec.__type__.__uri__ request = DummyRequest(params={'batch': 1}) mod = SQLAModule(None, request) table = mod['psqla-ptah_nodes'] render_view_to_response(table, request, '', False).text #self.assertIn(url_quote_plus(uri), res) #self.assertIn(url_quote_plus(type_uri), res) request = DummyRequest(params={'batch': 'unknown'}) render_view_to_response(table, request, '', False).text #self.assertIn(url_quote_plus(uri), res) request = DummyRequest(params={'batch': '0'}) render_view_to_response(table, request, '', False).text
def verify_handler(self): data, errors = self.extract() if errors: self.message(errors, 'form-error') return entry = self.entry request = self.request new_user = False email = data['email'] user = self.session.query(ptahcrowd.CrowdUser).filter( ptahcrowd.CrowdUser.email == email).first() if user is None: new_user = True # create user tinfo = ptahcrowd.get_user_type() user = tinfo.create( name=entry.name, login=email, email=email, password=entry.access_token) tinfo.add(user) # fixme: temporary ptah.get_session().flush() uri = user.__uri__ entry.uri = uri entry.email = email else: uri = user.__uri__ data = {'uri': uri, 'email': email, 'uid': entry.uid} t = ptah.token.service.generate(TOKEN_TYPE, json.dumps(data)) template = VerifyTemplate(entry, request, email=email, token=t) template.send() # login if new_user: self.message('Email verification email has been sent.') cfg = ptah.get_settings(ptahcrowd.CFG_ID_CROWD, request.registry) if cfg['validation']: if cfg['allow-unvalidated']: entry.uri = uri return login(uri, request) else: entry.uri = uri return login(uri, request) else: self.message('User with this email already exists. ' 'You have to verify email before you can login.') return HTTPFound(location=request.application_url)
def test_model_edit_node(self): from ptahcms.manage.model import ModelModule, EditRecord content = Content2() content.title = 'Content test' Session = ptah.get_session() Session.add(content) Session.flush() rowid = content.__id__ transaction.commit() mod = ModelModule(None, DummyRequest()) model = mod['content2'][rowid] form = EditRecord( model, DummyRequest( POST={'title': 'Content', 'form.buttons.modify': 'Modify'})) form.csrf = False form.update() self.assertIn("Model record has been modified.", ptah.view.render_messages(form.request)) transaction.commit() Session = ptah.get_session() content = Session.query(Content2) \ .filter(Content2.__id__ == rowid).first() self.assertEqual(content.title, 'Content')
def test_join_error(self): from ptahcrowd.provider import CrowdUser from ptahcrowd.registration import Registration user = CrowdUser(username='******', email='email') ptah.get_session().add(user) ptah.get_session().flush() request = self.make_request( POST = {'username': '******', 'email': 'custom login', 'password': '******', 'confirm_password': '******'}) form = Registration(None, request) form.update_form() data, errors = form.extract() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].msg[0], 'Invalid email address') form.register_handler() self.assertIn('Please fix indicated errors.', request.render_messages()) request = self.make_request( POST = {'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******'}) form = Registration(None, request) form.update_form() data, errors = form.extract() self.assertEqual(len(errors), 0)
def test_upgrade_several(self): from ptah.migrate import revision, Version ptah.register_migration('test1', 'test1:path', 'Test migration') ptah.register_migration('test2', 'test2:path', 'Test migration') self.init_ptah() versions = dict((v.package, v.version_num) for v in ptah.get_session().query(Version).all()) rev1 = revision('test1') rev2 = revision('test2') sys.argv[:] = ['ptah-migrate', 'ptah.ini', 'upgrade', 'test1', 'test2'] migrate.main() self._reset_stdout() versions = dict((v.package, v.version_num) for v in ptah.get_session().query(Version).all()) self.assertIn('test1', versions) self.assertIn('test2', versions) self.assertEqual(versions['test1'], rev1) self.assertEqual(versions['test2'], rev2)
def test_model_remove(self): from ptahcms.manage.model import ModelModule, ModelView content = Content1() content.title = 'Content test' Session = ptah.get_session() Session.add(content) Session.flush() rowid = content.__id__ transaction.commit() mod = ModelModule(None, DummyRequest()) model = mod['content1'] form = ModelView( model, DummyRequest( POST=MultiDict( list({'rowid':rowid, 'form.buttons.remove': 'Remove'}.items())))) form.csrf = False res = form.update() self.assertIsInstance(res, HTTPFound) transaction.commit() Session = ptah.get_session() rec = Session.query(Content1).filter( Content1.__id__ == rowid).first() self.assertIsNone(rec)
def _create_content(self): import ptahcms factory = ptahcms.ApplicationFactory(ApplicationRoot, '/test', 'root', 'Root App') self.factory = factory class MyContent(ptahcms.Content): __mapper_args__ = {'polymorphic_identity': 'mycontent'} __uri_factory__ = ptah.UriFactory('test') root = factory() folder = MyContent(__name__='folder', __parent__=root, __path__='%sfolder/' % root.__path__) self.folder_uri = folder.__uri__ content = MyContent(__name__='content', __parent__=folder, __path__='%scontent/' % folder.__path__) self.content_uri = content.__uri__ ptah.get_session().add(folder) ptah.get_session().add(content) transaction.commit()
def test_join(self): from ptahcrowd.provider import CrowdUser from ptahcrowd.registration import Registration user = CrowdUser(username='******', email='email') ptah.get_session().add(user) ptah.get_session().flush() class Stub(object): status = '' def send(self, frm, to, msg): Stub.status = 'Email has been sended' MAIL = ptah.get_settings(ptah.CFG_ID_PTAH) MAIL['mailer'] = Stub() request = self.make_request( POST = {'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******'}) request.environ['HTTP_HOST'] = 'example.com' form = Registration(None, request) form.update_form() res = form.register_handler() self.assertIsInstance(res, HTTPFound) self.assertEqual(res.headers['location'], 'http://example.com/login-success.html') user = ptah.auth_service.get_principal_bylogin('*****@*****.**') self.assertIsInstance(user, CrowdUser) self.assertEqual(user.name, 'test')
def test_sqla_table_editrec_remove(self): from ptah.manage.sqla import SQLAModule, EditRecord rec = TestSqlaModuleTable() rec.name = 'Test record' ptah.get_session().add(rec) ptah.get_session().flush() rec_id = rec.id mod = SQLAModule(None, DummyRequest()) table = mod['psqla-test_sqla_table'] rec = table[rec_id] request = self.make_request( POST={'form.buttons.remove': 'Remove'}) form = EditRecord(rec, request) form.csrf = False res = form() self.assertIn('Table record has been removed.', request.render_messages()) self.assertIsInstance(res, HTTPFound) self.assertEqual(res.headers['location'], '..') rec = ptah.get_session().query(TestSqlaModuleTable).filter( TestSqlaModuleTable.id == rec_id).first() self.assertIsNone(rec, None)
def test_model_edit_node(self): from ptahcms.manage.model import ModelModule, EditRecord content = Content2() content.title = 'Content test' Session = ptah.get_session() Session.add(content) Session.flush() rowid = content.__id__ transaction.commit() mod = ModelModule(None, DummyRequest()) model = mod['content2'][rowid] form = EditRecord( model, DummyRequest(POST={ 'title': 'Content', 'form.buttons.modify': 'Modify' })) form.csrf = False form.update() self.assertIn("Model record has been modified.", ptah.view.render_messages(form.request)) transaction.commit() Session = ptah.get_session() content = Session.query(Content2) \ .filter(Content2.__id__ == rowid).first() self.assertEqual(content.title, 'Content')
def test_sqla_table_editrec_basics(self): from ptah.manage.sqla import SQLAModule, EditRecord rec = TestSqlaModuleTable() rec.name = 'Test record' ptah.get_session().add(rec) ptah.get_session().flush() rec_id = rec.id request = self.make_request() mod = SQLAModule(None, request) table = mod['psqla-test_sqla_table'] rec = table[rec_id] form = EditRecord(rec, request) form.update_form() self.assertEqual(form.label, 'record 1') self.assertEqual(form.form_content(), {'name': 'Test record'}) request = DummyRequest( POST={'form.buttons.cancel': 'Cancel'}) form = EditRecord(rec, request) res = form() self.assertIsInstance(res, HTTPFound) self.assertEqual(res.headers['location'], '..')
class AuthProvider(object): _sql_get_login = ptah.QueryFreezer( lambda: ptah.get_session().query(User)\ .filter(User.login==sqla.sql.bindparam('login'))) _sql_search = ptah.QueryFreezer( lambda: ptah.get_session().query(User) \ .filter(sqla.sql.or_( User.name.contains(sqla.sql.bindparam('term')), User.email.contains(sqla.sql.bindparam('term'))))\ .order_by(sqla.sql.asc('name'))) def authenticate(self, creds): login, password = creds['login'], creds['password'] user = self._sql_get_login.first(login=login) if user is not None: if ptah.pwd_tool.check(user.password, password): return user def get_principal_bylogin(self, login): return self._sql_get_login.first(login=login) def add(self, user): """ Add user to crowd application. """ Session = ptah.get_session() Session.add(user) Session.flush() return user def get_user_bylogin(self, login): """ Given a login string return a user """ return self._sql_get_login.first(login=login)
def test_model_remove(self): from ptahcms.manage.model import ModelModule, ModelView content = Content1() content.title = 'Content test' Session = ptah.get_session() Session.add(content) Session.flush() rowid = content.__id__ transaction.commit() mod = ModelModule(None, DummyRequest()) model = mod['content1'] form = ModelView( model, DummyRequest(POST=MultiDict( list({ 'rowid': rowid, 'form.buttons.remove': 'Remove' }.items())))) form.csrf = False res = form.update() self.assertIsInstance(res, HTTPFound) transaction.commit() Session = ptah.get_session() rec = Session.query(Content1).filter(Content1.__id__ == rowid).first() self.assertIsNone(rec)
def test_loadapi_load(self): content = Content(title='Content') uri = content.__uri__ ptah.get_session().add(content) transaction.commit() content = ptahcms.load(uri) self.assertEqual(content.__uri__, uri)
def updateAction(form): data, errors = form.extract() if errors: form.message(errors, 'form-error') return category = models.Category(name = data['name']) ptah.get_session().add(category) form.message('Category has been created.') return HTTPFound(location='/')
def updateAction(form): data, errors = form.extract() if errors: form.message(errors, 'form-error') return link = models.Link(title = data['title'], href = data['href'], color = data['color']) ptah.get_session().add(link) form.message('Link has been created.') return HTTPFound(location='/')
def updateAction(form): data, errors = form.extract() if errors: form.message(errors, 'form-error') return obj = models.RackObject(title=data['title'], label=data['label'], objtype=data['objtype']) ptah.get_session().add(obj) form.message('RackObject has been created.') return HTTPFound(location='/')
def test_sqla_table_remove(self): from ptah.manage.sqla import SQLAModule, TableView rec = TestSqlaModuleTable() rec.name = 'Test record' ptah.get_session().add(rec) ptah.get_session().flush() rec_id = rec.id request = self.make_request() mod = SQLAModule(None, request) table = mod['psqla-test_sqla_table'] request = self.make_request( POST=MultiDict([('form.buttons.remove', 'Remove')])) form = TableView(table, request) form.csrf = False form.update_form() self.assertIn('lease select records for removing.', request.render_messages()) request = self.make_request( POST=MultiDict([('form.buttons.remove', 'Remove'), ('rowid', 'wrong')])) form = TableView(table, request) form.csrf = False form.update_form() #self.assertIn('Please select records for removing.', # request.render_messages()) request = self.make_request( POST=MultiDict([('form.buttons.remove', 'Remove'), ('rowid', rec_id), ('csrf-token', self.request.session.get_csrf_token())])) form = TableView(table, request) form.csrf = True form.update_form() self.assertIn('Select records have been removed.', request.render_messages()) rec = ptah.get_session().query(TestSqlaModuleTable).filter( TestSqlaModuleTable.id == rec_id).first() self.assertIsNone(rec, None)
class User(ptah.get_base()): """Default user ``name``: User name. ``email``: User email. ``properties``: User properties. """ __tablename__ = 'users' id = sqla.Column(sqla.Integer, primary_key=True) token = sqla.Column(sqla.String(255), index=True) source = sqla.Column(sqla.String(18)) name = sqla.Column(sqla.Unicode(255)) email = sqla.Column(sqla.Unicode(255), unique=True) joined = sqla.Column(sqla.DateTime()) properties = sqla.Column(ptah.JsonDictType(), default={}) def __init__(self, **kw): self.joined = datetime.utcnow() self.properties = {} super(User, self).__init__(**kw) def __str__(self): return self.name def __name__(self): return str(self.id) def __repr__(self): return '%s<%s:%s>' % (self.__class__.__name__, self.name, self.__uri__) _sql_get_id = ptah.QueryFreezer( lambda: ptah.get_session().query(User)\ .filter(User.id==sqla.sql.bindparam('id'))) @classmethod def get_byid(cls, id): return cls._sql_get_id.first(id=id) _sql_get_token = ptah.QueryFreezer( lambda: ptah.get_session().query(User)\ .filter(User.token==sqla.sql.bindparam('token'))) @classmethod def get_bytoken(cls, token): return cls._sql_get_token.first(token=token)
def test_sqla_table_view_model(self): from ptah.manage.sqla import SQLAModule ptah.get_session().add(TestSqlaModuleContent(title='test')) request = self.make_request() mod = SQLAModule(None, request) table = mod['psqla-test_sqla_content'] res = render_view_to_response(table, request, '', False).text self.assertIn('Inherits from:', res) self.assertIn('ptah_node', res) self.assertNotIn('form.buttons.add', res)
def test_get_bylogin(self): from ptahcrowd.provider import \ CrowdAuthProvider, CrowdUser provider = CrowdAuthProvider() self.assertIsNone(provider.get_principal_bylogin('test')) user = CrowdUser(username='******', email='*****@*****.**', password=ptah.pwd_tool.encode('12345')) ptah.get_session().add(user) ptah.get_session().flush() user = provider.get_principal_bylogin('test') self.assertIsInstance(user, CrowdUser) self.assertEqual(user.username, 'test')
def validateTransfer(request): site_id = request.params.get('site_id','') newowner = request.POST.get('newowner','').lower() principal = authenticated_userid(request) user = User.getByURI(principal) pol = POLICIES[user.type] if user.transfers >= pol.transfers: return {'newowner': "You are not allowed to transfer site."}, None if newowner == principal: return {'newowner': "Can't transfer sit to itself."}, None user = ptah.get_session().query(User).filter_by(email = newowner).first() if user is None: return {'newowner': 'User is not found.'}, None l = 0 for s in user.sites: if not s.removed: l += 1 remaining = POLICIES[user.type].sites - l if remaining <= 0: return {'newowner': 'User aready has created maximum number of allowed sites.'}, None data = {'site': site_id, 'user_id': user.id, 'type': user.type} return {}, data
def transfer(request): errors, data = validateTransfer(request) if errors: return HTTPFound( location="/dashboard.html?message=Can't transfer site.") site = ptah.get_session().query(Site).filter_by(id = data['site']).first() if site is None: return HTTPFound( location="/dashboard.html?message=Can't transfer site.") principal = authenticated_userid(request) user = User.getByURI(principal) if site.user_id != user.id: return HTTPFound( location="/dashboard.html?message=Can't transfer site.") user.transfers += 1 site.user_id = data['user_id'] # change policy hosts = [h.host for h in site.hosts] POLICIES[data['type']].changeHostsPolicy(hosts, site.site_name) # change owner of new site if maintenance.maintence is not None: maintenance.maintence.execute(hosts[0], 'ploud-fix-owner') return HTTPFound( location="/dashboard.html?message=Site has been transfered.")
def check_version(ev): """ ApplicationCreated event handler """ if not Version.__table__.exists(): return versions = dict((v.package, v.version_num) for v in ptah.get_session().query(Version).all()) packages = ptah.get_cfg_storage(MIGRATION_ID).keys() has_steps = False log = logging.getLogger('ptah.alembic') for pkg in packages: version = versions.get(pkg) script = ScriptDirectory(pkg) for sc in script.walk_revisions(): if sc.is_head: if sc.revision != version: has_steps = True log.error("Package '%s' current revision: '%s', head: '%s'", pkg, version, sc.revision) break if has_steps: config.shutdown() log.error("Please run `ptah-migrate` script. Stopping...") raise SystemExit(1)
def login(request): site_id = request.params.get('site_id', '') try: site_id = int(site_id) except: return HTTPFound(location = '/dashboard.html') site = ptah.get_session().query(Site).filter_by(id = site_id).first() if site is None: return HTTPFound( location = "/dashboard.html?message=Can't find site information.") principal = authenticated_userid(request) user = User.getByURI(principal) if user is None: return HTTPFound( location = "/dashboard.html?message=Can't find site information.") if site.user_id != user.id: return HTTPFound( location = "/dashboard.html?message=Can't find site information.") data = '%s::%s'%(user.email, user.password) tid = token.service.generate(LOGIN_TOKEN_TYPE, data) return HTTPFound(location='http://%s/authToken?token=%s'%(site.hosts[0].host, tid))
def update(self): self.user = ptah.auth_service.get_current_principal() self.isAnon = self.user is None self.manage_url = ptah.manage.get_manage_url(self.request) # query for links to populate links box self.objects = ptah.get_session().query(models.RackObject)
def update(self): request = self.request self.manage_url = ptah.manage.get_manage_url(request) Session = ptah.get_session() uids = request.POST.getall('uid') if 'remove' in request.POST and uids: for grp in Session.query(CrowdGroup).\ filter(CrowdGroup.__uri__.in_(uids)): grp.delete() self.request.add_message( _("The selected groups have been removed."), 'info') self.size = Session.query(CrowdGroup).count() try: current = int(request.params.get('batch', None)) if not current: current = 1 request.session['crowd-grp-batch'] = current except: current = request.session.get('crowd-grp-batch') if not current: current = 1 self.current = current self.pages, self.prev, self.next = self.page(self.size, self.current) offset, limit = self.page.offset(current) self.groups = Session.query(CrowdGroup)\ .offset(offset).limit(limit).all()
def test_model_list(self): from ptahcms.manage.model import ModelModule, ModelView content = Content1() content.title = 'Content test' Session = ptah.get_session() Session.add(content) Session.flush() rowid = content.__id__ transaction.commit() mod = ModelModule(None, DummyRequest()) model = mod['content1'] res = render_view_to_response(model, DummyRequest(), '', False) self.assertIn('value="%s"' % rowid, res.text) res = render_view_to_response(model, DummyRequest(params={'batch': 0}), '', False) self.assertIn('value="%s"' % rowid, res.text) res = render_view_to_response( model, DummyRequest(params={'batch': 'unknown'}), '', False) self.assertIn('value="%s"' % rowid, res.text)
def __call__(self, request=None): root = self._sql_get_root.first(name=self.name, type=self.type.__uri__) if root is None: root = self.type.create(title=self.title, description=self.description, public=self.public) root.__name_id__ = self.name root.__path__ = self.path Session = ptah.get_session() Session.add(root) Session.flush() root.__root_path__ = self.path policy = self.policy(request) if self.parent_factory: root.__parent__ = self.parent_factory() else: root.__parent__ = policy root.__default_root__ = self.default_root if request is not None: set_policy(policy) request.root = root if self.parent_factory: policy.__parent__ = self.parent_factory() return root
def add(self, user): """ Add user to crowd application. """ Session = ptah.get_session() Session.add(user) Session.flush() return user
def test_freezer_all(self): import ptah class Test(ptah.get_base()): __tablename__ = 'test13' id = sqla.Column('id', sqla.Integer, primary_key=True) name = sqla.Column(sqla.Unicode()) Session = ptah.get_session() ptah.get_base().metadata.create_all() transaction.commit() sql_get = ptah.QueryFreezer(lambda: Session.query(Test).filter( Test.name == sqla.sql.bindparam('name'))) self.assertIsNone(sql_get.first(name='test')) rec = Test() rec.name = 'test' Session.add(rec) Session.flush() rec = sql_get.all(name='test') self.assertEqual(rec[0].name, 'test')
def test_polymorphic_node(self): import ptahcms class MyContent(ptahcms.Node): __mapper_args__ = {'polymorphic_identity': 'mycontent'} __uri_factory__ = ptah.UriFactory('test') content = MyContent() _uri = content.__uri__ ptah.get_session().add(content) transaction.commit() c = ptah.get_session().query( ptahcms.Node).filter(ptahcms.Node.__uri__ == _uri).one() self.assertTrue(isinstance(c, MyContent))
def test_node(self): import ptahcms class MyContent(ptahcms.Node): __uri_factory__ = ptah.UriFactory('test') content = MyContent() _uri = content.__uri__ ptah.get_session().add(content) transaction.commit() c = ptah.get_session().query( ptahcms.Node).filter(ptahcms.Node.__uri__ == _uri).one() self.assertTrue(isinstance(c, ptahcms.Node)) self.assertIs(ptah.get_session().object_session(c), c.get_session())
def get_groups_vocabulary(context): groups = [] for grp in ptah.get_session().query(CrowdGroup).all(): groups.append((grp.title, form.SimpleTerm(grp.__uri__, grp.__uri__, grp.title))) groups.sort() return form.SimpleVocabulary(*[term for _t, term in sorted(groups)])
def create(self, parent=None): blob = Blob(__parent__=parent) Session = ptah.get_session() Session.add(blob) Session.flush() return blob
def test_model_add_node(self): from ptahcms.manage.model import ModelModule, AddRecord mod = ModelModule(None, DummyRequest()) model = mod['content2'] form = AddRecord( model, DummyRequest(POST={ 'title': 'Test content', 'form.buttons.add': 'Add' })) form.csrf = False res = form.update() id = form.record.__id__ transaction.commit() Session = ptah.get_session() self.assertIsInstance(res, HTTPFound) self.assertEqual(res.headers['location'], './%s/' % id) self.assertEqual(len(Session.query(self.Content2).all()), 1) content = Session.query(self.Content2) \ .filter(self.Content2.__id__ == id).first() self.assertEqual(content.title, 'Test content')
def register_type_impl( config, cls, tinfo, name, fieldset=None, fieldNames=None, **kw): # generate schema fieldset = kw.get('fieldset') if fieldset is None: kw['fieldset'] = ptah.generate_fieldset( cls, fieldNames=fieldNames, namesFilter=names_filter) log.info("Generating fieldset for %s content type.", cls) if 'global_allow' not in kw and not issubclass(cls, Content): kw['global_allow'] = False tinfo.__dict__.update(kw) tinfo.cls = cls config.get_cfg_storage(TYPES_DIR_ID)[tinfo.__uri__] = tinfo # sql query for content resolver cls.__uri_sql_get__ = ptah.QueryFreezer( lambda: ptah.get_session().query(cls) \ .filter(cls.__uri__ == sqla.sql.bindparam('uri'))) # build cms actions build_class_actions(cls)
def test_freezer_one(self): import ptah class Test(ptah.get_base()): __tablename__ = 'test10' id = sqla.Column('id', sqla.Integer, primary_key=True) name = sqla.Column(sqla.Unicode()) Session = ptah.get_session() ptah.get_base().metadata.create_all() transaction.commit() sql_get = ptah.QueryFreezer(lambda: Session.query(Test).filter( Test.name == sqla.sql.bindparam('name'))) self.assertRaises(sqla.orm.exc.NoResultFound, sql_get.one, name='test') rec = Test() rec.name = 'test' Session.add(rec) Session.flush() rec = sql_get.one(name='test') self.assertEqual(rec.name, 'test') rec = Test() rec.name = 'test' Session.add(rec) Session.flush() self.assertRaises(sqla.orm.exc.MultipleResultsFound, sql_get.one, name='test')
def test_module_validate(self): from ptahcrowd.provider import CrowdUser from ptahcrowd.views import CrowdModuleView mod = self._make_mod() user = self._make_user() user.validated = False id = user.id form = CrowdModuleView( mod, self.make_request(POST=MultiDict((('uid', id), ('validate', 'validate'))))) form.csrf = False form.update_form() transaction.commit() self.assertIn('The selected accounts have been validated.', form.request.render_messages()) user = ptah.get_session().query(CrowdUser)\ .filter(CrowdUser.id==id).first() self.assertTrue(user.validated)
def updatedb(self, **data): self.update(data) name = self.__name__ fields = self.__fields__ Session = ptah.get_session() # remove old data keys = tuple("{0}.{1}".format(name, key) for key in data.keys()) if keys: Session.query(SettingRecord).filter(SettingRecord.name.in_(keys)).delete(False) # insert new data for fname in data.keys(): if fname in fields: field = fields[fname] value = self[fname] if value == field.default: continue rec = SettingRecord(name="{0}.{1}".format(name, fname), value=ptah.json.dumps(value)) else: rec = SettingRecord(name="{0}.{1}".format(name, fname), value=JsonType.serializer.dumps(data[fname])) Session.add(rec) Session.flush() self.__registry__.notify(ptah.events.SettingsGroupModified(self)) self.__registry__.notify(ptah.events.UriInvalidateEvent(self.__uri__))
def factory(request): id_ = request.matchdict.get('id') if id_: return ptah.get_session().query(Link) \ .filter(Link.__id__ == id_).first() return HTTPNotFound(location='.')
def tearDown(self): import ptah.util ptah.util.tldata.clear() import ptah.security ptah.security.DEFAULT_ACL[:] = [] from ptah.config import ATTACH_ATTR mod = sys.modules[self.__class__.__module__] if hasattr(mod, ATTACH_ATTR): delattr(mod, ATTACH_ATTR) transaction.abort() ptah.get_session().remove() testing.tearDown()