def test_get(self): import datetime import json from z3c.saconfig import Session from euphorie.client.model import Company from euphorie.client.model import SurveySession from euphorie.content.tests.utils import BASIC_SURVEY from euphorie.client.tests.utils import addAccount from euphorie.client.tests.utils import addSurvey from euphorie.client.api.authentication import generate_token from Products.Five.testbrowser import Browser self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) account = addAccount(password='******') survey_session = SurveySession( title=u'Dummy session', created=datetime.datetime(2012, 4, 22, 23, 5, 12), modified=datetime.datetime(2012, 4, 23, 11, 50, 30), zodb_path='nl/ict/software-development', account=account, company=Company(country='nl', employees='1-9', referer='other')) Session.add(survey_session) browser = Browser() browser.addHeader('X-Euphorie-Token', generate_token(account)) browser.open( 'http://nohost/plone/client/api/users/1/sessions/1/company') self.assertEqual(browser.headers['Content-Type'], 'application/json') response = json.loads(browser.contents) self.assertEqual(response['type'], 'company')
def testTearDown(self): self._close_db() from fernlehrgang.models import Base session = Session() Base.metadata.drop_all(session.connection().engine) transaction.commit() session.close()
def __init__(self, data): session = Session() context = Mail() context.parsing_date = datetime.now() mail = message_from_string(data) for name, adapter in component.getAdapters((context,), interfaces.IFieldMapper): adapter.parse(mail) for part in mail.mailparts: type = part.type adapter = component.queryAdapter(context, interface=interfaces.IContentMapper, name=type) if adapter is None: adapter = component.getAdapter(context, interface=interfaces.IContentMapper, name='default') adapter.parse(part) backuppath = local_configuration['backup'].get('backup', '') if os.path.isdir(backuppath): name = time.strftime('%Y%m%d%H%M') path = os.path.join(backuppath, '%s.mail' % name) counter = 0 while os.path.isfile(path): path = os.path.join(backuppath, '%s_%s.mail' % (name, counter,)) counter += 1 context.original_path = os.path.abspath(path) with open(path, 'w') as f: f.write(data) f.close() context.hash = hashlib.md5(data).hexdigest() session.add(context) transaction.commit() session.close()
def removeClassSubscriptions(ploneClassPath): """ Remove any subscriptions for the class we're removing """ dbSub = (Session.query( db.Subscription).filter_by(plonePath=ploneClassPath).delete()) Session.flush()
def test_with_introduction(self): import datetime import json from z3c.saconfig import Session from euphorie.client.model import SurveySession from euphorie.client.api.authentication import generate_token from euphorie.content.tests.utils import BASIC_SURVEY from euphorie.client.tests.utils import addAccount from euphorie.client.tests.utils import addSurvey self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) survey = self.portal.client['nl']['ict']['software-development'] survey.introduction = u'<p>Fancy intro.</p>' account = addAccount(password='******') survey_session = SurveySession( title=u'Dummy session', created=datetime.datetime(2012, 4, 22, 23, 5, 12), modified=datetime.datetime(2012, 4, 23, 11, 50, 30), zodb_path='nl/ict/software-development', account=account) Session.add(survey_session) browser = Browser() browser.addHeader('X-Euphorie-Token', generate_token(account)) browser.open('http://nohost/plone/client/api/users/1/sessions/1') self.assertEqual(browser.headers['Content-Type'], 'application/json') response = json.loads(browser.contents) self.assertTrue('introduction' in response) self.assertEqual(response['introduction'], u'<p>Fancy intro.</p>')
def testEnumerateUsers_NoInexactMatch(self): session = Session() account = model.Account(loginname='john', password=u'jane') session.add(account) plugin = EuphorieAccountPlugin('plugin') self.assertEqual( plugin.enumerateUsers(login='******', exact_match=False), [])
def test_authenticate_login_valid_login(self): session = Session() account = model.Account(loginname='john', password=u'jane') session.add(account) plugin = EuphorieAccountPlugin('plugin') credentials = {'login': '******', 'password': u'jane'} self.assertTrue(plugin._authenticate_login(credentials) is not None)
def setLogEntry(self, body, message): log_entry = simplejson.loads(body) from fernlehrgang import models typ = log_entry.pop('typ') if typ == "ausstattung": log_entry['type'] = u"Ausstattung Büro %s, Lager %s, Verkauf %s" % ( log_entry.pop('buero'), log_entry.pop('lager'), log_entry.pop('verkauf')) elif typ == "fortschritt": log_entry.pop('position') log_entry['kursteilnehmer_id'] = int(log_entry['kursteilnehmer_id']) log_entry['type'] = u"Level %s (%s) zu %s abgeschlossen." % ( log_entry.pop('title'), log_entry.pop('key'), log_entry.pop('progress')) log_entry['type'] = log_entry['type'][:30] try: with transaction.manager as tm: session = Session() teilnehmer = session.query(models.Teilnehmer).get(int(log_entry.get('teilnehmer_id'))) if teilnehmer: je = models.JournalEntry(**log_entry) teilnehmer.journal_entries.append(je) message.ack() except: logger.exception('Error')
def test_browser_get(self): import datetime from z3c.saconfig import Session from euphorie.client.model import SurveySession from euphorie.content.tests.utils import BASIC_SURVEY from euphorie.client.tests.utils import addAccount from euphorie.client.tests.utils import addSurvey from euphorie.client.api.authentication import generate_token from tno.euphorie.model import DutchCompany from Products.Five.testbrowser import Browser self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) account = addAccount(password='******') survey_session = SurveySession( title=u'Dummy session', created=datetime.datetime(2012, 4, 22, 23, 5, 12), modified=datetime.datetime(2012, 4, 23, 11, 50, 30), zodb_path='nl/ict/software-development', account=account) survey_session.dutch_company = DutchCompany( title=u'Acme B.V.', employees='40h', email='*****@*****.**', submit_date=datetime.date(2012, 6, 6)) Session.add(survey_session) browser = Browser() browser.addHeader('X-Euphorie-Token', generate_token(account)) browser.handleErrors = False browser.open( 'http://nohost/plone/client/api/users/1/sessions/1/' 'report-actionplan') self.assertEqual(browser.headers['Content-Type'], 'application/rtf') self.assertTrue('Bedrijfsnaam' in browser.contents)
def test_add(self): session = Session() session.add(Organization(name=u"Vin", language="fr")) self.assertEqual(len(session.query(Organization).all()), 1) orga = session.query(Organization).first() self.assertEqual(orga.name, u"Vin")
def saveResult(self, body): from fernlehrgang import models session = Session() data = simplejson.loads(body) teilnehmer_id = data.pop('teilnehmer_id') ktn = session.query(models.Kursteilnehmer).get(data.get('kursteilnehmer_id')) data['datum'] = datetime.now() data['system'] = "Virtuelle Lernwelt" data['gbo'] = "OK" orgas = data.pop('orgas') gbo_daten = self.createGBODaten(ktn, orgas) data['gbo_daten'] = simplejson.dumps(gbo_daten) data['lehrheft_id'] = 1055 data['frage_id'] = 10550 gbo_u = data.pop('gbo_uebermittelung') antwort = models.Antwort(**data) ktn.antworten.append(antwort) je = models.JournalEntry(type="Abschluss Virtuelle Lernwelt", status="info", kursteilnehmer_id=ktn.id) ktn.teilnehmer.journal_entries.append(je) gbo_status="" if gbo_u: from fernlehrgang.api.gbo import GBOAPI gbo_api = GBOAPI() r = gbo_api.set_data(gbo_daten) gbo_status = r.status_code print "TANSERFER DATA TO GBO" result = ICalculateResults(ktn).summary() result['kursteilnehmer_id'] = data.get('kursteilnehmer_id') result['teilnehmer_id'] = teilnehmer_id result['ist_gespeichert'] = True result['an_gbo_uebermittelt'] = gbo_u result['gbo_comment'] = gbo_status print result return result
def test_get_no_company_data_present(self): import datetime import json from z3c.saconfig import Session from euphorie.client.model import SurveySession from euphorie.content.tests.utils import BASIC_SURVEY from euphorie.client.tests.utils import addAccount from euphorie.client.tests.utils import addSurvey from euphorie.client.api.authentication import generate_token from Products.Five.testbrowser import Browser self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) account = addAccount(password='******') survey_session = SurveySession( title=u'Dummy session', created=datetime.datetime(2012, 4, 22, 23, 5, 12), modified=datetime.datetime(2012, 4, 23, 11, 50, 30), zodb_path='nl/ict/software-development', account=account) Session.add(survey_session) browser = Browser() browser.addHeader('X-Euphorie-Token', generate_token(account)) browser.open( 'http://nohost/plone/client/api/users/1/sessions/1/company') self.assertEqual(browser.headers['Content-Type'], 'application/json') response = json.loads(browser.contents) self.assertEqual(response['type'], 'company')
def getGrundDaten(self): if os.environ.get('ADHOC_TEST') == "True": from ukh.adhoc.lib.testdata import gd return gd d1 = select([c1unf1aa, c1prs1aa], and_(c1prs1aa.c.prsoid == c1unf1aa.c.unfprs, c1unf1aa.c.unfaz == self.az)) session = Session() daten1 = session.execute(d1).fetchall() d2 = select([avika1aa], and_(avika1aa.c.ikkl == str(daten1[0]['prsikn'])[0:3], avika1aa.c.ikbs == str(daten1[0]['prsikn'])[3:10])) prsdaten = session.execute(d2).fetchall() datensatz = {} datensatz.update(dict(prsdaten[0])) datensatz.update(dict(daten1[0])) if datensatz['ikanr'] == 1: datensatz['ikanr'] = u'Frau' else: datensatz['ikanr'] = u'Herr' nd = {} for k, v in datensatz.items(): if isinstance(v, basestring): nd[k] = v else: nd[k] = str(v) return datensatz
def handleSubmit(self, action): data, errors = self.extractData() if not errors: session = Session() searched_categories = data.get('categories') search = data.get('search') if search == None: search = u"" request = session.query(Organization) if search: additionalinformations = session.query(AdditionalInformation).filter(func.lower(AdditionalInformation.objectif).like(u'%{0}%'.format(search).lower())).all() request = request.filter(or_ (func.lower(Organization.name).like(u'%{0}%'.format(search).lower()), (Organization.organization_id.in_([addit.organization_id for addit in additionalinformations])))) for categorie in searched_categories: if categorie == 'enseignement_formation': request = request.filter( or_(Organization.category.has(getattr(Category, 'tutoring') == True), Organization.category.has(getattr(Category, 'training') == True), Organization.category.has(getattr(Category, 'education') == True))) else: request = request.filter(Organization.category.has(getattr(Category, categorie) == True)) request = request.filter(Organization.language == self.context.Language()) request = request.order_by(Organization.name) self.searched_categories = searched_categories self.results = request.all() if len(self.results) == 0: self.status = _(u"No organization found.") else: self.request.SESSION.set(SESSION_SEARCH, self.results) self.request.SESSION.set(SESSION_CATEGORIES, self.searched_categories) self.request.response.redirect('organizations_search?search_term={0}'.format(search.encode('utf8')))
def get_results(self): if not 'SESSION' in self.request.keys(): return None if SESSION_JSON in self.request.SESSION.keys(): self.request.SESSION.delete(SESSION_JSON) if len(self.results) == 0: return None session = Session() json_organisations = [] sa_results = [] for orga in self.results: sa_orga = session.query(Organization).get(orga.organization_id) sa_results.append(sa_orga) dict_orga = {} dict_orga['id'] = sa_orga.organization_id dict_orga['name'] = sa_orga.name dict_orga['x'] = sa_orga.x dict_orga['y'] = sa_orga.y dict_orga['street'] = u"{0}, {1}".format(sa_orga.address.num, sa_orga.address.street) dict_orga['city'] = u"{0} {1}".format(sa_orga.address.post_code, sa_orga.address.municipality) dict_orga['url'] = "{0}/org/{1}/oview".format(self.context.absolute_url(), sa_orga.organization_id) dict_orga['icon'] = "{0}/++resource++map_pin.png".format(self.context.portal_url()) json_organisations.append({'orga': dict_orga}) self.request.SESSION.set(SESSION_JSON, json_organisations) self.results = sa_results return sa_results
def getStats(self): """Get statistics for all questions in the lecture""" if IQuestion.providedBy(self.context): # Return just the current question and it's DB object dbQns = (Session.query(db.Question) .filter(db.Question.plonePath == '/'.join(self.context.getPhysicalPath())) .filter(db.Question.active == True) .order_by(db.Question.plonePath)) else: # TODO: Batching, optimise query dbQns = (Session.query(db.Question) .filter(db.Question.lectures.contains(self.getDbLecture())) .filter(db.Question.active == True) .order_by(db.Question.plonePath)) out = [] for dbQn in dbQns: plonePath = str(dbQn.plonePath) queryString = None if '?' in plonePath: (plonePath, queryString) = plonePath.split('?', 1) plQn = self.portalObject().unrestrictedTraverse(plonePath) out.append(dict( url=plQn.absolute_url() + ('?%s' % queryString if queryString else ""), id=plQn.getId() + ('?%s' % queryString if queryString else ""), title=plQn.Title(), timesAnswered=dbQn.timesAnswered, timesCorrect=dbQn.timesCorrect, )) return out
def handle_custom_risks_order(context, event): session = Session() custom_risks = session.query(SurveyTreeItem).filter( and_( SurveyTreeItem.session_id == context.session_id, SurveyTreeItem.path.like(context.path + "%"), SurveyTreeItem.type == "risk", )) # First, set all paths and zodb_paths to bogus values (extra zeros) # to avoid constraint errors for risk in custom_risks: risk.path = risk.path + "000" risk.zodb_path = risk.zodb_path + "000" ordered_custom_risks = (session.query(SurveyTreeItem).filter( and_( SurveyTreeItem.session_id == context.session_id, SurveyTreeItem.path.like(context.path + "%"), SurveyTreeItem.type == "risk", )).order_by( cast(func.split_part(SurveyTreeItem.zodb_path, "/", 2), Integer))) # Iterate over the risks in their natural order. Close any gaps in numbering for count, risk in enumerate(ordered_custom_risks): risk.zodb_path = "custom-risks/{}".format(count + 1) # Now, set the path according to the zodb_path (= natural order) for risk in custom_risks: risk.path = "%s%03d" % (context.path, int( risk.zodb_path.split("/")[-1]))
def createAccount(self, login="******", password=u"jane"): from euphorie.client.model import Account session = Session() account = Account(loginname=login, password=password) session.add(account) session.flush() return account
def enumerateUsers(self, id=None, login=None, exact_match=False, sort_by=None, max_results=None, **kw): """IUserEnumerationPlugin implementation""" if not exact_match: return [] if not IClientSkinLayer.providedBy(self.REQUEST): return [] query = Session().query(model.Account) if id is not None: try: query = query.filter(model.Account.id == int(id)) except ValueError: return [] if login: query = query.filter(model.Account.loginname == login) account = query.first() if account is not None: return [{"id": str(account.id), "login": account.loginname}] return []
def RGStatistik(az, bestaet, unfoid): datum = str(strftime("%d.%m.%Y", localtime())) upd = z1vrs1aa.update().where(and_(z1vrs1aa.c.az == az)).values( bestaet=bestaet, am=datum, unfoid=unfoid) session = Session() session.execute(upd) mark_changed(session)
def test_browser(self): import datetime from z3c.saconfig import Session from euphorie.client.model import SurveySession from euphorie.client.api.authentication import generate_token from euphorie.content.tests.utils import BASIC_SURVEY from euphorie.client.tests.utils import addAccount from euphorie.client.tests.utils import addSurvey self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) account = addAccount(password='******') survey_session = SurveySession( title=u'Dummy session', created=datetime.datetime(2012, 4, 22, 23, 5, 12), modified=datetime.datetime(2012, 4, 23, 11, 50, 30), zodb_path='nl/ict/software-development', account=account) Session.add(survey_session) browser = Browser() browser.addHeader('X-Euphorie-Token', generate_token(account)) browser.handleErrors = False browser.open('http://nohost/plone/client/api/users/1/' 'sessions/1/report-timeline') self.assertEqual( browser.headers['Content-Type'], 'application/vnd.openxmlformats-' 'officedocument.spreadsheetml.sheet')
def login(self, account, remember): # Fetch the account again, to circumvent caching session = Session() account = session.query(Account).filter(Account.id == account.id).one() ls = LoginStatistics(account=account) account.logins.append(ls) return super(Login, self).login(account, remember)
def test_get_no_company_data_present(self): import datetime import json from z3c.saconfig import Session from euphorie.client.model import SurveySession from euphorie.content.tests.utils import BASIC_SURVEY from euphorie.client.tests.utils import addAccount from euphorie.client.tests.utils import addSurvey from euphorie.client.api.authentication import generate_token from Products.Five.testbrowser import Browser self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) account = addAccount(password="******") survey_session = SurveySession( title=u"Dummy session", created=datetime.datetime(2012, 4, 22, 23, 5, 12), modified=datetime.datetime(2012, 4, 23, 11, 50, 30), zodb_path="nl/ict/software-development", account=account, ) Session.add(survey_session) browser = Browser() browser.addHeader("X-Euphorie-Token", generate_token(account)) browser.open("http://nohost/plone/client/api/users/1/sessions/1/company") self.assertEqual(browser.headers["Content-Type"], "application/json") response = json.loads(browser.contents) self.assertEqual(response["type"], "company")
def testChange(self): import datetime from z3c.saconfig import Session from euphorie.client.model import AccountChangeRequest from euphorie.client.model import Account browser = self.browser browser.handleErrors = False browser.open("http://nohost/plone/client/nl/new-email") browser.getControl(name="form.widgets.password").value = "guest" browser.getControl( name="form.widgets.loginname").value = "*****@*****.**" browser.getControl(name="form.buttons.save").click() self.assertEqual( browser.url, "http://nohost/plone/client/nl/account-settings") self.assertTrue("Please confirm your new email" in browser.contents) self.assertTrue("*****@*****.**" in browser.contents) self.assertEqual(Session.query(AccountChangeRequest).count(), 1) user = Session.query(Account).first() self.assertTrue(user.change_request is not None) self.assertEqual(user.change_request.value, "*****@*****.**") self.assertTrue(user.change_request.expires > datetime.datetime.now() + datetime.timedelta(days=6)) self.assertEqual(len(self.email_send), 1) parameters = self.email_send[0] self.assertEqual(parameters[0][1], "*****@*****.**")
def handle_search(self): v = False data, errors = self.extractData() session = Session() sql = session.query(Unternehmen) if data.get('mnr') != NO_VALUE: sql = sql.filter(Unternehmen.mnr == data.get('mnr')) v = True if data.get('mnr_g_alt') != NO_VALUE: sql = sql.filter(Unternehmen.mnr_g_alt == data.get('mnr_g_alt')) v = True if data.get('name') != NO_VALUE: constraint = "%%%s%%" % data.get('name') sql = sql.filter(Unternehmen.name.ilike(constraint)) v = True if data.get('str') != NO_VALUE: constraint = "%%%s%%" % data.get('str') sql = sql.filter(Unternehmen.str.ilike(constraint)) v = True if data.get('plz') != NO_VALUE: sql = sql.filter(Unternehmen.plz == data.get('plz')) v = True if data.get('ort') != NO_VALUE: constraint = "%%%s%%" % data.get('ort') sql = sql.filter(Unternehmen.ort.ilike(constraint)) v = True if not v: self.flash(u'Bitte geben Sie die Suchkriterien ein.') return ### FIXME length between (100000000 and 1000000000) instead of --> sql = sql.filter(func.length(Unternehmen.mnr) == 9) self.results = sql.order_by(Unternehmen.name).all()
def _tryRegistration(self): reply = self.request.form loginname = reply.get("email") if not loginname: self.errors["email"] = _("error_missing_email", default=u"Please enter your email address") elif not EMAIL_RE.match(loginname): self.errors["email"] = _("error_invalid_email", default=u"Please enter a valid email address") if not reply.get("password1"): self.errors["password"] = _("error_missing_password", default=u"Please enter a password") elif reply.get("password1") != reply.get("password2"): self.errors["password"] = _("error_password_mismatch", default=u"Passwords do not match") if self.errors: return False session = Session() loginname = loginname.lower() account = session.query(Account).filter(Account.loginname == loginname).count() if account: self.errors["email"] = _( "error_email_in_use", default=u"An account with this email address already exists." ) return False pm = getToolByName(self.context, "portal_membership") if pm.getMemberById(loginname) is not None: self.errors["email"] = _( "error_email_in_use", default=u"An account with this email address already exists." ) return False account = Account(loginname=loginname, password=reply.get("password1")) Session().add(account) log.info("Registered new account %s", loginname) return account
def render(self): """JSON entry point for session deletion.""" session = Session() ss = session.query(model.SurveySession).get(self.request.form["id"]) if ss is not None: session.delete(ss) return dict(result="ok")
def set(self, value, _sa_initiator=None): key = self.keyfunc(value) if key is None: session = Session() session.flush() key = self.keyfunc(value) self.__setitem__(key, value, _sa_initiator)
def beforeTearDown(self): from euphorie.client import model from euphorie.client import utils from z3c.saconfig import Session Session.remove() model.metadata.drop_all(Session.bind) utils.setRequest(None)
def render(self): dbtable_surveys = 'statistics_surveys' info_surveys = self.getSurveysInfo() # write to db session = Session() session.execute('''DELETE FROM %s;''' % dbtable_surveys) def clean(value): if isinstance(value, basestring): return safe_unicode(value).strip().encode('utf-8') return value def pg_format(value): if value is None: return 'NULL' if isinstance(value, datetime): return "TIMESTAMP '%s'" % value.isoformat() return "'%s'" % value for line in info_surveys: insert = '''INSERT INTO %s VALUES %s;''' % \ (dbtable_surveys, '(%s)' % ', '.join(map(pg_format, map(clean, line)))) session.execute(insert) datamanager.mark_changed(session) transaction.get().commit() from pprint import pformat return "Written:\n" + pformat(info_surveys)
def get_kursteilnehmer(self, ktn_id): session = Session() from fernlehrgang.models import Kursteilnehmer ktn_id, flg_id = ktn_id.split(',') ktn = session.query(Kursteilnehmer).get(ktn_id) print {'status': ktn.status, 'un_klasse': ktn.un_klasse, 'branche': ktn.branche, 'gespraech': ktn.gespraech} return {'status': ktn.status, 'un_klasse': ktn.un_klasse, 'branche': ktn.branche, 'gespraech': ktn.gespraech}
def test_authenticate_login_not_case_sensitive(self): session = Session() account = model.Account(loginname='john', password=u'jane') session.add(account) plugin = EuphorieAccountPlugin('plugin') credentials = {'login': '******', 'password': u'jane'} self.assertTrue(plugin._authenticate_login(credentials) is not None)
def test_sessions_ordering(self): import datetime from euphorie.content.tests.utils import BASIC_SURVEY from z3c.saconfig import Session from AccessControl.SecurityManagement import newSecurityManager from ..model import Account from ..model import SurveySession self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) session = Session() account = Account( loginname='johny', sessions=[ SurveySession(zodb_path='nl/ict/software-development', title=u'One', modified=datetime.datetime(2012, 12, 10)), SurveySession(zodb_path='nl/ict/software-development', title=u'Three', modified=datetime.datetime(2012, 12, 12)), SurveySession(zodb_path='nl/ict/software-development', title=u'Two', modified=datetime.datetime(2012, 12, 11)) ]) session.add(account) newSecurityManager(None, account) view = self.View(self.portal.client['nl'], None) self.assertEqual([s['title'] for s in view.sessions()], [u'Three', u'Two', 'One'])
def test_authenticate_login_not_case_sensitive(self): session = Session() account = model.Account(loginname="john", password="******") session.add(account) plugin = EuphorieAccountPlugin("plugin") credentials = {"login": "******", "password": "******"} self.assertTrue(plugin._authenticate_login(credentials) is not None)
def getStatus(self): # Note: Optional modules with a yes-answer are not distinguishable # from non-optional modules, and ignored. session_id = SessionManager.id query = self.query % dict(sessionid=session_id) session = Session() result = session.execute(query).fetchall() modules = {} base_url = "%s/identification" % self.request.survey.absolute_url() for row in result: module = modules.setdefault(row.module, dict()) if "url" not in module: module["url"] = "%s/%s" % (base_url, int(row.module)) module["path"] = row.module if row.status != "ignore": module["total"] = module.get("total", 0) + row.count module[row.status] = {'count': row.count} titles = dict(session.query(model.Module.path, model.Module.title) .filter(model.Module.session_id == session_id) .filter(model.Module.path.in_(modules.keys()))) for module in modules.values(): module["title"] = titles[module["path"]] for status in ["postponed", "ok", "risk"]: if status in module: module[status]["width"] = int(570 * (float(module[status]["count"]) / module["total"])) self.status = modules.values() self.status.sort(key=lambda m: m["path"])
def transferGuestSession(self): """Transfer session(s) from guest account to an existing user account The guest account is expected to go the login form as an authenticated user. For this reason we can know from the session plugin who he is even if during the request process we are now logged in as a new user. """ plugin = self.context.acl_users.session old_credentials = plugin.authenticateCredentials( plugin.extractCredentials(self.request)) if old_credentials is None: # We came here as anonymous user, no need to proceed return old_authenticated_account_id = old_credentials[0] if (Session.query(model.Account).filter( model.Account.account_type == config.GUEST_ACCOUNT, model.Account.id == old_authenticated_account_id, ).first()) is None: # We check that the previously authenticated user was actually # a guest account that has been converted. # This prevents that a regular logged in user A logs in as B # and then all the sessions are transferred to B return new_account = get_current_account() sessions = Session.query(model.SurveySession).filter( model.SurveySession.account_id == old_authenticated_account_id) for session in sessions: session.account_id = new_account.id
def get_categories_without_other(self): session = Session() cat = session.query(Category).filter(Category.organization_id == self.organization_id).all() if len(cat) != 1: raise IndexError('Only one Category class by organization is possible.') categories = cat[0].get_list() return categories
def fernlehrgang_vocab(context): rc = [SimpleTerm('', '', u'Fernlehrgang auswählen')] session = Session() from fernlehrgang.models import Fernlehrgang sql = session.query(Fernlehrgang) def getKTN(context, flg_id): if IFernlehrgangApp.providedBy(context): return if not hasattr(context, 'kursteilnehmer'): return True for x in context.kursteilnehmer: if flg_id == x.fernlehrgang_id: return x for flg in sql.all(): ktn = getKTN(context, flg.id) if ktn: value = "%s - %s, bereits Registriert" % (flg.titel, flg.jahr) if ktn is True: token = flg.id else: token = "%s,%s" %(ktn.id, flg.id) rc.append(SimpleTerm(token, token, value)) else: value = "%s - %s" % (flg.titel, flg.jahr) rc.append(SimpleTerm(flg.id, flg.id, value)) return SimpleVocabulary(rc)
def test_sessions_ordering(self): import datetime from euphorie.content.tests.utils import BASIC_SURVEY from z3c.saconfig import Session from AccessControl.SecurityManagement import newSecurityManager from ..model import Account from ..model import SurveySession self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) session = Session() account = Account(loginname='johny', sessions=[ SurveySession(zodb_path='nl/ict/software-development', title=u'One', modified=datetime.datetime(2012, 12, 10)), SurveySession(zodb_path='nl/ict/software-development', title=u'Three', modified=datetime.datetime(2012, 12, 12)), SurveySession(zodb_path='nl/ict/software-development', title=u'Two', modified=datetime.datetime(2012, 12, 11))]) session.add(account) newSecurityManager(None, account) view = self.View(self.portal.client['nl'], None) self.assertEqual( [s['title'] for s in view.sessions()], [u'Three', u'Two', 'One'])
def getMNRFromTeilnehmerID(self, teilnehmer_id): #log('getMNRFromTeilnehmerID %s' % teilnehmer_id, 'performance_analyse') session = Session() ret = session.query(Teilnehmer.unternehmen_mnr).filter(Teilnehmer.id==teilnehmer_id) if ret.count() != 1: return False return str(ret.one()[0])
def maybe_create_earned_certificate(self): """Check if certificates are enabled in this country and if the user has earned the certificate for this session. In case the user needs a certificate, it will be created. """ certificate_view = api.content.get_view("certificate", self.traversed_session, self.request) country = certificate_view.country if not getattr(country, "certificates_enabled", False): return session = self.traversed_session.session if session.completion_percentage < country.certificate_completion_threshold: return if (Session.query(Certificate).filter( Certificate.session_id == session.session_id).first()): return Session.add( Certificate( session_id=session.session_id, json=json.dumps({"date": date.today().strftime("%Y-%m-%d")}), ))
def enable_longer_zodb_paths(context): session = Session() session.execute( "ALTER TABLE %s ALTER COLUMN zodb_path TYPE varchar(512);" % model.SurveyTreeItem.__table__.name ) datamanager.mark_changed(session)
def test_get_empty_profile(self): import datetime import json from z3c.saconfig import Session from euphorie.client.model import SurveySession from euphorie.content.tests.utils import PROFILE_SURVEY from euphorie.client.tests.utils import addAccount from euphorie.client.tests.utils import addSurvey from euphorie.client.api.authentication import generate_token self.loginAsPortalOwner() addSurvey(self.portal, PROFILE_SURVEY) account = addAccount(password='******') survey_session = SurveySession( title=u'Dummy session', created=datetime.datetime(2012, 4, 22, 23, 5, 12), modified=datetime.datetime(2012, 4, 23, 11, 50, 30), zodb_path='nl/ict/software-development', account=account) Session.add(survey_session) browser = Browser() browser.addHeader('X-Euphorie-Token', generate_token(account)) browser.open( 'http://nohost/plone/client/api/users/1/sessions/1/profile') self.assertEqual(browser.headers['Content-Type'], 'application/json') response = json.loads(browser.contents) self.assertEqual(set(response), set(['id', 'type', 'title', 'profile'])) self.assertEqual(response['id'], 1) self.assertEqual(response['type'], 'profile') self.assertEqual(response['title'], u'Dummy session') self.assertEqual(response['profile'], [{ 'id': u'1', 'question': u'List all your departments:', 'value': [] }])
def test_not_nullable(self): import mock from z3c.saconfig import Session session = Session() session.execute('CREATE TABLE account (password TEXT)') session.execute = mock.Mock() self.allow_empty_password() self.assertTrue(not session.execute.called)
def getSessionTree(session): """Build and return a list of all survey tree nodes (as :obj:`Node` instances) for the current session.""" sqlsession = Session() query = sqlsession.query(model.SurveyTreeItem)\ .filter(model.SurveyTreeItem.session_id == session.id)\ .order_by(model.SurveyTreeItem.path) return [Node(item) for item in query]
def testActionedNodes(self): self.createData() query = Session().query(model.SurveyTreeItem)\ .filter(model.SurveyTreeItem.session == self.survey_session)\ .order_by(model.SurveyTreeItem.path) nodes = query.all() self.assertEqual(len(utils.get_actioned_nodes(nodes)), 0)
def drop_constraint_no_duplicates_in_tree(context): session = Session() if TableExists(session, "tree"): session.execute("ALTER TABLE tree DROP CONSTRAINT no_duplicates") model.metadata.create_all(session.bind, checkfirst=True) datamanager.mark_changed(session) transaction.get().commit() log.info("Removed the constraint `no_duplicates` from table tree.")
def asDict(self, data): """For all students already in DB, update details""" mtool = getToolByName(self.context, 'portal_membership') for dbStudent in Session.query(db.Student).all(): mb = mtool.getMemberById(dbStudent.userName) dbStudent.eMail = mb.getProperty('email') Session.flush() return dict(success=True)
def test_column_not_present(self): import mock from z3c.saconfig import Session session = Session() session.execute('CREATE TABLE risk (foo INT)') session.execute = mock.Mock() self.add_skip_evaluation_to_model() self.assertTrue(session.execute.called)
def test_not_nullable(self): import mock from z3c.saconfig import Session session = Session() session.execute('CREATE TABLE action_plan (reference TEXT)') session.execute = mock.Mock() self.add_actionplan_reference() self.assertTrue(not session.execute.called)
def increase_sessions_path_column(context): session = Session() if TableExists(session, "session"): session.execute("ALTER TABLE session ALTER COLUMN zodb_path TYPE varchar(512)") model.metadata.create_all(session.bind, checkfirst=True) datamanager.mark_changed(session) transaction.get().commit() log.info("Increased the size of column zodb_path in table session.")
def enable_custom_risks_on_all_modules(context): """ """ if not api.portal.get_registry_record("euphorie.allow_user_defined_risks"): log.warning( "Custom risks are not enabled. Set 'allow_user_defined_risks' to " "true in euphorie.ini for enabling them." ) return portal = api.portal.get() client = portal.client count = 0 for country in client.objectValues(): if IClientCountry.providedBy(country): for sector in country.objectValues(): if IClientSector.providedBy(sector): for survey in sector.objectValues(): try: is_new = EnableCustomRisks(survey) count += 1 custom = getattr(survey, "custom-risks", None) if custom: custom.title = _( "title_other_risks", default="Added risks (by you)", ) custom.description = _( "description_other_risks", default="In case you have identified risks not included in " # noqa: E501 "the tool, you are able to add them now:", ) custom.question = _( "question_other_risks", default="<p>Would you now like to add your own defined risks " # noqa: E501 "to this tool?</p><p><strong>Important:</strong> In " # noqa: E501 "order to avoid duplicating risks, we strongly recommend you " # noqa: E501 "to go first through all the previous modules, if you have not " # noqa: E501 "done it yet.</p><p>If you don't need to add risks, please select 'No.'</p>", # noqa: E501 ) if is_new: survey.published = ( survey.id, survey.title, datetime.datetime.now(), ) except Exception as e: log.error( "Could not enable custom risks for module. %s" % e ) log.info("All %d published surveys can now have custom risks." % count) session = Session() if TableExists(session, "tree"): session.execute( "UPDATE tree SET title = 'title_other_risks' WHERE zodb_path ='custom-risks'" # noqa: E501 ) model.metadata.create_all(session.bind, checkfirst=True) datamanager.mark_changed(session) transaction.get().commit() log.info("Set correct title on all exisiting sessions for custom risks module.")
def test_EnumerateUsers_search_by_id(self): session = Session() account = model.Account(loginname='john', password=u'jane') session.add(account) plugin = EuphorieAccountPlugin('plugin') info = plugin.enumerateUsers(id='1', exact_match=True) self.assertEqual(info, [{'id': '1', 'login': '******'}]) self.assertTrue(isinstance(info[0]['id'], str)) self.assertTrue(isinstance(info[0]['login'], str))
def __getitem__(self, key): token = self.request.getHeader('X-Euphorie-Token') uid_and_login = authenticate_token(token) if uid_and_login is None or key != uid_and_login[0]: raise KeyError(key) account = Session().query(Account).get(int(uid_and_login[0])) account.getId = lambda: key newSecurityManager(None, account) return account.__of__(self)
def testCreateUser_ValidAccount(self): session = Session() account = model.Account(loginname="john", password="******") session.add(account) request = MockRequest(ACTUAL_URL="http://www.example.com/client") directlyProvides(request, IClientSkinLayer) plugin = EuphorieAccountPlugin("plugin") plugin.REQUEST = request self.assertTrue(plugin.createUser("1", "john") is account)