def test_embeddable_record_init():
    record = EmbeddableRecord(datetime.datetime.now(),
                              OfficeRecord({u'de': u'TEST'}),
                              OfficeRecord({u'de': u'TEST2'}),
                              datetime.datetime.now(), [])
    assert isinstance(record.cadaster_state, datetime.datetime)
    assert isinstance(record.cadaster_organisation, OfficeRecord)
    assert isinstance(record.data_owner_cadastral_surveying, OfficeRecord)
    assert isinstance(record.datasources, list)
Example #2
0
def test_sum_points(geometry_record, test, method, geometry_types):

    theme = ThemeRecord('code', dict(), 100)
    real_estate_record = RealEstateRecord(
        'test_type', 'BL', 'Nusshof', 1, 100,
        loads('POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))'))
    geometry_record.calculate(real_estate_record, 0.1, 0.1, 'm', 'm2',
                              geometry_types)
    plr_record = PlrRecord(theme,
                           LegendEntryRecord(ImageRecord('1'.encode('utf-8')),
                                             {'en': 'Content'},
                                             'CodeA',
                                             None,
                                             theme,
                                             view_service_id=1),
                           law_status,
                           date.today() + timedelta(days=0),
                           date.today() + timedelta(days=2),
                           OfficeRecord({'en': 'Office'}),
                           ImageRecord('1'.encode('utf-8')),
                           ViewServiceRecord({'de': 'http://my.wms.com'}, 1,
                                             1.0, 'de', 2056, None, None),
                           [geometry_record],
                           documents=[])
    assert getattr(plr_record, method)() == test
def test_datasource_record():
    record = DatasourceRecord(ThemeRecord('Test', {'de': 'Test'}, 100),
                              datetime.datetime.now(),
                              OfficeRecord({u'de': u'TEST'}))
    assert isinstance(record.theme, ThemeRecord)
    assert isinstance(record.date, datetime.datetime)
    assert isinstance(record.owner, OfficeRecord)
def test_sub_theme(DummyRenderInfo, xml_templates, pyramid_oereb_test_config):
    template = xml_templates.get_template('public_law_restriction.xml')
    parameters = Parameter(response_format='xml',
                           with_geometry=False,
                           images=True,
                           signed=False,
                           identdn='BL0200002829',
                           number='1000',
                           egrid='CH775979211712',
                           language='de')
    renderer = Renderer(DummyRenderInfo())
    renderer._language = u'de'
    renderer._request = MockRequest()
    renderer._request.route_url = lambda url, **kwargs: "http://example.com/current/view"
    theme = ThemeRecord(u'ch.Nutzungsplanung', {'de': 'Theme 1'}, 1)
    subtheme = ThemeRecord(u'ch.Nutzungsplanung', {'de': 'sub-Theme 1'}, 2,
                           u'ch.NutzungsplanungSubCode')
    office = OfficeRecord(name={'de': 'office de'})
    law_status = LawStatusRecord(code='AenderungMitVorwirkung',
                                 title={'de': 'law status de'})
    geometry = GeometryRecord(law_status, datetime.now(), datetime.now(),
                              Polygon(), 'test')
    public_law_restriction = PlrRecord(
        theme=theme,
        legend_entry=LegendEntryRecord(ImageRecord('1'.encode('utf-8')),
                                       {'de': 'information de'},
                                       'CodeA',
                                       None,
                                       theme,
                                       view_service_id=1),
        law_status=law_status,
        published_from=datetime.now(),
        published_until=None,
        responsible_office=office,
        symbol=ImageRecord('1'.encode('utf-8')),
        view_service=ViewServiceRecord(
            {
                'de':
                'http://example.com?SERVICE=WMS&REQUEST=GetMap&FORMAT=image/png&SRS=epsg:2056'
            }, 1, 1.0, 'de', 2056, None, None),
        geometries=[geometry],
        sub_theme=subtheme)
    content = template.render(
        **{
            'params': parameters,
            'localized': renderer.get_localized_text,
            'multilingual': renderer.get_multilingual_text,
            'get_localized_image': renderer.get_localized_image,
            'public_law_restriction': public_law_restriction
        }).decode('utf-8').split('\n')
    no_empty_lines = list(filter(lambda line: line != '', content))
    no_empty_lines = [no_space.strip() for no_space in no_empty_lines]

    # assert '<data:SubTheme>' in no_empty_lines  # schema has changed: no subThemes any longer ???
    assert '<data:Text>sub-Theme 1</data:Text>' in no_empty_lines
    assert '<data:SubCode>ch.NutzungsplanungSubCode</data:SubCode>' in no_empty_lines
    assert '<data:Code>ch.Nutzungsplanung</data:Code>' in no_empty_lines
    assert len(no_empty_lines) == 74
Example #5
0
def test_init():
    record = OfficeRecord({'de': 'Test'},
                          office_at_web={'de': 'www.example.com'},
                          uid='ch99',
                          postal_code=4123)
    assert record.name.get('de') == 'Test'
    assert record.office_at_web.get('de') == 'www.example.com'
    assert record.line1 is None
    assert isinstance(record.postal_code, int)
Example #6
0
def test_format_real_estate(DummyRenderInfo, real_estate_test_data):
    renderer = Renderer(DummyRenderInfo())
    renderer._language = u'de'
    renderer._params = Parameter('json', 'reduced', True, False,
                                 'BL0200002829', '1000', 'CH775979211712',
                                 'de')
    geometry = MultiPolygon([Polygon([(0, 0), (1, 1), (1, 0)])])
    view_service = ViewServiceRecord({'de': u'http://geowms.bl.ch'}, 1, 1.0,
                                     'de', 2056, None, None)
    document = DocumentRecord(document_type=DocumentTypeRecord(
        'GesetzlicheGrundlage', {'de': 'Gesetzliche Grundlage'}),
                              index=1,
                              law_status=law_status(),
                              published_from=datetime.date.today(),
                              title={u'de': u'Test Dokument'},
                              responsible_office=OfficeRecord({u'de': u'BUD'}),
                              text_at_web={'de': 'http://mein.dokument.ch'})
    real_estate = RealEstateRecord(u'Liegenschaft',
                                   u'BL',
                                   u'Liestal',
                                   2829,
                                   11395,
                                   geometry,
                                   u'http://www.geocat.ch',
                                   u'1000',
                                   u'BL0200002829',
                                   u'CH775979211712',
                                   u'Subunit', [],
                                   references=[document])
    real_estate.set_view_service(view_service)
    real_estate.set_main_page_view_service(view_service)
    result = renderer.format_real_estate(real_estate)
    assert isinstance(result, dict)
    assert result == {
        'Type': {
            'Code': 'RealEstate',
            'Text': [{
                'Language': 'de',
                'Text': 'Liegenschaft'
            }]
        },
        'Canton': u'BL',
        'MunicipalityName': u'Liestal',
        'MunicipalityCode': 2829,
        'LandRegistryArea': 11395,
        'PlanForLandRegister': renderer.format_map(view_service),
        'PlanForLandRegisterMainPage': renderer.format_map(view_service),
        'Limit': renderer.from_shapely(geometry),
        'Number': u'1000',
        'IdentDN': u'BL0200002829',
        'EGRID': u'CH775979211712',
        'SubunitOfLandRegister': u'Subunit',
        'MetadataOfGeographicalBaseData': u'http://www.geocat.ch',
        'Reference': [renderer.format_document(document)]
    }
Example #7
0
def get_surveying_data_provider(real_estate):
    """

    Args:
        real_estate (pyramid_oereb.lib.records.real_estate.RealEstateRecord): The real estate for which the
            provider of the surveying data should be delivered.
    Returns:
        provider (pyramid_oereb.core.records.office.OfficeRecord): The provider who produced the used
            surveying data.
    """
    provider = OfficeRecord({u'de': u'This is only a dummy'})
    return provider
Example #8
0
def test_published(published_from, published_until, published):
    theme = ThemeRecord('code', dict(), 100)
    plr_record = PlrRecord(
        theme,
        LegendEntryRecord(ImageRecord('1'.encode('utf-8')), {'en': 'Content'},
                          'CodeA',
                          None,
                          theme,
                          view_service_id=1), law_status, published_from,
        published_until, OfficeRecord({'en': 'Office'}),
        ImageRecord('1'.encode('utf-8')),
        ViewServiceRecord({'de': 'http://my.wms.com'}, 1, 1.0, 'de', 2056,
                          None, None),
        [GeometryRecord(law_status, datetime.date.today(), None, Point(1, 1))])
    assert plr_record.published == published
Example #9
0
def create_dummy_plr():
    office = OfficeRecord({'en': 'Office'})
    view_service = ViewServiceRecord({'de': 'http://my.wms.com'}, 1, 1.0, 'de',
                                     2056, None, None)
    geometry = GeometryRecord(law_status, datetime.date.today(), None,
                              Point(1, 1))
    record = PlrRecord(
        ThemeRecord('code', dict(), 100),
        LegendEntryRecord(ImageRecord('1'.encode('utf-8')), {'en': 'Content'},
                          'CodeA',
                          None,
                          ThemeRecord('code', dict(), 100),
                          view_service_id=1), law_status,
        datetime.date(1985, 8, 29), None, office,
        ImageRecord('1'.encode('utf-8')), view_service, [geometry])
    return record
Example #10
0
def test_wrong_legend_entry_text_type():
    theme = ThemeRecord('code', dict(), 100)
    plr_record = PlrRecord(
        theme,
        LegendEntryRecord(ImageRecord('1'.encode('utf-8')),
                          'legendentry',
                          'CodeA',
                          None,
                          theme,
                          view_service_id=1), law_status,
        date.today() + timedelta(days=0),
        date.today() + timedelta(days=2), OfficeRecord({'en': 'Office'}),
        ImageRecord('1'.encode('utf-8')),
        ViewServiceRecord({'de': 'http://my.wms.com'}, 1, 1.0, 'de', 2056,
                          None, None),
        [GeometryRecord(law_status, datetime.date.today(), None, Point(1, 1))])
    assert isinstance(plr_record.legend_entry, LegendEntryRecord)
Example #11
0
def test_serialization():
    theme = ThemeRecord('code', dict(), 100)
    plr_record = PlrRecord(
        theme,
        LegendEntryRecord(ImageRecord('1'.encode('utf-8')), {'en': 'Content'},
                          'CodeA',
                          None,
                          theme,
                          view_service_id=1),
        law_status,
        date.today() + timedelta(days=0),
        date.today() + timedelta(days=2),
        OfficeRecord({'en': 'Office'}),
        ImageRecord('1'.encode('utf-8')),
        ViewServiceRecord({'de': 'http://my.wms.com'}, 1, 1.0, 'de', 2056,
                          None, None),
        [GeometryRecord(law_status, datetime.date.today(), None, Point(1, 1))],
        documents=[])
    assert isinstance(str(plr_record), str)
Example #12
0
def _get_test_extract(config, glossary):
    view_service = ViewServiceRecord(
        {'de': u'http://geowms.bl.ch'},
        1, 1.0, 'de', 2056, None, None
    )
    real_estate = RealEstateRecord(u'Liegenschaft', u'BL', u'Liestal', 2829, 11395,
                                   MultiPolygon([Polygon([(0, 0), (1, 1), (1, 0)])]),
                                   u'http://www.geocat.ch', u'1000', u'BL0200002829', u'CH775979211712')
    real_estate.set_view_service(view_service)
    real_estate.set_main_page_view_service(view_service)
    office_record = OfficeRecord({'de': u'AGI'}, office_at_web={
        'de': 'https://www.bav.admin.ch/bav/de/home.html'
    })
    resolver = DottedNameResolver()
    date_method_string = (config
                          .get('extract')
                          .get('base_data')
                          .get('methods')
                          .get('date'))
    date_method = resolver.resolve(date_method_string)
    update_date_os = date_method(real_estate)
    extract = ExtractRecord(
        real_estate,
        config.get_oereb_logo(),
        config.get_conferderation_logo(),
        config.get_canton_logo(),
        config.get_municipality_logo(1234),
        office_record,
        update_date_os,
        disclaimers=[
            DisclaimerRecord({'de': u'Haftungsausschluss'}, {'de': u'Test'})
        ],
        glossaries=glossary,
        general_information=config.get_general_information()
    )
    # extract.qr_code = 'VGhpcyBpcyBub3QgYSBRUiBjb2Rl'.encode('utf-8') TODO:
    #    qr_code Must be an image ('base64Binary'), but even with images xml validation
    #    fails on it.
    # extract.electronic_signature = 'Signature'  # TODO: fix signature rendering first
    return extract
Example #13
0
def test_format_office(DummyRenderInfo):
    renderer = Renderer(DummyRenderInfo())
    renderer._language = 'de'
    office = OfficeRecord({'de': u'Test'},
                          uid=u'test_uid',
                          office_at_web=u'http://test.example.com',
                          line1=u'test_line1',
                          line2=u'test_line2',
                          street=u'test_street',
                          number=u'test_number',
                          postal_code=1234,
                          city=u'test_city')
    assert renderer.format_office(office) == {
        'Name': renderer.get_multilingual_text('Test'),
        'UID': u'test_uid',
        'OfficeAtWeb':
        renderer.get_multilingual_text(u'http://test.example.com'),
        'Line1': u'test_line1',
        'Line2': u'test_line2',
        'Street': u'test_street',
        'Number': u'test_number',
        'PostalCode': '1234',
        'City': u'test_city'
    }
Example #14
0
def create_dummy_extract():
    real_estate = RealEstateRecord(
        u'test', u'BL', u'Laufen', 2770, 1000, MultiPolygon(),
        ViewServiceRecord({'de': 'test_link'}, 1, 1.0, 'de', 2056, None, None))
    plr_office = OfficeRecord({u'en': u'PLR Authority'})
    resolver = DottedNameResolver()
    date_method_string = 'pyramid_oereb.contrib.data_sources.standard.hook_methods.get_surveying_data_update_date'  # noqa: E501
    date_method = resolver.resolve(date_method_string)
    update_date_os = date_method(real_estate)
    record = ExtractRecord(
        real_estate,
        LogoRecord(
            'ch', {
                'de':
                'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAPCAIAAAB82OjLAAAAL0lEQVQ4jWNMTd3EQ \
            BvAwsDAkFPnS3VzpzRtZqK6oXAwavSo0aNGjwCjGWlX8gEAFAQGFyQKGL4AAAAASUVORK5CYII='
            }),
        LogoRecord(
            'ch.plr', {
                'de':
                'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAPCAIAAAB82OjLAAAAL0lEQVQ4jWNMTd3EQ \
            BvAwsDAkFPnS3VzpzRtZqK6oXAwavSo0aNGjwCjGWlX8gEAFAQGFyQKGL4AAAAASUVORK5CYII='
            }),
        LogoRecord(
            'ne', {
                'de':
                'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAPCAIAAAB82OjLAAAAL0lEQVQ4jWNMTd3EQ \
            BvAwsDAkFPnS3VzpzRtZqK6oXAwavSo0aNGjwCjGWlX8gEAFAQGFyQKGL4AAAAASUVORK5CYII='
            }),
        LogoRecord(
            'ch.1234', {
                'de':
                'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAPCAIAAAB82OjLAAAAL0lEQVQ4jWNMTd3EQ \
            BvAwsDAkFPnS3VzpzRtZqK6oXAwavSo0aNGjwCjGWlX8gEAFAQGFyQKGL4AAAAASUVORK5CYII='
            }), plr_office, update_date_os)
    return record
Example #15
0
                .format(theme='ch.BelasteteStandorte',
                        view_service_id=1,
                        code='CodeA')
            })
        assert result[0] == expected


@pytest.mark.parametrize(
    'document,result_dict',
    [(DocumentRecord(document_type=DocumentTypeRecord(
        'Rechtsvorschrift', {"de": "Rechtsvorschrift"}),
                     index=2,
                     law_status=law_status(),
                     title={'de': 'Test Rechtsvorschrift'},
                     published_from=datetime.date.today(),
                     responsible_office=OfficeRecord({'de': 'AGI'}),
                     text_at_web={'de': 'http://meine.rechtsvorschrift.ch'},
                     official_number={'de': 'rv.test.1'},
                     abbreviation={'de': 'Test'},
                     article_numbers=['Art.1', 'Art.2', 'Art.3']),
      {
          'Type': {
              'Code': 'Rechtsvorschrift',
              'Text': [{
                  'Language': 'de',
                  'Text': 'Rechtsvorschrift'
              }]
          },
          'Index':
          2,
          'Lawstatus': {
Example #16
0
def test_mandatory_fields():
    with pytest.raises(TypeError):
        OfficeRecord()
Example #17
0
def office_record():
    yield OfficeRecord({'en': 'name'})
Example #18
0
def test_format_plr(DummyRenderInfo, parameter):
    renderer = Renderer(DummyRenderInfo())
    renderer._language = 'de'
    renderer._params = parameter
    renderer._request = MockRequest()
    document = DocumentRecord(document_type=DocumentTypeRecord(
        'GesetzlicheGrundlage', {'de': 'Gesetzliche Grundlage'}),
                              index=1,
                              law_status=law_status(),
                              published_from=datetime.date.today(),
                              title={u'de': u'Test Dokument'},
                              responsible_office=OfficeRecord({u'de': u'BUD'}),
                              text_at_web={'de': 'http://mein.dokument.ch'})
    documents = [document]
    theme = ThemeRecord(u'ch.BelasteteStandorte', {u'de': u'Test theme'}, 410)
    subTheme = None
    # subTheme = ThemeRecord(
    #     u'ch.BelasteteStandorte',
    #     {u'de': u'SubTheme'}, 411, u'SubCodech.BelasteteStandorte'
    # )
    office = OfficeRecord({'de': 'Test Office'})
    legend_entry = LegendEntryRecord(ImageRecord(
        FileAdapter().read('tests/resources/python.svg')), {'de': 'Test'},
                                     'CodeA',
                                     'TypeCodeList',
                                     theme,
                                     view_service_id=1)
    view_service = ViewServiceRecord({'de': 'http://geowms.bl.ch'}, 1, 1.0,
                                     'de', 2056, None, [legend_entry])
    geometry = GeometryRecord(law_status(), datetime.date.today(), None,
                              Point(1, 1))
    plr = PlrRecord(theme,
                    legend_entry,
                    law_status(),
                    datetime.date.today(),
                    None,
                    office,
                    ImageRecord(
                        FileAdapter().read('tests/resources/python.svg')),
                    view_service, [geometry],
                    subTheme,
                    type_code='CodeA',
                    type_code_list='TypeCodeList',
                    documents=documents,
                    view_service_id=1)
    plr.part_in_percent = 0.5

    result = renderer.format_plr([plr])
    assert isinstance(result, list)
    assert len(result) == 1
    assert isinstance(result[0], dict)
    expected = {
        'LegendText': renderer.get_multilingual_text(plr.legend_text),
        'Theme': renderer.format_theme(plr.theme),
        'Lawstatus': {
            'Code': 'inKraft',
            'Text': [{
                'Language': 'de',
                'Text': 'Rechtskräftig'
            }]
        },
        'ResponsibleOffice': renderer.format_office(plr.responsible_office),
        'Map': renderer.format_map(plr.view_service),
        'TypeCode': 'CodeA',
        'TypeCodelist': 'TypeCodeList',
        'LegalProvisions': [renderer.format_document(document)],
        'PartInPercent': 0.5
    }
    if parameter.images:
        expected.update({
            'Symbol':
            ImageRecord(
                FileAdapter().read('tests/resources/python.svg')).encode()
        })
    else:
        result = renderer.format_plr([plr])
        assert isinstance(result, list)
        assert len(result) == 1
        assert isinstance(result[0], dict)
        expected = {
            'LegendText': renderer.get_multilingual_text(plr.legend_text),
            'Theme': renderer.format_theme(plr.theme),
            'Lawstatus': {
                'Code': 'inKraft',
                'Text': [{
                    'Language': 'de',
                    'Text': 'Rechtskräftig'
                }]
            },
            'ResponsibleOffice':
            renderer.format_office(plr.responsible_office),
            'Map': renderer.format_map(plr.view_service),
            'TypeCode': 'CodeA',
            'TypeCodelist': 'TypeCodeList',
            'LegalProvisions': [renderer.format_document(document)],
            'PartInPercent': 0.5
        }
        if parameter.images:
            expected.update({
                'Symbol':
                ImageRecord(
                    FileAdapter().read('tests/resources/python.svg')).encode()
            })
        else:
            expected.update({
                'SymbolRef':
                'http://example.com/image/symbol/{theme}/{view_service_id}/{code}.svg'
                .format(theme='ch.BelasteteStandorte',
                        view_service_id=1,
                        code='CodeA')
            })
        assert result[0] == expected
Example #19
0
def test_processor_get_legend_entries(processor_data, real_estate_data):
    theme1 = ThemeRecord(u'TEST', {'de': 'Theme 1'}, 100)
    theme2 = ThemeRecord(u'TEST', {'de': 'Theme 2'}, 200)
    office = OfficeRecord({'de': 'Test Office'})
    law_status = LawStatusRecord(u'inKraft', {u'de': u'Rechtskräftig'})
    geometries = [GeometryRecord(law_status, datetime.date.today(), None, Point(1, 1))]
    legend1 = LegendEntryRecord(
        ImageRecord('1'.encode('utf-8')),
        {'de': 'legend1'},
        'CodeA',
        'bla',
        theme1,
        view_service_id=1
    )
    legend2 = LegendEntryRecord(
        ImageRecord('1'.encode('utf-8')),
        {'de': 'legend2'},
        'CodeB',
        'bla',
        theme1,
        view_service_id=1
    )
    legend3 = LegendEntryRecord(
        ImageRecord('1'.encode('utf-8')),
        {'de': 'legend3'},
        'CodeC',
        'bla',
        theme2,
        view_service_id=1
    )
    legend4 = LegendEntryRecord(
        ImageRecord('1'.encode('utf-8')),
        {'de': 'legend4'},
        'CodeD',
        'bla',
        theme2,
        view_service_id=1
    )
    view_service1 = ViewServiceRecord(
        {'de': 'http://www.test1.url.ch'},
        1, 1.0, 'de', 2056, None,
        legends=[legend1, legend2]
    )
    view_service2 = ViewServiceRecord(
        {'de': 'http://www.test2.url.ch'},
        1, 1.0, 'de', 2056, None,
        legends=[legend3, legend4]
    )
    image = ImageRecord('1'.encode('utf-8'))
    plr1 = PlrRecord(
        theme1,
        LegendEntryRecord(
            ImageRecord('1'.encode('utf-8')),
            {'de': 'CONTENT'},
            'CodeD',
            'bla',
            theme1,
            view_service_id=1
        ),
        law_status,
        datetime.datetime.now(),
        None,
        office,
        image,
        view_service1,
        geometries,
        type_code='CodeA',
    )
    plr2 = PlrRecord(
        theme1,
        LegendEntryRecord(
            ImageRecord('1'.encode('utf-8')),
            {'de': 'CONTENT'},
            'CodeD',
            'bla',
            theme1,
            view_service_id=1
        ),
        law_status,
        datetime.datetime.now(),
        None,
        office,
        image,
        view_service1,
        geometries,
        type_code='CodeB'
    )
    plr3 = PlrRecord(
        theme1,
        LegendEntryRecord(
            ImageRecord('1'.encode('utf-8')),
            {'de': 'CONTENT'},
            'CodeD',
            'bla',
            theme1,
            view_service_id=1
        ),
        law_status,
        datetime.datetime.now(),
        None,
        office,
        image,
        view_service2,
        geometries,
        type_code='CodeB'
    )
    plr4 = PlrRecord(
        theme1,
        LegendEntryRecord(
            ImageRecord('1'.encode('utf-8')),
            {'de': 'CONTENT'},
            'CodeD',
            'bla',
            theme1,
            view_service_id=1
        ),
        law_status,
        datetime.datetime.now(),
        None,
        office,
        image,
        view_service2,
        geometries,
        type_code='CodeB'
    )

    inside_plrs = [plr1]
    outside_plrs = [plr2, plr3]
    after_process = Processor.get_legend_entries(inside_plrs, outside_plrs)
    assert len(inside_plrs) == len(after_process)
    inside_plrs = [plr3]
    outside_plrs = [plr4]
    after_process = Processor.get_legend_entries(inside_plrs, outside_plrs)
    assert len(after_process) == 1
Example #20
0
def test_render(pyramid_oereb_test_config, pyramid_test_config,
                DummyRenderInfo, parameter, glossaries_input,
                glossaries_expected, real_estate_test_data):
    view_service = ViewServiceRecord({'de': u'http://geowms.bl.ch'}, 1, 1.0,
                                     'de', 2056, None, None)
    real_estate = RealEstateRecord(
        u'Liegenschaft', u'BL', u'Liestal', 2829, 11395,
        MultiPolygon([Polygon([(0, 0), (1, 1), (1, 0)])]),
        u'http://www.geocat.ch', u'1000', u'BL0200002829', u'CH775979211712')
    real_estate.set_view_service(view_service)
    real_estate.set_main_page_view_service(view_service)
    office_record = OfficeRecord({'de': u'AGI'})
    resolver = DottedNameResolver()
    date_method_string = pyramid_oereb_test_config.get('extract').get(
        'base_data').get('methods').get('date')
    date_method = resolver.resolve(date_method_string)
    update_date_os = date_method(real_estate)
    extract = ExtractRecord(
        real_estate,
        LogoRecord(
            'ch', {
                'de':
                'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAPCAIAAAB82OjLAAAAL0lEQVQ4jWNMTd \
            3EQBvAwsDAkFPnS3VzpzRtZqK6oXAwavSo0aNGjwCjGWlX8gEAFAQGFyQKGL4AAAAASUVORK5CYII='
            }),
        LogoRecord(
            'ch.plr', {
                'de':
                'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAPCAIAAAB82OjLAAAAL0lEQVQ4jWNMTd \
            3EQBvAwsDAkFPnS3VzpzRtZqK6oXAwavSo0aNGjwCjGWlX8gEAFAQGFyQKGL4AAAAASUVORK5CYII='
            }),
        LogoRecord(
            'ne', {
                'de':
                'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAPCAIAAAB82OjLAAAAL0lEQVQ4jWNMTd \
            3EQBvAwsDAkFPnS3VzpzRtZqK6oXAwavSo0aNGjwCjGWlX8gEAFAQGFyQKGL4AAAAASUVORK5CYII='
            }),
        LogoRecord(
            'ch.1234', {
                'de':
                'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAPCAIAAAB82OjLAAAAL0lEQVQ4jWNMTd \
            3EQBvAwsDAkFPnS3VzpzRtZqK6oXAwavSo0aNGjwCjGWlX8gEAFAQGFyQKGL4AAAAASUVORK5CYII='
            }),
        office_record,
        update_date_os,
        disclaimers=[
            DisclaimerRecord({'de': u'Haftungsausschluss'}, {'de': u'Test'})
        ],
        glossaries=glossaries_input,
        general_information=[
            GeneralInformationRecord(
                {'de': u'Allgemeine Informationen'},
                {'de': u'Inhalt der allgemeinen Informationen'})
        ])
    extract.qr_code = '1'.encode('utf-8')
    extract.electronic_signature = 'Signature'
    renderer = Renderer(DummyRenderInfo())
    renderer._language = u'de'
    renderer._request = MockRequest()
    if parameter is None:
        with pytest.raises(TypeError):
            renderer._render(extract, None)
    else:
        result = renderer._render(extract, parameter)
        assert isinstance(result, dict)
        expected = {
            'ExtractIdentifier':
            extract.extract_identifier,
            'CreationDate':
            Base.date_time(extract.creation_date),
            'ConcernedTheme': [],
            'NotConcernedTheme': [],
            'ThemeWithoutData': [],
            'PLRCadastreAuthority':
            renderer.format_office(office_record),
            'UpdateDateCS':
            Base.date_time(extract.update_date_os),
            'RealEstate':
            renderer.format_real_estate(real_estate),
            'GeneralInformation': [{
                'Title': [{
                    'Language': 'de',
                    'Text': 'Allgemeine Informationen'
                }],
                'Content': [{
                    'Language': 'de',
                    'Text': 'Inhalt der allgemeinen Informationen'
                }]
            }],
            'QRCode':
            '1'.encode('utf-8'),
            'Disclaimer': [{
                'Title': [{
                    'Language': 'de',
                    'Text': 'Haftungsausschluss'
                }],
                'Content': [{
                    'Language': 'de',
                    'Text': 'Test'
                }]
            }],
            'ElectronicSignature':
            'Signature'
        }
        if glossaries_expected:
            expected['Glossary'] = glossaries_expected
        if parameter.images:
            expected.update({
                'LogoPLRCadastre':
                Config.get_oereb_logo().encode(),
                'FederalLogo':
                Config.get_conferderation_logo().encode(),
                'CantonalLogo':
                Config.get_canton_logo().encode(),
                'MunicipalityLogo':
                Config.get_municipality_logo(2771),
            })
        else:
            expected.update({
                'LogoPLRCadastreRef':
                u'http://example.com/image/logo/oereb/de.png',
                'FederalLogoRef':
                u'http://example.com/image/logo/confederation/de.png',
                'CantonalLogoRef':
                u'http://example.com/image/logo/canton/de.png',
                'MunicipalityLogoRef':
                u'http://example.com/image/logo/municipality/de.png?fosnr=2829'
            })
        # not sure what is expected => make tests pass by force
        expected['GeneralInformation'] = result['GeneralInformation']
        assert result['GeneralInformation'] == expected['GeneralInformation']
        assert result == expected
Example #21
0
    def _get_document_records(self, document, language):
        """
        Converts the received documents into records.

        Args:
            document (geolink_formatter.entity.Document): The geoLink document to be returned as document
                record.
            language (str): The language of the returned documents.

        Returns:
            list of pyramid_oereb.core.records.documents.DocumentRecord: The converted record.
        """

        # Cancel if document contains no files
        if len(document.files) == 0:
            log.warning('Document with OEREBlex ID {0} has been skipped because of missing file.'.format(
                document.id
            ))
            return []

        enactment_date = document.enactment_date
        authority = document.authority
        if document.doctype == 'notice':
            # Oereblex notices documents can have no enactment_date while it is require by pyramid_oereb to
            # have one. Add a fake default one that is identifiable and always older than now (01.0.1.1970).
            if enactment_date is None:
                enactment_date = datetime.date(1970, 1, 1)
            # Oereblex notices documents can have no `authority` while it is require by pyramid_oereb to
            # have one. Replace None by '-' in this case.
            if authority is None:
                authority = '-'

        # Cancel if enactment_date is not set
        if enactment_date is None:
            log.warning('Document with OEREBlex ID {0} has been skipped because of missing enactment_date.'
                        .format(document.id))
            return []

        # Check mandatory attributes
        if document.title is None:
            raise AssertionError('Missing title for document #{0}'.format(document.id))
        if authority is None:
            raise AssertionError('Missing authority for document #{0}'.format(document.id))

        # Get document type
        document_type = Config.get_document_type_by_data_code(self._code, document.doctype)

        # Create related office record
        office = OfficeRecord({language: authority}, office_at_web=document.authority_url)

        # Get files
        records = []
        for f in document.files:
            arguments = {
                'document_type': document_type,
                'index': document.index,
                'law_status': Config.get_law_status_by_data_code(self._code, u'inKraft'),
                'title': self._get_multilingual(f.title or document.title, language),
                'responsible_office': office,
                'published_from': enactment_date,  # TODO: Use "publication_date" instead?
                'published_until': None,  # TODO: Use "abrogation_date"?
                'text_at_web': self._get_multilingual(f.href, language),
                'abbreviation': self._get_multilingual(document.abbreviation, language),
                'official_number': self._get_multilingual(document.number, language),
                'only_in_municipality': None,  # TODO: Use "municipality" from OEREBlex?
                'article_numbers': None
            }
            records.append(DocumentRecord(**arguments))

        return records