예제 #1
0
def test_find_by_content_signed(app, temporary_path):
    ensure_correct_depot(app)

    tape = module_path('onegov.file', 'tests/cassettes/ais-success.json')
    path = module_path('onegov.file', 'tests/fixtures/sample.pdf')

    with vcr.use_cassette(tape, record_mode='none'):
        transaction.begin()

        with open(path, 'rb') as f:
            app.session().add(File(name='sample.pdf', reference=f))

        transaction.commit()

        pdf = app.session().query(File).one()
        token = 'ccccccbcgujhingjrdejhgfnuetrgigvejhhgbkugded'

        with patch.object(Yubico, 'verify') as verify:
            verify.return_value = True
            app.sign_file(file=pdf, signee='*****@*****.**', token=token)

        transaction.commit()

    # after signing we can still lookup the file using the old content
    files = FileCollection(app.session())

    with open(path, 'rb') as f:
        assert files.by_content(f).count() == 1

    # and of course by using the content of the signed file
    pdf = app.session().query(File).one()
    assert files.by_content(pdf.reference.file.read()).count() == 1
예제 #2
0
def add_donation_page(context):

    org = context.session.query(Organisation).first()

    if org is None:
        return

    # not a feriennet
    if '<registration />' not in org.meta['homepage_structure']:
        return

    if org.locales == 'fr_CH':
        path = module_path('onegov.feriennet', 'content/fr.yaml')
    else:
        path = module_path('onegov.feriennet', 'content/de.yaml')

    page = next(p for p in load_content(path)['pages']
                if p['title'] in ('Spende', 'Dons'))

    pages = PageCollection(context.session)
    order = max(p.order for p in pages.roots) + 1

    meta = page.get('meta', {})
    meta['is_hidden_from_public'] = True

    pages.add(parent=None,
              title=page['title'],
              type=page['type'],
              name=page.get('name', None),
              meta=meta,
              content=page.get('content', None),
              order=order)
예제 #3
0
def get_i18n_localedirs():
    return [
        utils.module_path('onegov.onboarding', 'locale'),
        utils.module_path('onegov.town', 'locale'),
        utils.module_path('onegov.org', 'locale'),
        utils.module_path('onegov.form', 'locale'),
        utils.module_path('onegov.user', 'locale')
    ]
예제 #4
0
def app(request, postgres_dsn, temporary_path, redis_url):

    with (temporary_path / 'bust').open('w') as f:
        f.write('\n'.join((
            f'#!/bin/bash',
            f'touch {temporary_path}/$1'
        )))

    signing_services = (temporary_path / 'signing-services')
    signing_services.mkdir()

    cert_file = module_path('onegov.file', 'tests/fixtures/test.crt')
    cert_key = module_path('onegov.file', 'tests/fixtures/test.crt')

    with (signing_services / '__default__.yml').open('w') as f:
        f.write(textwrap.dedent(f"""
            name: swisscom_ais
            parameters:
                customer: foo
                key_static: bar
                cert_file: {cert_file}
                cert_key: {cert_key}
        """))

    os.chmod(temporary_path / 'bust', 0o775)

    backend = request.param

    class App(Framework, DepotApp):
        anonymous_access = False

    @App.permission_rule(model=object, permission=object, identity=None)
    def test_has_permission_not_logged_in(app, identity, model, permission):
        if app.anonymous_access:
            return True

        return has_permission_not_logged_in(app, identity, model, permission)

    scan_morepath_modules(App)
    morepath.commit(App)

    app = App()
    app.configure_application(
        dsn=postgres_dsn,
        depot_backend=backend,
        depot_storage_path=str(temporary_path),
        frontend_cache_buster=f'{temporary_path}/bust',
        redis_url=redis_url,
        signing_services=str(signing_services),
        yubikey_client_id='foo',
        yubikey_secret_key='dGhlIHdvcmxkIGlzIGNvbnRyb2xsZWQgYnkgbGl6YXJkcyE='
    )

    app.namespace = 'apps'
    app.set_application_id('apps/my-app')

    return app
예제 #5
0
def test_ais_error(app):
    ensure_correct_depot(app)

    path = module_path('onegov.file', 'tests/fixtures/example.pdf')
    tape = module_path('onegov.file', 'tests/cassettes/ais-error.json')

    # recordings were shamelessly copied from AIS.py's unit tests
    with vcr.use_cassette(tape, record_mode='none'):
        with open(path, 'rb') as infile:
            with pytest.raises(AIS.exceptions.AuthenticationFailed):
                outfile = BytesIO()
                app.signing_service.sign(infile, outfile)
예제 #6
0
def test_sign_file(app):
    tape = module_path('onegov.file', 'tests/cassettes/ais-success.json')

    with vcr.use_cassette(tape, record_mode='none'):
        ensure_correct_depot(app)

        transaction.begin()

        path = module_path('onegov.file', 'tests/fixtures/sample.pdf')

        with open(path, 'rb') as f:
            app.session().add(File(name='sample.pdf', reference=f))

        with open(path, 'rb') as f:
            old_digest = hashlib.sha256(f.read()).hexdigest()

        transaction.commit()
        pdf = app.session().query(File).one()

        token = 'ccccccbcgujhingjrdejhgfnuetrgigvejhhgbkugded'

        with patch.object(Yubico, 'verify') as verify:
            verify.return_value = True

            app.sign_file(file=pdf, signee='*****@*****.**', token=token)

            transaction.commit()
            pdf = app.session().query(File).one()

            assert pdf.signed
            assert pdf.reference['content_type'] == 'application/pdf'
            assert pdf.signature_metadata['signee'] == '*****@*****.**'
            assert pdf.signature_metadata['old_digest'] == old_digest
            assert pdf.signature_metadata['new_digest']
            assert pdf.signature_metadata['token'] == token
            assert pdf.signature_metadata['token_type'] == 'yubikey'
            assert pdf.signature_metadata['request_id']\
                .startswith('swisscom_ais/foo/')

            assert len(pdf.reference.file.read()) > 0

            timestamp = isodate.parse_datetime(
                pdf.signature_metadata['timestamp'])

            now = sedate.utcnow()
            assert (now - timedelta(seconds=10)) <= timestamp <= now

            with pytest.raises(RuntimeError) as e:
                app.sign_file(pdf, signee='*****@*****.**', token=token)

            assert "already been signed" in str(e)
예제 #7
0
def test_signature_file_messages(app):
    tape = module_path('onegov.file', 'tests/cassettes/ais-success.json')

    with vcr.use_cassette(tape, record_mode='none'):
        ensure_correct_depot(app)

        # sign the file
        transaction.begin()
        path = module_path('onegov.file', 'tests/fixtures/sample.pdf')
        with open(path, 'rb') as f:
            app.session().add(File(name='sample.pdf', reference=f))
        transaction.commit()

        pdf = app.session().query(File).one()
        token = 'ccccccbcgujhingjrdejhgfnuetrgigvejhhgbkugded'

        with patch.object(Yubico, 'verify') as verify:
            verify.return_value = True
            app.sign_file(file=pdf, signee='*****@*****.**', token=token)
            transaction.commit()

            # ensure that this was logged
            pdf = app.session().query(File).one()
            messages = tuple(app.session().query(FileMessage))
            assert len(messages) == 1
            assert messages[0].channel_id == pdf.id
            assert messages[0].owner == '*****@*****.**'
            assert messages[0].meta['name'] == 'sample.pdf'
            assert messages[0].meta['action'] == 'signature'
            assert messages[0].meta['action_metadata']\
                == pdf.signature_metadata

        # ensure that deleting a signed file is logged as well
        session = app.session()
        pdf = session.query(File).one()
        delete_file(self=pdf, request=Bunch(
            session=session,
            current_username='******',
            assert_valid_csrf_token=lambda: True
        ))

        messages = tuple(app.session().query(FileMessage))
        assert len(messages) == 2
        assert messages[1].channel_id == pdf.id
        assert messages[1].owner == 'foo'
        assert messages[1].meta['name'] == 'sample.pdf'
        assert messages[1].meta['action'] == 'signed-file-removal'
        assert not messages[1].meta['action_metadata']
예제 #8
0
def test_signature_timestamp(session):
    path = module_path('onegov.file', 'tests/fixtures/sample.pdf')
    time = sedate.utcnow()

    with open(path, 'rb') as f:
        session.add(File(name='sample.pdf', reference=f, signature_metadata={
            'timestamp': time.isoformat()
        }))

    transaction.commit()

    # if unsinged, the timestamp is ignored
    assert session.query(File).one().signature_timestamp is None
    assert session.query(File).with_entities(File.signature_timestamp).one()\
        .signature_timestamp is None

    # if signed the timestamp is in UTC (not timezone-aware)
    session.query(File).one().signed = True
    transaction.commit()

    assert session.query(File).one().signature_timestamp == time
    assert session.query(File).with_entities(File.signature_timestamp).one()\
        .signature_timestamp == time

    # make sure we can filter by time
    assert session.query(File).filter_by(signature_timestamp=time).first()

    # make sure we get utc for both
    assert session.query(File).one()\
        .signature_timestamp.tzinfo.zone == 'UTC'
    assert session.query(File).with_entities(File.signature_timestamp).one()\
        .signature_timestamp.tzinfo.zone == 'UTC'
예제 #9
0
def test_sitecollection(town_app):

    sitecollection = SiteCollection(town_app.session())
    objects = sitecollection.get()

    assert {o.name for o in objects['topics']} == {
        'leben-wohnen',
        'kultur-freizeit',
        'bildung-gesellschaft',
        'gewerbe-tourismus',
        'politik-verwaltung'
    }

    assert {o.name for o in objects['news']} == {
        'aktuelles'
    }

    paths = (p for p in os.listdir(module_path('onegov.town', 'forms')))
    paths = (p for p in paths if p.endswith('.form'))
    paths = (os.path.basename(p) for p in paths)
    builtin_forms = set(rchop(p, '.form') for p in paths)

    assert {o.name for o in objects['forms']} == set(builtin_forms)

    assert {o.name for o in objects['resources']} == {'sbb-tageskarte'}
예제 #10
0
def test_initial_content(town_app):
    pages = PageCollection(town_app.session()).query().all()
    pages = {p.name: p.title for p in pages}

    assert pages == {
        'leben-wohnen': 'Leben & Wohnen',
        'kultur-freizeit': 'Kultur & Freizeit',
        'bildung-gesellschaft': 'Bildung & Gesellschaft',
        'gewerbe-tourismus': 'Gewerbe & Tourismus',
        'politik-verwaltung': 'Politik & Verwaltung',
        'aktuelles': 'Aktuelles'
    }

    forms = FormCollection(town_app.session()).definitions.query().all()
    forms = set(form.name for form in forms)

    paths = (p for p in os.listdir(module_path('onegov.town', 'forms')))
    paths = (p for p in paths if p.endswith('.form'))
    paths = (os.path.basename(p) for p in paths)
    builtin_forms = set(rchop(p, '.form') for p in paths)

    assert builtin_forms == forms

    resources = ResourceCollection(town_app.libres_context).query().all()
    resources = {r.name: r.type for r in resources}

    assert resources == {
        'sbb-tageskarte': 'daypass'
    }

    assert EventCollection(town_app.session()).query().count() == 4
    assert OccurrenceCollection(town_app.session()).query().count() > 4
예제 #11
0
def test_sign_transaction(app, temporary_path):
    tape = module_path('onegov.file', 'tests/cassettes/ais-success.json')

    with vcr.use_cassette(tape, record_mode='none'):
        ensure_correct_depot(app)
        transaction.begin()

        path = module_path('onegov.file', 'tests/fixtures/sample.pdf')

        with open(path, 'rb') as f:
            app.session().add(File(name='sample.pdf', reference=f))

        with open(path, 'rb') as f:
            old_digest = hashlib.sha256(f.read()).hexdigest()

        transaction.commit()

        pdf = app.session().query(File).one()

        token = 'ccccccbcgujhingjrdejhgfnuetrgigvejhhgbkugded'

        with patch.object(Yubico, 'verify') as verify:
            verify.return_value = True
            app.sign_file(file=pdf, signee='*****@*****.**', token=token)
            transaction.abort()
            transaction.begin()

    # we have to put in the cassette again, to 'rewind' it
    with vcr.use_cassette(tape, record_mode='none'):

        # ensure that aborting a transaction doesn't result in a changed file
        pdf = app.session().query(File).one()
        assert not pdf.signed
        assert hashlib.sha256(pdf.reference.file.read()).hexdigest()\
            == old_digest

        # only after a proper commit should this work
        with patch.object(Yubico, 'verify') as verify:
            verify.return_value = True
            app.sign_file(file=pdf, signee='*****@*****.**', token=token)
            transaction.commit()

        pdf = app.session().query(File).one()
        assert pdf.signed
        assert hashlib.sha256(pdf.reference.file.read()).hexdigest()\
            != old_digest
예제 #12
0
 def __init__(self, *args, **kwargs):
     filename = path.join(
         module_path('onegov.agency', 'static/logos'),
         'canton-ar.svg'
     )
     with open(filename) as file:
         logo = file.read()
     kwargs['logo'] = logo
     kwargs['author'] = "Kanton Appenzell Ausserrhoden"
     super(AgencyPdfDefault, self).__init__(*args, **kwargs)
예제 #13
0
def test_save_png_zipbomb(session):
    path = module_path('onegov.file', 'tests/fixtures/bomb.png')

    with open(path, 'rb') as f:
        session.add(File(name='zipbomb.png', reference=f))

    transaction.commit()
    file = session.query(File).one()
    assert file.reference.file.read() == b''
    assert file.reference.content_type == 'application/malicious'
예제 #14
0
    def is_year_available(self, year, map_required=True):
        if self.entities and year not in self.entities:
            return False

        if map_required:
            path = utils.module_path(onegov.election_day, 'static/mapdata')
            return Path(
                '{}/{}/{}.json'.format(path, year, self.id)
            ).exists()

        return True
예제 #15
0
def test_pdf_text_extraction(session):
    path = module_path('onegov.file', 'tests/fixtures/sample.pdf')

    with open(path, 'rb') as f:
        session.add(File(name='sample.pdf', reference=f))

    transaction.commit()

    pdf = session.query(File).one()
    assert 'Adobe® Portable Document Format (PDF)' in pdf.extract
    assert pdf.stats['pages'] == 1
    assert pdf.stats['words'] > 20
예제 #16
0
def builtin_form_definitions(path=None):
    """ Yields the name, title and the form definition of all form definitions
    in the given or the default path.

    """
    path = path or module_path('onegov.town', 'forms')

    for filename in os.listdir(path):
        if filename.endswith('.form'):
            name = filename.replace('.form', '')
            title, definition = load_definition(os.path.join(path, filename))
            yield name, title, definition
예제 #17
0
def create_new_organisation(app, name, locale='de_CH'):
    assert locale == 'de_CH'

    path = module_path('onegov.winterthur', 'content/de.yaml')
    content = load_content(path)

    org = Organisation(name=name, **content['organisation'])
    org.meta['locales'] = locale

    session = app.session()
    session.add(org)

    add_pages(session, path)

    return org
예제 #18
0
def test_ais_success(app):
    ensure_correct_depot(app)

    path = module_path('onegov.file', 'tests/fixtures/example.pdf')
    tape = module_path('onegov.file', 'tests/cassettes/ais-success.json')

    # recordings were shamelessly copied from AIS.py's unit tests
    with vcr.use_cassette(tape, record_mode='none'):
        with open(path, 'rb') as infile:
            assert b'/SigFlags' not in infile.read()
            infile.seek(0)

            outfile = BytesIO()
            request_id = app.signing_service.sign(infile, outfile)

            name, customer, id = request_id.split('/')
            assert name == 'swisscom_ais'
            assert customer == 'foo'
            assert is_uuid(id)

            outfile.seek(0)
            assert b'/SigFlags' in outfile.read()

        outfile.seek(0)
예제 #19
0
    def __init__(self, municipality=None, **kwargs):
        assert municipality
        domains = OrderedDict((
            ('federation', _("Federal")),
            ('canton', _("Cantonal")),
            ('municipality', _("Communal"))
        ))

        # Try to read the quarters for each year from our static data
        entities = {}
        path = utils.module_path(onegov.election_day, 'static/quarters')
        paths = (p for p in Path(path).iterdir() if p.is_dir())
        for path in paths:
            year = int(path.name)
            path = path / '{}.json'.format(municipality)
            if path.exists():
                with (path).open('r') as f:
                    entities[year] = {
                        int(k): v for k, v in json.load(f).items()
                    }
        if entities:
            self.has_quarters = True
            # Test if all entities have districts (use none, if ambiguous)
            districts = set([
                entity.get('district', None)
                for year in entities.values()
                for entity in year.values()
            ])
            has_districts = None not in districts
        else:
            # ... we have no static data, autogenerate it!
            self.has_quarters = False
            has_districts = False
            entities = {
                year: {int(municipality): {'name': kwargs.get('name', '')}}
                for year in range(2002, date.today().year + 1)
            }

        super(Municipality, self).__init__(
            id_=municipality,
            domain='municipality',
            domains_election=domains,
            domains_vote=domains,
            entities=entities,
            has_districts=has_districts,
            **kwargs
        )
예제 #20
0
def test_pdf_preview_creation(session):
    path = module_path('onegov.file', 'tests/fixtures/example.pdf')

    with open(path, 'rb') as f:
        session.add(File(name='example.pdf', reference=f))

    transaction.commit()

    pdf = session.query(File).one()
    pdf.reference['thumbnail_medium']

    # our example file contains a blue backgorund so we can verify that
    # the thumbnail for the pdf is generated correctly

    thumb = DepotManager.get().get(pdf.reference['thumbnail_medium']['id'])
    image = Image.open(thumb)

    assert (0, 91, 161, 255) in set(image.getdata())
    assert image.size == (395, 512)
예제 #21
0
def related_attendees(session, occasion_ids):
    stmt = as_selectable_from_path(
        module_path('onegov.feriennet', 'queries/related_attendees.sql'))

    related = session.execute(
        select(stmt.c).where(
            and_(
                stmt.c.occasion_id.in_(occasion_ids),
                stmt.c.booking_state == 'accepted'
            )
        )
    )

    result = defaultdict(list)

    for r in related:
        result[r.occasion_id].append(r)

    return result
예제 #22
0
    def __init__(self, canton=None, **kwargs):
        assert canton in self.CANTONS

        kwargs.pop('use_maps', None)

        domains_election = OrderedDict((
            ('federation', _("Federal")),
            ('region', _("Regional")),
            ('canton', _("Cantonal"))
        ))
        domains_vote = OrderedDict((
            ('federation', _("Federal")),
            ('canton', _("Cantonal"))
        ))

        # Read the municipalties for each year from our static data
        entities = {}
        path = utils.module_path(onegov.election_day, 'static/municipalities')
        paths = (p for p in Path(path).iterdir() if p.is_dir())
        for path in paths:
            year = int(path.name)
            with (path / '{}.json'.format(canton)).open('r') as f:
                entities[year] = {int(k): v for k, v in json.load(f).items()}

        # Test if all entities have districts (use none, if ambiguous)
        districts = set([
            entity.get('district', None)
            for year in entities.values()
            for entity in year.values()
        ])
        has_districts = None not in districts

        super(Canton, self).__init__(
            id_=canton,
            domain='canton',
            domains_election=domains_election,
            domains_vote=domains_vote,
            entities=entities,
            has_districts=has_districts,
            use_maps=True,
            **kwargs
        )
예제 #23
0
def add_builtin_forms(session):
    forms = FormCollection(session).definitions
    builtin_forms = module_path('onegov.town', 'forms')

    def load_definition(filename):
        path = os.path.join(builtin_forms, filename)
        with codecs.open(path, 'r', encoding='utf-8') as formfile:
            formlines = formfile.readlines()

            title = formlines[0].strip()
            definition = u''.join(formlines[3:])

            return title, definition

    def ensure_form(name, title, definition):
        form = forms.by_name(name)

        if form:
            form.title = title
            form.definition = definition
        else:
            form = forms.add(
                name=name,
                title=title,
                definition=definition,
                type='builtin'
            )

        assert form.form_class().match_fields(
            include_classes=(EmailField, ),
            required=True,
            limit=1
        ), "Each form must have at least one required email field"

    for filename in os.listdir(builtin_forms):
        if filename.endswith('.form'):
            name = filename.replace('.form', '')
            title, definition = load_definition(filename)

            ensure_form(name, title, definition)
    def occasion_choices(self):
        if not self.request.app.active_period:
            return

        layout = DefaultLayout(self.model, self.request)

        stmt = as_selectable_from_path(
            module_path('onegov.feriennet', 'queries/occasion_choices.sql'))

        query = select(stmt.c).where(
            stmt.c.period_id == self.request.app.active_period.id)

        templates = {
            True:
            _("${title} (cancelled) "
              "<small>${dates}, ${count} Attendees</small>"),
            False:
            _("${title} "
              "<small>${dates}, ${count} Attendees</small>")
        }

        for record in self.request.session.execute(query):
            template = templates[record.cancelled]
            label = self.request.translate(
                _(template,
                  mapping={
                      'title':
                      record.title,
                      'count':
                      record.count,
                      'dates':
                      ', '.join(
                          layout.format_datetime_range(*d)
                          for d in record.dates)
                  }))

            yield record.occasion_id.hex, label
예제 #25
0
def get_shared_assets_path():
    return utils.module_path('onegov.shared', 'assets/js')
예제 #26
0
from click.testing import CliRunner
from onegov.agency.cli import cli
from onegov.core.utils import module_path
from onegov.org.cli import cli as org_cli
from onegov.org.models import Organisation
from onegov.people.models import Agency
from onegov.people.models import Person
from pathlib import Path
from pytest import mark
from textwrap import dedent
from textwrap import indent
from unittest.mock import patch


@mark.parametrize("file", [
    module_path('onegov.agency', 'tests/fixtures/export.xls'),
])
def test_import_agencies(cfg_path, session_manager, file):
    runner = CliRunner()

    result = runner.invoke(
        org_cli,
        ['--config', cfg_path, '--select', '/agency/zug', 'add', 'Kanton Zug'])
    assert result.exit_code == 0

    expected = dedent("""
        Bundesbehörden
          Nationalrat
          * Mitglied von Zug: Aeschi Thomas
          * Mitglied von Zug: Pezzatti Bruno
          * Mitglied von Zug: Pfister Gerhard
예제 #27
0
파일: app.py 프로젝트: i18nHub/onegov.town
def get_i18n_localedirs():
    return [
        utils.module_path('onegov.town', 'locale'),
        utils.module_path('onegov.form', 'locale'),
        utils.module_path('onegov.user', 'locale')
    ]
예제 #28
0
 def extra_search_paths(self):
     return [module_path('onegov.gazette.theme', 'styles')]
예제 #29
0
def get_i18n_localedirs():
    mine = utils.module_path('onegov.winterthur', 'locale')
    return [mine] + get_org_i18n_localedirs()
예제 #30
0
def get_i18n_localedirs():
    mine = utils.module_path('onegov.agency', 'locale')
    return [mine] + get_org_i18n_localedirs()
예제 #31
0
def get_i18n_localedirs():
    return [
        utils.module_path('onegov.swissvotes', 'locale'),
        utils.module_path('onegov.form', 'locale'),
        utils.module_path('onegov.user', 'locale')
    ]
예제 #32
0
from io import BytesIO
from onegov.core.utils import module_path
from onegov.swissvotes.models import ColumnMapper
from onegov.swissvotes.models import SwissVote
from pytest import mark
from webtest import TestApp as Client
from webtest.forms import Upload
from xlrd import open_workbook
from xlsxwriter.workbook import Workbook


@mark.parametrize("file", [
    module_path('onegov.swissvotes', 'tests/fixtures/votes.xlsx'),
])
def test_update_votes(swissvotes_app, file):
    client = Client(swissvotes_app)
    client.get('/locale/de_CH').follow()

    login = client.get('/auth/login')
    login.form['username'] = '******'
    login.form['password'] = '******'
    login.form.submit()

    with open(file, 'rb') as f:
        content = f.read()
        workbook = open_workbook(file_contents=content)

    sheet = workbook.sheet_by_name('DATA')
    data_rows = sheet.nrows - 1

    # Upload
예제 #33
0
import time

from contextlib import suppress
from http.client import RemoteDisconnected
from onegov.core.utils import module_path
from time import sleep


with open(module_path('onegov_testing', 'drop_file.js')) as f:
    JS_DROP_FILE = f.read()


class InjectedBrowserExtension(object):
    """ Offers methods to inject an extended browser into the Splinter browser
    class hierarchy. All methods not related to spawning/cloning a new browser
    instance are provided by :class:`ExtendedBrowser`.

    """

    @classmethod
    def spawn(cls, browser_factory, *args, **kwargs):
        """ Takes a Splinter browser factory together with the arguments
        meant for the factory and returns a new browser with the current class
        injected into the class hierarchy.

        """

        # spawning Chrome on Travis is rather flaky and succeeds less than
        # 50% of the time for unknown reasons
        for _ in range(10):
            with suppress(Exception):
예제 #34
0
def get_i18n_localedirs():
    return [
        utils.module_path('onegov.gazette', 'locale'),
        utils.module_path('onegov.form', 'locale'),
        utils.module_path('onegov.user', 'locale')
    ]
예제 #35
0
def get_shared_assets_path():
    return utils.module_path('onegov.shared', 'assets/js')
예제 #36
0
def fixtures():
    return Path(module_path('onegov.winterthur', 'tests/fixtures'))
예제 #37
0
            '<p>Wohnsitz:<br>street houseNumber<br>swissZipCode town</p>'
            '<p>Weitere Informationen zur Person:<br>personInformation</p>'
            '<p><strong>Datum der Konkurseröffnung</strong><br>31.05.2018</p>'
            '<p><strong>Zusatz</strong><br>ausgeschlagene Erbschaft</p>'
            '<p><strong>Rechtliche Hinweise und Fristen</strong><br>legal</p>'
            '<p><strong>Ergänzende rechtliche Hinweise</strong><br>add</p>'
            '<p><strong>Bemerkungen</strong><br>remarks</p>')
        assert notice.category_id == '190'
        assert notice.organization_id == '200'
        assert notice.source == 'YYY1'
        assert list(notice.issues.keys()) == ['2018-7']
        assert notice.first_issue.date() == date(2018, 7, 1)


@mark.parametrize("xml",
                  [module_path('onegov.gazette', 'tests/fixtures/KK01.xml')])
def test_sogc_converter_KK01(gazette_app, xml):
    converter = KK01(etree.parse(xml))
    assert converter.source == 'KK01-0000000008'
    assert converter.publication_date == datetime(2018, 7, 2, 0, 0)
    assert converter.expiration_date == datetime(2020, 12, 12, 0, 0)
    assert converter.title == (
        'Vorläufige Konkursanzeige Museum Company mit UID')
    assert converter.text == (
        '<p><strong>Schuldner</strong><br>Museum Company mit UID</p>'
        '<p>UID: CHE-123.456.789</p>'
        '<p>Grossmatt 144<br>5618 Bettwil</p>'
        '<p><strong>Datum der Konkurseröffnung</strong><br>03.05.2018</p>'
        '<p><strong>Rechtliche Hinweise und Fristen</strong><br>'
        'Meldung nach Art. 222 SchKG. Die Publikation betreffend Art, '
        'Verfahren, Eingabefrist usw. erfolgt später.</p>'
예제 #38
0
 def sponsors(self):
     return load_sponsors(utils.module_path('onegov.feriennet', 'sponsors'))
예제 #39
0
 def extra_search_paths(self):
     return [module_path('onegov.town.theme', 'styles')]
예제 #40
0
파일: app.py 프로젝트: Gitlab11/onegov.town
def get_i18n_localedir():
    return utils.module_path('onegov.town', 'locale')
예제 #41
0
 def occasions_by_state(self):
     return as_selectable_from_path(
         module_path('onegov.feriennet', 'queries/occasions_by_state.sql'))
예제 #42
0
def get_i18n_localedirs():
    return [utils.module_path('onegov.feriennet', 'locale')] \
        + default_i18n_localedirs()
예제 #43
0
def create_new_organisation(app,
                            name,
                            create_files=True,
                            path=None,
                            locale='de_CH'):
    locales = {
        'de_CH': 'content/de.yaml',
        'fr_CH': 'content/fr.yaml',
    }

    path = path or module_path('onegov.feriennet', locales[locale])
    content = load_content(path)

    org = Organisation(name=name, **content['organisation'])
    org.meta['locales'] = locale

    session = app.session()
    session.add(org)

    add_pages(session, path)

    forms = FormCollection(session).definitions

    if locale == 'de_CH':
        forms.add(name='kontakt',
                  title="Kontakt",
                  meta={
                      'lead':
                      ("Haben Sie Fragen oder eine Anregung? "
                       "Rufen Sie uns einfach an oder benutzen Sie dieses "
                       "Formular.")
                  },
                  definition=textwrap.dedent("""\
                Vorname *= ___
                Nachname *= ___
                Telefon *= ___
                E-Mail *= @@@
                Mitteilung *= ...[12]
            """),
                  type='builtin')
    elif locale == 'fr_CH':
        forms.add(name='contact',
                  title="Contact",
                  meta={
                      'lead':
                      ("Avez-vous des questions ou des commentaires ? "
                       "Appelez-nous simplement, ou utilisez le formulaire "
                       "suivant.")
                  },
                  definition=textwrap.dedent("""\
                Prénom *= ___
                Nom *= ___
                Telefon *= ___
                Émail *= @@@
                Message *= ...[12]
            """),
                  type='builtin')
    else:
        raise NotImplementedError

    if create_files:
        add_filesets(session, name,
                     module_path('onegov.feriennet', locales[locale]))

    return org
예제 #44
0
 def extra_search_paths(self):
     base_paths = super().extra_search_paths
     return [module_path('onegov.agency.theme', 'styles')] + base_paths
예제 #45
0
from freezegun import freeze_time
from onegov.core.utils import module_path
from onegov.gazette.tests.common import accept_notice
from onegov.gazette.tests.common import login_users
from onegov.gazette.tests.common import submit_notice
from pytest import mark
from webtest.forms import Upload


@mark.parametrize(
    "pdf_1, pdf_2",
    [(module_path('onegov.gazette', 'tests/fixtures/example_1.pdf'),
      module_path('onegov.gazette', 'tests/fixtures/example_2.pdf'))])
def test_view_notice_attachments(gazette_app, temporary_path, pdf_1, pdf_2):

    admin, editor_1, editor_2, editor_3, publisher = login_users(gazette_app)

    with freeze_time("2017-10-01 12:00"):
        manage = editor_1.get('/notices/drafted/new-notice')
        manage.form['title'] = "Erneuerungswahlen"
        manage.form['organization'] = '200'
        manage.form['category'] = '11'
        manage.form['issues'] = ['2017-40']
        manage.form['text'] = "1. Oktober 2017"
        manage.form['author_place'] = 'Govikon'
        manage.form['author_name'] = 'State Chancellerist'
        manage.form['author_date'] = '2019-01-01'
        manage.form.submit()

        editor_1.get('/notice/erneuerungswahlen/attachments', status=403)
        manage = publisher.get('/notice/erneuerungswahlen/attachments')
예제 #46
0
from onegov.core.request import CoreRequest
from onegov.core.utils import module_path
from pytest import mark
from unittest.mock import patch
from webtest.forms import Upload


@mark.parametrize(
    "pdf_1, pdf_2",
    [(module_path('onegov.wtfs', 'tests/fixtures/example_1.pdf'),
      module_path('onegov.wtfs', 'tests/fixtures/example_2.pdf'))])
def test_views_user_manual(client, pdf_1, pdf_2):
    with open(pdf_1, 'rb') as file:
        pdf_1 = file.read()
    with open(pdf_2, 'rb') as file:
        pdf_2 = file.read()

    client.login_admin()

    view = client.get('/user-manual')
    client.get('http://localhost/user-manual/pdf', status=503)
    assert "Noch kein Benutzerhandbuch vorhanden." in view

    add = view.click("Bearbeiten")
    add.form['pdf'] = Upload(f'Handbuch.pdf', pdf_1, 'application/pdf')
    added = add.form.submit().follow()
    assert "Benutzerhandbuch geändert." in added
    assert "Benutzerhandbuch (PDF, 8.1 kB)." in added
    assert client.get('http://localhost/user-manual/pdf').body == pdf_1

    # Edit
예제 #47
0
import tarfile

from datetime import date
from io import BytesIO
from onegov.ballot import Vote
from onegov.core.csv import convert_list_of_dicts_to_csv
from onegov.core.utils import module_path
from onegov.election_day.formats import import_vote_internal
from onegov.election_day.models import Canton
from pytest import mark


@mark.parametrize("tar_file", [
    module_path('onegov.election_day', 'tests/fixtures/internal_vote.tar.gz'),
])
def test_import_internal_vote(session, tar_file):
    session.add(
        Vote(title='vote', domain='federation', date=date(2017, 5, 21))
    )
    session.flush()
    vote = session.query(Vote).one()

    # The tar file contains vote results from SG (Energiegesetz) v1.13.1
    with tarfile.open(tar_file, 'r|gz') as f:
        csv = f.extractfile(f.next()).read()

    # Test federal results
    principal = Canton(canton='sg')
    vote.expats = True

    errors = import_vote_internal(vote, principal, BytesIO(csv), 'text/plain')
예제 #48
0
 def extra_search_paths(self):
     return [module_path('onegov.onboarding.theme', 'styles')]
예제 #49
0
 def invoices_by_period_query(self):
     return as_selectable_from_path(
         module_path('onegov.feriennet', 'queries/invoices_by_period.sql'))
예제 #50
0
def asset(path):
    """ Returns the absolute path to an asset path relative to this module. """
    return module_path('onegov.shared', 'assets' + '/' + path.lstrip('/'))
예제 #51
0
import time

from contextlib import suppress
from http.client import RemoteDisconnected
from onegov.core.utils import module_path
from time import sleep

with open(module_path('onegov_testing', 'drop_file.js')) as f:
    JS_DROP_FILE = f.read()


class InjectedBrowserExtension(object):
    """ Offers methods to inject an extended browser into the Splinter browser
    class hierarchy. All methods not related to spawning/cloning a new browser
    instance are provided by :class:`ExtendedBrowser`.

    """
    @classmethod
    def spawn(cls, browser_factory, *args, **kwargs):
        """ Takes a Splinter browser factory together with the arguments
        meant for the factory and returns a new browser with the current class
        injected into the class hierarchy.

        """

        # spawning Chrome on Travis is rather flaky and succeeds less than
        # 50% of the time for unknown reasons
        for _ in range(10):
            with suppress(Exception):
                browser = browser_factory(*args, **kwargs)
                break
예제 #52
0
 def attendee_calendar(self):
     return as_selectable_from_path(
         module_path('onegov.feriennet', 'queries/attendee_calendar.sql'))
예제 #53
0
파일: app.py 프로젝트: i18nHub/onegov.town
 def webassets_path(self):
     return utils.module_path('onegov.town', 'assets')
예제 #54
0
def create_app(app_class,
               request,
               use_elasticsearch=False,
               reuse_filestorage=True,
               use_smtp=True,
               depot_backend='depot.io.local.LocalFileStorage',
               depot_storage_path=None):

    # filestorage can be reused between tries as it is nowadays mainly (if not
    # exclusively) used by the theme compiler
    if reuse_filestorage:
        filestorage_object = request.getfixturevalue('long_lived_filestorage')
    else:
        filestorage_object = None

    if not app_class.is_committed():
        scan_morepath_modules(app_class)
        app_class.commit()

    if use_elasticsearch:
        elasticsearch_hosts = [request.getfixturevalue('es_url')]
    else:
        elasticsearch_hosts = []

    if depot_backend == 'depot.io.local.LocalFileStorage':
        if not depot_storage_path:
            depot_storage_path = request.getfixturevalue('temporary_directory')

    temporary_path = request.getfixturevalue('temporary_path')
    signing_services = (temporary_path / 'signing-services')
    signing_services.mkdir()

    cert_file = module_path('onegov_testing', 'tests/fixtures/test.crt')
    cert_key = module_path('onegov_testing', 'tests/fixtures/test.crt')

    with (signing_services / '__default__.yml').open('w') as f:
        f.write(
            textwrap.dedent(f"""
            name: swisscom_ais
            parameters:
                customer: foo
                key_static: bar
                cert_file: {cert_file}
                cert_key: {cert_key}
        """))

    app = app_class()
    app.namespace = random_namespace()
    app.configure_application(
        dsn=request.getfixturevalue('postgres_dsn'),
        filestorage='fs.osfs.OSFS',
        filestorage_object=filestorage_object,
        depot_backend=depot_backend,
        depot_storage_path=depot_storage_path,
        identity_secure=False,
        enable_elasticsearch=use_elasticsearch,
        elasticsearch_hosts=elasticsearch_hosts,
        redis_url=request.getfixturevalue('redis_url'),
        yubikey_client_id='foo',
        yubikey_secret_key='dGhlIHdvcmxkIGlzIGNvbnRyb2xsZWQgYnkgbGl6YXJkcyE=',
        signing_services=str(signing_services))

    app.set_application_id(app.namespace + '/test')
    app.clear_request_cache()

    if hasattr(app, 'bind_depot'):
        app.bind_depot()

    # cronjobs leave lingering sessions open, in real life this is not a
    # problem, but in testing it leads to connection pool exhaustion
    app.settings.cronjobs = Bunch(enabled=False)

    if use_smtp:
        smtp = request.getfixturevalue('smtp')

        app.mail = {
            'marketing': {
                'host': smtp.address[0],
                'port': smtp.address[1],
                'force_tls': False,
                'username': None,
                'password': None,
                'use_directory': False,
                'sender': '*****@*****.**'
            },
            'transactional': {
                'host': smtp.address[0],
                'port': smtp.address[1],
                'force_tls': False,
                'username': None,
                'password': None,
                'use_directory': False,
                'sender': '*****@*****.**'
            }
        }

        app.smtp = smtp

    return app
예제 #55
0
        ('de_CH', "Über das Projekt", "Platzhalterttext"),
        ('fr_CH', "À propos du projet", "Texte de remplacement"),
        ('en_US', "About the project", "Placeholder text")
    ):
        client.get(f'/locale/{locale}').follow()
        page = client.get('/page/about')
        assert title in page
        assert content in page

    client.get(f'/locale/de_CH').follow()
    client.get('/page/about').click("Seite löschen").form.submit()
    client.get('/page/about', status=404)


@mark.parametrize("pdf_1, pdf_2", [(
    module_path('onegov.swissvotes', 'tests/fixtures/example_1.pdf'),
    module_path('onegov.swissvotes', 'tests/fixtures/example_2.pdf')
)])
def test_view_page_attachments(swissvotes_app, temporary_path, pdf_1, pdf_2):

    client = Client(swissvotes_app)

    login = client.get('/auth/login')
    login.form['username'] = '******'
    login.form['password'] = '******'
    login.form.submit()

    client.get(f'/locale/en_US').follow()
    add = client.get('/').maybe_follow().click(href='add')
    add.form['title'] = "About"
    add.form['content'] = "About the project"
import tarfile

from datetime import date
from io import BytesIO
from onegov.ballot import Election
from onegov.core.utils import module_path
from onegov.election_day.formats import import_election_wabsti_majorz
from onegov.election_day.models import Canton
from onegov.election_day.models import Municipality
from pytest import mark


@mark.parametrize("tar_file", [
    module_path('onegov.election_day', 'tests/fixtures/wabsti_majorz.tar.gz'),
])
def test_import_wabsti_majorz(session, tar_file):
    session.add(
        Election(
            title='election',
            domain='canton',
            date=date(2011, 10, 23),
            number_of_mandates=1,
        )
    )
    session.flush()
    election = session.query(Election).one()

    principal = Canton(canton='sg')

    # The tar file contains
    # - cantonal results from SG from the 23.10.2011
예제 #57
0
def create_app(app_class, request, use_elasticsearch=False,
               reuse_filestorage=True, use_smtp=True,
               depot_backend='depot.io.local.LocalFileStorage',
               depot_storage_path=None):

    # filestorage can be reused between tries as it is nowadays mainly (if not
    # exclusively) used by the theme compiler
    if reuse_filestorage:
        filestorage_object = request.getfixturevalue('long_lived_filestorage')
    else:
        filestorage_object = None

    if not app_class.is_committed():
        scan_morepath_modules(app_class)
        app_class.commit()

    if use_elasticsearch:
        elasticsearch_hosts = [
            request.getfixturevalue('es_url')
        ]
    else:
        elasticsearch_hosts = []

    if depot_backend == 'depot.io.local.LocalFileStorage':
        if not depot_storage_path:
            depot_storage_path = request.getfixturevalue('temporary_directory')

    temporary_path = request.getfixturevalue('temporary_path')
    signing_services = (temporary_path / 'signing-services')
    signing_services.mkdir()

    cert_file = module_path('onegov_testing', 'tests/fixtures/test.crt')
    cert_key = module_path('onegov_testing', 'tests/fixtures/test.crt')

    with (signing_services / '__default__.yml').open('w') as f:
        f.write(textwrap.dedent(f"""
            name: swisscom_ais
            parameters:
                customer: foo
                key_static: bar
                cert_file: {cert_file}
                cert_key: {cert_key}
        """))

    app = app_class()
    app.namespace = random_namespace()
    app.configure_application(
        dsn=request.getfixturevalue('postgres_dsn'),
        filestorage='fs.osfs.OSFS',
        filestorage_object=filestorage_object,
        depot_backend=depot_backend,
        depot_storage_path=depot_storage_path,
        identity_secure=False,
        enable_elasticsearch=use_elasticsearch,
        elasticsearch_hosts=elasticsearch_hosts,
        redis_url=request.getfixturevalue('redis_url'),
        yubikey_client_id='foo',
        yubikey_secret_key='dGhlIHdvcmxkIGlzIGNvbnRyb2xsZWQgYnkgbGl6YXJkcyE=',
        signing_services=str(signing_services)
    )

    app.set_application_id(app.namespace + '/test')
    app.clear_request_cache()

    if hasattr(app, 'bind_depot'):
        app.bind_depot()

    # cronjobs leave lingering sessions open, in real life this is not a
    # problem, but in testing it leads to connection pool exhaustion
    app.settings.cronjobs = Bunch(enabled=False)

    if use_smtp:
        smtp = request.getfixturevalue('smtp')

        app.mail = {
            'marketing': {
                'host': smtp.address[0],
                'port': smtp.address[1],
                'force_tls': False,
                'username': None,
                'password': None,
                'use_directory': False,
                'sender': '*****@*****.**'
            },
            'transactional': {
                'host': smtp.address[0],
                'port': smtp.address[1],
                'force_tls': False,
                'username': None,
                'password': None,
                'use_directory': False,
                'sender': '*****@*****.**'
            }
        }

        app.smtp = smtp

    return app
예제 #58
0
def get_i18n_localedirs():
    return [
        utils.module_path('onegov.election_day', 'locale'),
        utils.module_path('onegov.form', 'locale'),
        utils.module_path('onegov.user', 'locale')
    ]