def test_format_map(params, legend_at_web, expected_legend_at_web): with pyramid_oereb_test_config(): renderer = Renderer(DummyRenderInfo()) renderer._language = u'de' renderer._params = params renderer._request = MockRequest() legend_entry = LegendEntryRecord( ImageRecord(FileAdapter().read('tests/resources/python.svg')), {u'de': u'Legendeneintrag'}, u'CodeA', u'type_code_list', ThemeRecord(u'ContaminatedSites', {u'de': u'Test'}), view_service_id=1 ) view_service = ViewServiceRecord('http://my.wms.ch', 1, 1.0, legend_at_web, [legend_entry]) view_service.image = ImageRecord(FileAdapter().read('tests/resources/python.svg')) result = renderer.format_map(view_service) assert isinstance(result, dict) expected_result = { 'Image': ImageRecord(FileAdapter().read('tests/resources/python.svg')).encode(), 'layerIndex': 1, 'layerOpacity': 1.0, 'ReferenceWMS': 'http://my.wms.ch', 'OtherLegend': [renderer.format_legend_entry(legend_entry)] } if expected_legend_at_web is not None: expected_result['LegendAtWeb'] = expected_legend_at_web assert result == expected_result
def get_logo_config(): """ Returns a dictionary of the configured file path's to the logos. Returns: dict: The configured paths to the logos wrapped in a dictionary. """ assert Config._config is not None confederation_key = 'confederation' oereb_key = 'oereb' canton_key = 'canton' msg = 'The definition for "{key}" must be set. Got: {found_config}' logo_dict = Config._config.get('logo') if not logo_dict.get(confederation_key): raise ConfigurationError( msg.format(key=confederation_key, found_config=logo_dict)) if not logo_dict.get(oereb_key): raise ConfigurationError( msg.format(key=oereb_key, found_config=logo_dict)) if not logo_dict.get(canton_key): raise ConfigurationError( msg.format(key=canton_key, found_config=logo_dict)) file_adapter = FileAdapter() confederation_logo = ImageRecord( file_adapter.read(logo_dict.get(confederation_key))) oereb_logo = ImageRecord(file_adapter.read(logo_dict.get(oereb_key))) canton_logo = ImageRecord(file_adapter.read(logo_dict.get(canton_key))) return { confederation_key: confederation_logo, oereb_key: oereb_logo, canton_key: canton_logo }
def test_get_logo_multilingual(language): Config._config = None Config.init('./tests/resources/test_config.yml', 'pyramid_oereb') Config.get('logo')['oereb'] = { 'de': 'pyramid_oereb/standard/logo_oereb_de.png', 'fr': 'pyramid_oereb/standard/logo_oereb_fr.png', 'it': 'pyramid_oereb/standard/logo_oereb_it.png' } logos = Config.get_logo_config(language=language) assert isinstance(logos, dict) logo_oereb = logos.get('oereb') if language is None: assert logo_oereb.content == FileAdapter().read( Config.get('logo').get('oereb').get('de')) else: assert logo_oereb.content == FileAdapter().read( Config.get('logo').get('oereb').get(language))
def test_get_logo_config(): Config._config = None Config.init('./tests/resources/test_config.yml', 'pyramid_oereb') logos = Config.get_logo_config() assert isinstance(logos, dict) logo_oereb = logos.get('oereb') assert isinstance(logo_oereb, ImageRecord) assert logo_oereb.content == FileAdapter().read( Config.get('logo').get('oereb'))
def test_get_image(): request = MockRequest() request.matchdict.update({ 'fosnr': '1234' }) webservice = Municipality(request) result = webservice.get_image() assert isinstance(result, Response) assert result.body == FileAdapter().read('tests/resources/python.svg')
def test_get_symbol(): request = DummyRequest() request.matchdict.update({ 'theme_code': 'ContaminatedSites', 'view_service_id': '1', 'type_code': 'CodeA' }) response = get_symbol(request) assert response.body == FileAdapter().read('tests/resources/symbol.png')
def _get_test_extract(glossary): date = datetime.datetime.now() file_adapter = FileAdapter() with pyramid_oereb_test_config(): view_service = ViewServiceRecord(u'http://geowms.bl.ch', 1, 1.0, {'de': u'http://geowms.bl.ch'}, None) real_estate = RealEstateRecord( u'RealEstate', 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 = Config.get('extract').get('base_data').get( 'methods').get('date') date_method = resolver.resolve(date_method_string) av_update_date = date_method(real_estate) base_data = Config.get_base_data(av_update_date) av_provider_method_string = Config.get('extract').get('base_data').get( 'methods').get('provider') av_provider_method = resolver.resolve(av_provider_method_string) cadaster_state = date theme = ThemeRecord(u'TEST', {'de': u'TEST TEXT'}) datasources = [DatasourceRecord(theme, date, office_record)] plr_cadastre_authority = Config.get_plr_cadastre_authority() embeddable = EmbeddableRecord(cadaster_state, plr_cadastre_authority, av_provider_method(real_estate), av_update_date, datasources) extract = ExtractRecord( real_estate, ImageRecord(file_adapter.read('tests/resources/python.svg')), ImageRecord(file_adapter.read('tests/resources/python.svg')), ImageRecord(file_adapter.read('tests/resources/python.svg')), ImageRecord(file_adapter.read('tests/resources/python.svg')), office_record, base_data, embeddable, exclusions_of_liability=[ ExclusionOfLiabilityRecord({'de': u'Haftungsausschluss'}, {'de': u'Test'}) ], glossaries=glossary, general_information={'de': u'Allgemeine Informationen'}, certification={'de': u'certification'}, certification_at_web={'de': u'certification_at_web'}, ) # 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
def test_get_image(): request = MockRequest() request.matchdict.update({ 'theme_code': 'ContaminatedSites', 'view_service_id': '1', 'type_code': 'CodeA' }) webservice = Symbol(request) result = webservice.get_image() assert isinstance(result, Response) assert result.body == FileAdapter().read('tests/resources/symbol.png')
def test_format_legend_entry(parameter): with pyramid_oereb_test_config(): renderer = Renderer(DummyRenderInfo()) renderer._language = u'de' renderer._params = parameter renderer._request = MockRequest() theme = ThemeRecord(u'ContaminatedSites', {u'de': u'Test'}) legend_entry = LegendEntryRecord( ImageRecord(FileAdapter().read('tests/resources/python.svg')), {u'de': u'Legendeneintrag'}, u'CodeA', u'type_code_list', theme, {'de': u'Subthema'}, u'Weiteres Thema', view_service_id=1 ) result = renderer.format_legend_entry(legend_entry) expected = { 'LegendText': renderer.get_multilingual_text({'de': 'Legendeneintrag'}), 'TypeCode': 'CodeA', 'TypeCodelist': 'type_code_list', 'Theme': renderer.format_theme(theme), 'SubTheme': 'Subthema', 'OtherTheme': 'Weiteres Thema' } if parameter.images: expected.update({ 'Symbol': ImageRecord(FileAdapter().read('tests/resources/python.svg')).encode() }) else: expected.update({ 'SymbolRef': 'http://example.com/image/symbol/{theme_code}/{view_service_id}/{code}.svg' .format( theme_code='ContaminatedSites', view_service_id=1, code='CodeA' ) }) assert isinstance(result, dict) assert result == expected
def test_get_symbol_ref(): record = LegendEntryRecord( ImageRecord(FileAdapter().read('tests/resources/logo_canton.png')), {'de': 'Test'}, 'CodeA', 'http://my.codelist.com/test.xml', ThemeRecord('ContaminatedSites', {'de': 'Belastete Standorte'}), view_service_id='1' ) with pyramid_oereb_test_config(): request = DummyRequest() url = urlparse(get_symbol_ref(request, record)) assert url.path == '/image/symbol/ContaminatedSites/1/CodeA.png'
def test_get_symbol_ref(theme_code): with pyramid_oereb_test_config(): request = MockRequest() record = LegendEntryRecord(ImageRecord( FileAdapter().read('tests/resources/python.svg')), {'de': 'Test'}, u'test', u'test', ThemeRecord(theme_code, {'de': 'Test'}), view_service_id=1) if theme_code == u'NotExistingTheme': with pytest.raises(HTTPServerError): Base.get_symbol_ref(request, record) else: ref = Base.get_symbol_ref(request, record) assert ref == 'http://example.com/image/symbol/{}/{}/{}.svg'.format( theme_code, record.view_service_id, record.type_code)
def test_ls(): base_path = os.path.abspath('./tests/resources') file_adapter = FileAdapter(base_path) dir_list = file_adapter.ls() assert isinstance(dir_list, list) assert len(dir_list) == 5 file_found = False dir_found = False for entry in dir_list: if entry[0] == 'test_config.yml': file_found = True assert entry[1].get('is_file') assert not entry[1].get('is_dir') if entry[0] == 'schema': dir_found = True assert not entry[1].get('is_file') assert entry[1].get('is_dir') assert file_found and dir_found
def test_validate_filetype_png_content(): content = FileAdapter().read('tests/resources/logo_canton.png') if sys.version_info.major == 2: content = bytearray(content) assert ImageRecord._validate_filetype(content) == ('png', 'image/png')
# -*- coding: utf-8 -*- from datetime import date, timedelta from sqlalchemy import create_engine from pyramid_oereb.lib import b64 from pyramid_oereb.lib.adapter import FileAdapter from pyramid_oereb.lib.config import Config file_adapter = FileAdapter() class DummyData(object): def __init__(self): self._engine = create_engine( Config.get('app_schema').get('db_connection')) def init(self): self._truncate() self._import_main() self._import_motorways_building_lines() self._import_contaminated_sites() self._import_land_use_plans() self._import_forest_perimeters() def _truncate(self): from pyramid_oereb.standard.models import main, contaminated_sites, \ land_use_plans, motorways_building_lines, forest_perimeters connection = self._engine.connect() trans = connection.begin()
def test_init(): base_path = os.path.abspath('.') file_adapter_1 = FileAdapter() assert file_adapter_1.cwd == base_path file_adapter_2 = FileAdapter('test') assert file_adapter_2.cwd == os.path.join(base_path, 'test')
def test_read_no_file(): base_path = os.path.abspath('./tests/resources') file_adapter = FileAdapter(base_path) with pytest.raises(IOError) as exc_info: file_adapter.read('plr119') assert 'Not a file:' in str(exc_info.value)
def test_read(): base_path = os.path.abspath('./tests/resources') file_adapter = FileAdapter(base_path) content = file_adapter.read('file_adapter_dummy.txt').decode('utf-8') assert content.startswith( 'If the content looks like this, the test has been successful.')
def test_render(parameter, glossaries_input, glossaries_expected): date = datetime.datetime.now() with pyramid_oereb_test_config(): view_service = ViewServiceRecord(u'http://geowms.bl.ch', 1, 1.0, {'de': u'http://geowms.bl.ch'}, None) real_estate = RealEstateRecord(u'RealEstate', 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 = Config.get('extract').get('base_data').get('methods').get('date') date_method = resolver.resolve(date_method_string) av_update_date = date_method(real_estate) base_data = Config.get_base_data(av_update_date) av_provider_method_string = Config.get('extract').get('base_data').get('methods').get('provider') av_provider_method = resolver.resolve(av_provider_method_string) cadaster_state = date theme = ThemeRecord(u'TEST', {'de': u'TEST TEXT'}) datasources = [DatasourceRecord(theme, date, office_record)] plr_cadastre_authority = Config.get_plr_cadastre_authority() embeddable = EmbeddableRecord( cadaster_state, plr_cadastre_authority, av_provider_method(real_estate), av_update_date, datasources ) extract = ExtractRecord( real_estate, ImageRecord(FileAdapter().read('tests/resources/logo_canton.png')), ImageRecord(FileAdapter().read('tests/resources/logo_canton.png')), ImageRecord(FileAdapter().read('tests/resources/logo_canton.png')), ImageRecord(FileAdapter().read('tests/resources/python.svg')), office_record, base_data, embeddable, exclusions_of_liability=[ ExclusionOfLiabilityRecord({'de': u'Haftungsausschluss'}, {'de': u'Test'}) ], glossaries=glossaries_input, general_information={'de': u'Allgemeine Informationen'}, certification={'de': u'certification'}, certification_at_web={'de': u'certification_at_web'}, ) 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': [], 'isReduced': True, 'PLRCadastreAuthority': renderer.format_office(office_record), 'BaseData': renderer.get_multilingual_text(Config.get_base_data(av_update_date)), 'RealEstate': renderer.format_real_estate(real_estate), 'Certification': [{'Language': 'de', 'Text': 'certification'}], 'CertificationAtWeb': [{'Language': 'de', 'Text': 'certification_at_web'}], 'GeneralInformation': [{'Language': 'de', 'Text': 'Allgemeine Informationen'}], 'QRCode': '1'.encode('utf-8'), 'ExclusionOfLiability': [{ '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': ImageRecord(FileAdapter().read('tests/resources/logo_canton.png')) .encode(), 'FederalLogo': ImageRecord(FileAdapter().read('tests/resources/logo_canton.png')) .encode(), 'CantonalLogo': ImageRecord(FileAdapter().read('tests/resources/logo_canton.png')) .encode(), 'MunicipalityLogo': ImageRecord(FileAdapter().read('tests/resources/python.svg')) .encode(), }) 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/municipality/2829.svg' }) assert result == expected
def test_validate_filetype_svg_content(): content = FileAdapter().read('tests/resources/python.svg') assert ImageRecord._validate_filetype(content) == ('svg', 'image/svg+xml')
def test_validate_filetype_png_content(): content = FileAdapter().read('tests/resources/logo_canton.png') assert ImageRecord._validate_filetype(content) == ('png', 'image/png')
def test_cd(): base_path = os.path.abspath('.') file_adapter = FileAdapter() file_adapter.cd('test') assert file_adapter.cwd == os.path.join(base_path, 'test')
def test_format_plr(parameter): with pyramid_oereb_test_config(): renderer = Renderer(DummyRenderInfo()) renderer._language = 'de' renderer._params = parameter renderer._request = MockRequest() document = DocumentRecord( 'Law', law_status(), datetime.date.today(), {u'de': u'Test Dokument'}, OfficeRecord({u'de': u'BUD'}), {'de': 'http://mein.dokument.ch'} ) if parameter.flavour == 'reduced': documents = [document] else: documents = None theme = ThemeRecord(u'ContaminatedSites', {u'de': u'Test theme'}) 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('http://geowms.bl.ch', 1, 1.0, {'de': u'http://geowms.bl.ch'}, [legend_entry]) geometry = GeometryRecord(law_status(), datetime.date.today(), Point(1, 1)) plr = PlrRecord( theme, {'de': 'Test'}, law_status(), datetime.date.today(), office, ImageRecord(FileAdapter().read('tests/resources/python.svg')), view_service, [geometry], sub_theme={ 'de': 'Subtopic' }, other_theme='Additional topic', type_code='CodeA', type_code_list='TypeCodeList', documents=documents, view_service_id=1 ) plr.part_in_percent = 0.5 if parameter.flavour == 'full': with pytest.raises(ValueError): renderer.format_plr([plr]) else: result = renderer.format_plr([plr]) assert isinstance(result, list) assert len(result) == 1 assert isinstance(result[0], dict) expected = { 'Information': renderer.get_multilingual_text(plr.information), 'Theme': renderer.format_theme(plr.theme), 'Lawstatus': { 'Code': 'inForce', 'Text': {'Language': 'de', 'Text': 'In Kraft'} }, 'ResponsibleOffice': renderer.format_office(plr.responsible_office), 'Map': renderer.format_map(plr.view_service), 'SubTheme': 'Subtopic', 'OtherTheme': 'Additional topic', '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='ContaminatedSites', view_service_id=1, code='CodeA' ) }) assert result[0] == expected