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 __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 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 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), [])
class TreeTests(EuphorieFunctionalTestCase): def createClientSurvey(self): self.loginAsPortalOwner() self.client = self.portal.client self.client.invokeFactory("euphorie.clientcountry", "nl") createContentInContainer(self.client.nl, "euphorie.sector", checkConstraints=False, title="dining") self.sector = self.client.nl.dining createContentInContainer(self.sector, "euphorie.survey", checkConstraints=False, title="Survey") self.survey = self.sector.survey return self.survey def createSurveySession(self): self.sqlsession = Session() account = model.Account(loginname="jane", password="******") self.sqlsession.add(account) self.session = model.SurveySession(title="Session", zodb_path="nl/dining/survey", account=account) self.sqlsession.add(self.session) self.sqlsession.flush() return self.session
def create_session(self): with api.env.adopt_user(SITE_OWNER_NAME): api.content.create(container=self.portal.sectors, type="euphorie.country", id="eu") client_country = api.content.create(container=self.portal.client, type="euphorie.clientcountry", id="eu") client_sector = api.content.create(container=client_country, type="euphorie.clientsector", id="sector") api.content.create(container=client_sector, type="euphorie.survey", id="survey") sqlsession = Session() account = model.Account(loginname="jane", password="******") sqlsession.add(account) session = model.SurveySession(title="Session", zodb_path="eu/sector/survey", account=account) sqlsession.add(session) sqlsession.flush() return session
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 finish(self): self.applySteps(self.context) sqlalsession = Session() sqlalsession.flush() organization = self.session["organization"] canonical_id = self.session["canonical_id"] if organization.organization_id: sqlalsession.merge(organization) else: sqlalsession.add(organization) if canonical_id: # flush required for organization.organization_id creation sqlalsession.flush() assoc = Association(association_type="lang") assoc.translated_id = organization.organization_id assoc.canonical_id = canonical_id sqlalsession.add(assoc) from cirb.organizations.traversal import OrganizationWrapper # transaction.commit() self.request.SESSION.clear() orga_page = "{0}/organizations_manage".format(self.context.absolute_url()) if isinstance(self.context, OrganizationWrapper): orga_page = "{0}/organizations_manage".format(self.context.__parent__.__parent__.absolute_url()) self.request.response.redirect(orga_page)
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 _create_session(self, dbsession=None): if dbsession is None: dbsession = Session() session = SurveySession(account=self.account, zodb_path="survey") dbsession.add(session) dbsession.flush() return session
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 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_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 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 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_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 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 syncPloneQuestions(dbLec, lectureObj): """Ensure database has same questions as Plone""" # Get all plone questions, turn it into a dict by path if getattr(lectureObj, 'isAlias', False): lectureObj = lectureObj._target listing = lectureObj.portal_catalog.unrestrictedSearchResults( path={'query': '/'.join(lectureObj.getPhysicalPath()), 'depth': 1}, object_provides=IQuestion.__identifier__ ) # Sort questions into a dict by path ploneQns = _ploneQuestionDict(listing) # Get all questions currently in the database for dbQn in (Session.query(db.Question).filter(db.Question.lectures.contains(dbLec))): qn = ploneQns.get(dbQn.plonePath, None) if qn is not None: # Question still there (or returned), update dbQn.active = True dbQn.correctChoices = json.dumps(qn['correctChoices']) dbQn.incorrectChoices = json.dumps(qn['incorrectChoices']) dbQn.lastUpdate = qn['lastUpdate'] # Dont add this question later del ploneQns[dbQn.plonePath] elif dbQn.active and not(dbQn.plonePath.startswith(dbLec.plonePath)): # Remove slave symlink question from lecture dbQn.lectures = [l for l in dbQn.lectures if l != dbLec] dbQn.active = len(dbQn.lectures) > 0 dbQn.lastUpdate = datetime.datetime.utcnow() elif dbQn.active: # Remove question from all lectures and mark as inactive dbQn.lectures = [] dbQn.active = False dbQn.lastUpdate = datetime.datetime.utcnow() else: # No question & already removed from DB pass # Insert any remaining questions for (path, qn) in ploneQns.iteritems(): try: # If question already exists, add it to this lecture. dbQn = Session.query(db.Question).filter(db.Question.plonePath == path).one() dbQn.lectures.append(dbLec) dbQn.active = True except NoResultFound: Session.add(db.Question( plonePath=path, qnType=qn['qnType'], lastUpdate=qn['lastUpdate'], correctChoices=json.dumps(qn['correctChoices']), incorrectChoices=json.dumps(qn['incorrectChoices']), timesAnswered=qn['timesAnswered'], timesCorrect=qn['timesCorrect'], lectures=[dbLec], )) dbLec.lastUpdate = datetime.datetime.utcnow() Session.flush() return True
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 create_survey_session(self, title, account=None, **params): """Create a new survey session. :param title: title for the new survey session. :type title: unicode :rtype: :py:class:`cls.survey_session_model` instance """ if account is None: account = get_current_account() session = Session() sector = self.context.aq_parent country = sector.aq_parent zodb_path = "%s/%s/%s" % (country.id, sector.id, self.context.id) survey_session = self.survey_session_model( title=title, zodb_path=zodb_path, account_id=account.id, group_id=account.group_id, ) for key in params: setattr(survey_session, key, params[key]) session.add(survey_session) session.refresh(account) session.flush() # flush so we get a session id return survey_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 _newLink(self, vestigings_sleutel, webservice): session = Session() # Check if there is an account from another regelhulp for the same # vestiging. account = session.query(model.Account)\ .filter(model.Account.loginname == vestigings_sleutel)\ .first() if account is None: # Create a new account account = model.Account( loginname=vestigings_sleutel, password=None) session.add(account) session.flush() # Make sure account.id is set log.info('Created new OD account %s for %s', account.loginname, self.url()) # Login with the account newSecurityManager(None, account) pas = getToolByName(self.context, 'acl_users') pas.updateCredentials(self.request, self.response, account.loginname, None) # And start a new survey survey = aq_inner(self.context) ss = SessionManager.start(title=survey.Title(), survey=survey) Session.add(OdLink( session=ss, vestigings_sleutel=vestigings_sleutel, webservice=webservice)) v_url = urlparse.urlsplit(survey.absolute_url() + '/od-new').path trigger_extra_pageview(self.request, v_url) self.request.response.redirect('%s/start' % survey.absolute_url())
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_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 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 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 test_EnumerateUsers_search_by_login(self): session = Session() account = model.Account(loginname='john', password=u'jane') session.add(account) plugin = EuphorieAccountPlugin('plugin') self.assertEqual( plugin.enumerateUsers(login='******', exact_match=True), [{'id': '1', 'login': '******'}])
def createSurvey(): session = Session() account = model.Account(loginname="jane", password="******") session.add(account) survey = model.SurveySession(title="Session", zodb_path="survey", account=account) session.add(survey) session.flush() return (session, survey)
def addAccount(login="******", password=u"Øle"): from euphorie.client import CONDITIONS_VERSION account = model.Account(loginname=login, password=password, tc_approved=CONDITIONS_VERSION) session = Session() session.add(account) session.flush() return account
def createSurvey(): session = Session() account = model.Account(loginname=u"jane", password=u"secret") session.add(account) survey = model.SurveySession(title=u"Session", zodb_path="survey", account=account) session.add(survey) return (session, survey)
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)
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 test_uppercase_login(self): from z3c.saconfig import Session from euphorie.client.model import Account session = Session() account = Account(loginname='*****@*****.**', password=u'john') session.add(account) self.lowercase_login(None) session.expire(account) self.assertEqual(account.loginname, '*****@*****.**')
def test_not_empty_search(self): session = Session() session.add(Organization(name=u"Vin sur vin", language="fr")) session.flush() browser = Browser(self.app) #testURL = self.folder_fr.absolute_url() testURL = self.portal.absolute_url() browser.open(testURL)
def addAccount(login="******", password=u"Øle"): from euphorie.client import CONDITIONS_VERSION account = model.Account(loginname=login, password=password, tc_approved=CONDITIONS_VERSION) session = Session() session.add(account) session.flush() return account
def test_uppercase_login(self): from z3c.saconfig import Session from euphorie.client.model import Account session = Session() account = Account(loginname='*****@*****.**', password=u'john') session.add(account) self.lowercase_login(None) session.expire(account) self.assertEqual(account.loginname, '*****@*****.**')
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))
class BuildSurveyTreeTests(DatabaseTests): def setUp(self): from z3c.saconfig import Session super(BuildSurveyTreeTests, self).setUp() self.session = Session() account = model.Account(loginname=u"jane", password=u"secret") self.session.add(account) self.survey = model.SurveySession(title=u"Survey", zodb_path="survey", account=account) self.session.add(self.survey) self.session.flush() def test_empty_profile_no_question(self): BuildSurveyTree({}, dbsession=self.survey) self.assertTrue(not self.survey.hasTree()) def test_empty_profile_with_risk(self): BuildSurveyTree({'one': createRisk("13")}, dbsession=self.survey) self.assertTrue(self.survey.hasTree()) children = self.survey.children().all() self.assertEqual(len(children), 1) self.assertEqual(children[0].zodb_path, '13') self.assertEqual(children[0].children().count(), 0) def test_empty_profile_with_container(self): BuildSurveyTree({'one': createContainer("13")}, dbsession=self.survey) self.assertTrue(self.survey.hasTree()) children = self.survey.children().all() self.assertEqual(len(children), 1) self.assertEqual(children[0].zodb_path, '13') self.assertEqual(children[0].children().count(), 0) def test_empty_profile_with_profile_question(self): BuildSurveyTree({'one': createContainer("13", True)}, dbsession=self.survey) self.assertTrue(not self.survey.hasTree()) def test_profile_without_answers(self): BuildSurveyTree({'one': createContainer("13", True)}, profile={"13": []}, dbsession=self.survey) self.assertTrue(not self.survey.hasTree()) def test_profile_with_multiple_answers(self): BuildSurveyTree({'one': createContainer("13", True)}, profile={"13": ["one", "two"]}, dbsession=self.survey) self.assertTrue(self.survey.hasTree()) children = self.survey.children().all() self.assertEqual(len(children), 1) self.assertEqual(children[0].zodb_path, '13') self.assertEqual(children[0].profile_index, -1) grandchildren = children[0].children().all() self.assertEqual(len(grandchildren), 2) self.assertEqual(grandchildren[0].title, 'one') self.assertEqual(grandchildren[0].profile_index, 0) self.assertEqual(grandchildren[1].title, 'two') self.assertEqual(grandchildren[1].profile_index, 1)
def testDuplicateEmail(self): browser = self.browser Session.add(Account(loginname="*****@*****.**", password="******")) commit() browser.open("http://nohost/plone/client/nl/new-email?set_language=en") browser.getControl(name="form.widgets.password").value = "Guest12345#!" browser.getControl(name="form.widgets.loginname").value = "*****@*****.**" browser.getControl(name="form.buttons.save").click() self.assertEqual(browser.url, "http://nohost/plone/client/nl/new-email") self.assertTrue("address is not available" in browser.contents)
def addAccount(login="******", password="******"): account = model.Account( loginname=login, password=password, tc_approved=CONDITIONS_VERSION, ) session = Session() session.add(account) session.flush() return account
def test_EnumerateUsers_search_by_login(self): session = Session() account = model.Account(loginname='john', password=u'jane') session.add(account) plugin = EuphorieAccountPlugin('plugin') self.assertEqual(plugin.enumerateUsers(login='******', exact_match=True), [{ 'id': '1', 'login': '******' }])
def createSurveySession(): sqlsession = Session() account = model.Account(loginname="jane", password="******") sqlsession.add(account) session = model.SurveySession(title="Session", zodb_path="ict/software-development", account=account) sqlsession.add(session) sqlsession.flush() return session
def createSurveySession(): sqlsession = Session() account = model.Account(loginname=u"jane", password=u"secret") sqlsession.add(account) session = model.SurveySession( title=u"Session", zodb_path="ict/software-development", account=account) sqlsession.add(session) sqlsession.flush() return session
def asDict(self, data): """Show coins given to student""" student = self.getCurrentStudent() # Add any additional subscriptions for lec in toArray(data.get('add_lec', [])): ploneLec = self.portalObject().restrictedTraverse(self.lectureUrlToPlonePath(lec)) ploneTutPath = '/'.join(ploneLec.aq_parent.getPhysicalPath()) try: dbSub = (Session.query(db.Subscription) .filter_by(student=student) .filter_by(plonePath=ploneTutPath) .one()) # Already there, so make sure it's available dbSub.hidden = False except NoResultFound: Session.add(db.Subscription( student=student, plonePath=ploneTutPath, )) Session.flush() # Fish out all subscribed tutorials/classes, organised by tutorial del_lec = toArray(data.get('del_lec', [])) subs = dict(children=[]) for dbSub in Session.query(db.Subscription).filter_by(student=student).filter_by(hidden=False).order_by(db.Subscription.plonePath): try: obj = self.portalObject().restrictedTraverse(str(dbSub.plonePath)) except KeyError: # Subscription item vanished, hide it and move on dbSub.hidden = True Session.flush() continue if obj.portal_type == 'tw_tutorial': lectures = (l.getObject() for l in obj.restrictedTraverse('@@folderListing')(portal_type='tw_lecture')) elif obj.portal_type == 'tw_class': lectures = (l.to_object for l in obj.lectures) else: raise ValueError("Unknown portal type!") lectures = [dict( uri=self.lectureObjToUrl(l), title=l.Title(), ) for l in lectures] if next((l for l in lectures if l['uri'] in del_lec), False): dbSub.hidden = True Session.flush() else: subs['children'].append(dict( title=obj.Title(), children=lectures, )) return subs
def test_authentication_success(self): import json from z3c.saconfig import Session from euphorie.client.model import Account Session.add(Account(loginname='john', password=u'jane')) browser = Browser() browser.handleErrors = False browser.post('http://nohost/plone/client/api/users/authenticate', '{"login": "******", "password": "******"}') response = json.loads(browser.contents) self.assertEqual(response['type'], 'user')
def test_authentication_success(self): import json from z3c.saconfig import Session from euphorie.client.model import Account Session.add(Account(loginname='john', password=u'jane')) browser = Browser() browser.handleErrors = False browser.post('http://nohost/plone/client/api/users/authenticate', '{"login": "******", "password": "******"}') response = json.loads(browser.contents) self.assertEqual(response['type'], 'user')
def setupSession(self): od_link = self.session.od_link super(OdProfile, self).setupSession() if od_link is not None: s = Session() if od_link.session in s.deleted: s.expunge(od_link) new_link = OdLink( session=self.session, vestigings_sleutel=od_link.vestigings_sleutel, webservice=od_link.webservice) s.add(new_link)
def test_EnumerateUsers_search_by_login_and_id(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.assertEqual( plugin.enumerateUsers(id="1", login="******", exact_match=True), [{"id": "1", "login": "******"}], )
def maybe_update(self): if self.request.method != "POST": return if not self.webhelpers.show_certificate_status_box(): # Already added return Session.add( model.UsersNotInterestedInCertificateStatusBox( account_id=self.webhelpers.get_current_account().id ) )
def testValidKey(self): account = Account(loginname="login", password="******") account.change_request = AccountChangeRequest( id="X" * 16, value="new-login", expires=datetime.datetime.now() + datetime.timedelta(1), ) Session.add(account) Session.flush() browser = self.get_browser() browser.open("http://nohost/plone/client/confirm-change?key=XXXXXXXXXXXXXXXX") self.assertEqual(browser.url, "http://nohost/plone/client/") self.assertEqual(Session.query(Account.loginname).first()[0], "new-login")
def updateAnswers(self, input, keuzemap, survey, session): idmap = self.buildExternalIdMap(survey) query = Session.query(model.Risk)\ .filter(model.Risk.session_id == session.id) identification_map = {"1": "yes", "2": "no", "3": "n/a"} priority_map = {"laag": "low", "midden": "medium", "hoog": "high"} for antwoord in input.antwoorden.antwoord: risk_id = idmap.get(antwoord.attrib["risk-id"]) if risk_id is None: continue risk = query\ .filter(model.Risk.zodb_path == risk_id)\ .filter(model.Risk.profile_index == keuzemap.get(antwoord.attrib["keuze"], 0))\ .first() if risk is None: continue risk.identification = identification_map.get(antwoord.attrib["inventariseren"]) if antwoord.attrib["inventariseren"] == "-1": risk.postponed = True elif risk.identification is not None: risk.postponed = False risk.probability = attr_int(antwoord, "evalueren1") risk.frequency = attr_int(antwoord, "evalueren2") risk.effect = attr_int(antwoord, "evalueren3") risk.priority = priority_map.get(antwoord.attrib["prioriteit"]) if hasattr(antwoord, "opmerking"): risk.comment = el_unicode(antwoord, "opmerking") for pva in antwoord.iterchildren("pva"): plan = model.ActionPlan(risk=risk) plan.action_plan = el_unicode(pva, "maatregel") plan.prevention_plan = el_unicode(pva, "preventietaken") plan.requirements = el_unicode(pva, "preventiekennis") plan.responsible = el_unicode(pva, "uitvoerder") try: plan.budget = int(pva.budget.text) except (TypeError, ValueError): pass timeline = pva.planning.text.split() plan.planning_start = parse_date(timeline[0]) plan.planning_end = parse_date(timeline[2]) Session.add(plan) session.touch()
def testDuplicateEmail(self): from z3c.saconfig import Session from euphorie.client.model import Account browser = self.browser Session.add(Account(loginname="*****@*****.**", password="******")) 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/new-email") self.assertTrue("address is not available" in browser.contents)
def updateHost(fqdn, hostKey): """Insert/update a host entry""" try: dbHost = (Session.query(db.Host).filter(db.Host.fqdn == fqdn).one()) dbHost.hostKey = hostKey except NoResultFound: dbHost = db.Host(fqdn=fqdn, hostKey=hostKey) Session.add(dbHost) Session.flush() return dict( fqdn=dbHost.fqdn, hostKey=str(dbHost.hostKey), )
class find_sql_context_tests(DatabaseTests): def find_sql_context(self, *a, **kw): from euphorie.client.survey import find_sql_context return find_sql_context(*a, **kw) def createSqlData(self): from z3c.saconfig import Session self.session = Session() account = model.Account(loginname=u'jane', password=u'secret') self.session.add(account) self.survey = model.SurveySession(title=u'Survey', zodb_path='survey', account=account) self.session.add(self.survey) self.session.flush() self.mod1 = self.survey.addChild(model.Module( title=u'module 1', module_id='1', zodb_path='a')) self.q1 = self.mod1.addChild(model.Risk( title=u'question 1', risk_id='1', zodb_path='a/b')) self.session.flush() def test_unknown_path(self): self.createSqlData() zodb_path = ['not', 'found'] result = self.find_sql_context(self.survey.id, zodb_path) self.failUnless(result is None) self.assertEqual(zodb_path, ['not', 'found']) def test_one_step_path(self): self.createSqlData() zodb_path = ['1'] result = self.find_sql_context(self.survey.id, zodb_path) self.assertEqual(result, self.mod1.id) self.assertEqual(zodb_path, []) def test_two_step_path(self): self.createSqlData() zodb_path = ['1', '1'] result = self.find_sql_context(self.survey.id, zodb_path) self.assertEqual(result, self.q1.id) self.assertEqual(zodb_path, []) def test_keep_non_numeric_elements(self): self.createSqlData() zodb_path = ['oops', '1'] result = self.find_sql_context(self.survey.id, zodb_path) self.assertEqual(result, self.mod1.id) self.assertEqual(zodb_path, ["oops"]) def test_keep_sessions_apart(self): self.createSqlData() account = model.Account(loginname=u'john', password=u'jane') self.session.add(account) survey2 = model.SurveySession(title=u'Survey', zodb_path='survey', account=account) self.session.add(survey2) self.session.flush() zodb_path = ['1'] result = self.find_sql_context(survey2.id, zodb_path) self.failUnless(result is None)
def addTranslation(self, language): organization = Organization(address=Address(), category=Category(), person_incharge=InCharge(), person_contact=Contact(), additionalinfo=AdditionalInformation()) organization.person_contact.address = Address() organization.name = self._organization.name organization.language = language session = Session() session.add(organization) session.flush() canonical_id = self.getId() assoc = Association(association_type="lang") assoc.translated_id = organization.organization_id assoc.canonical_id = canonical_id session.add(assoc) session.flush()
def testValidKey(self): import datetime from z3c.saconfig import Session from euphorie.client.model import AccountChangeRequest from euphorie.client.model import Account account = Account(loginname="login", password="******") account.change_request = AccountChangeRequest(id="X" * 16, value="new-login", expires=datetime.datetime.now() + datetime.timedelta(1)) Session.add(account) Session.flush browser = self.browser browser.open( "http://nohost/plone/client/confirm-change?key=XXXXXXXXXXXXXXXX") self.assertEqual(browser.url, "http://nohost/plone/client") self.assertEqual( Session.query(Account.loginname).first()[0], "new-login")