diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c204061..c6164df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: pipx install flake8 - name: Lint package - run: flake8 src examples + run: flake8 src examples test - name: Typecheck package run: mypy src diff --git a/test/conftest.py b/test/conftest.py index 9d97e4b..ccb5dbf 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -1,30 +1,36 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. -from io import StringIO +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. from pathlib import Path import sys import sysconfig import uuid from textwrap import dedent +import pytest + + SRC_DIR = (Path(__file__) / '..' / '..').resolve() + BUILD_DIR = "build/lib.{}-{}.{}".format(sysconfig.get_platform(), sys.version_info[0], sys.version_info[1]) + + if not (SRC_DIR / BUILD_DIR).exists(): BUILD_DIR = "build/lib.{}-{}".format(sysconfig.get_platform(), - sys.implementation.cache_tag) + sys.implementation.cache_tag) if (SRC_DIR / BUILD_DIR).exists(): sys.path.insert(0, str(SRC_DIR)) sys.path.insert(0, str(SRC_DIR / BUILD_DIR)) -import pytest -import osmium as o +import osmium # noqa + @pytest.fixture def test_data_dir(): @@ -52,27 +58,30 @@ def _mkfile(data): return _mkfile + @pytest.fixture def opl_buffer(to_opl): def _mkbuffer(data): - return o.io.FileBuffer(to_opl(data).encode('utf-8'), 'opl') + return osmium.io.FileBuffer(to_opl(data).encode('utf-8'), 'opl') return _mkbuffer + @pytest.fixture def opl_reader(opl_buffer): def _mkbuffer(data): - return o.io.Reader(opl_buffer(data)) + return osmium.io.Reader(opl_buffer(data)) return _mkbuffer + @pytest.fixture def simple_handler(to_opl): def _run(data, node=None, way=None, relation=None, area=None, locations=False): - handler = o.make_simple_handler(node=node, way=way, relation=relation, area=area) + handler = osmium.make_simple_handler(node=node, way=way, relation=relation, area=area) handler.apply_buffer(to_opl(data).encode('utf-8'), 'opl', locations=locations) return _run diff --git a/test/helpers.py b/test/helpers.py index 4839526..47bbfe6 100644 --- a/test/helpers.py +++ b/test/helpers.py @@ -1,12 +1,20 @@ +# SPDX-License-Identifier: BSD-2-Clause +# +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) +# +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. """ Provides some helper functions for test. """ from datetime import datetime, timezone import osmium + def mkdate(*args): return datetime(*args, tzinfo=timezone.utc) + class CountingHandler(osmium.SimpleHandler): def __init__(self): diff --git a/test/test_area.py b/test/test_area.py index e0c509d..de837b4 100644 --- a/test/test_area.py +++ b/test/test_area.py @@ -1,45 +1,48 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. from pathlib import Path -import osmium as o +import osmium from helpers import CountingHandler + TEST_FILE = str((Path(__file__) / '..' / 'example-test.pbf').resolve()) + def test_area_handler(): - area = o.area.AreaManager() + area = osmium.area.AreaManager() - o.apply(o.io.Reader(TEST_FILE), area.first_pass_handler()) + osmium.apply(osmium.io.Reader(TEST_FILE), area.first_pass_handler()) ch_area = CountingHandler() ch_others = CountingHandler() - lh = o.NodeLocationsForWays(o.index.create_map("flex_mem")) + lh = osmium.NodeLocationsForWays(osmium.index.create_map("flex_mem")) lh.ignore_errors() - o.apply(o.io.Reader(TEST_FILE), lh, - ch_others, area.second_pass_handler(ch_area)) + osmium.apply(osmium.io.Reader(TEST_FILE), lh, + ch_others, area.second_pass_handler(ch_area)) assert ch_area.counts == [0, 0, 0, 5239] assert ch_others.counts == [211100, 10315, 244, 0] def test_area_buffer_handler(): - area = o.area.AreaManager() + area = osmium.area.AreaManager() - o.apply(o.io.Reader(TEST_FILE), area.first_pass_handler()) + osmium.apply(osmium.io.Reader(TEST_FILE), area.first_pass_handler()) - lh = o.NodeLocationsForWays(o.index.create_map("flex_mem")) + lh = osmium.NodeLocationsForWays(osmium.index.create_map("flex_mem")) lh.ignore_errors() - buf = o.BufferIterator() + buf = osmium.BufferIterator() - o.apply(o.io.Reader(TEST_FILE), lh, area.second_pass_to_buffer(buf)) + osmium.apply(osmium.io.Reader(TEST_FILE), lh, area.second_pass_to_buffer(buf)) counts = 0 for obj in buf: diff --git a/test/test_back_reference_writer.py b/test/test_back_reference_writer.py index 8ab48e7..c906a43 100644 --- a/test/test_back_reference_writer.py +++ b/test/test_back_reference_writer.py @@ -2,14 +2,15 @@ # # This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann and others. +# Copyright (C) 2025 Sarah Hoffmann and others. # For a full list of authors see the git log. import pytest -import osmium as o +import osmium from helpers import IDCollector + def test_simple_way(test_data, tmp_path): ref_file = test_data('\n'.join((f"n{i} x2 y3" for i in range(10)))) @@ -19,11 +20,11 @@ class TestWay: outfile = str(tmp_path / 'test.osm') - with o.BackReferenceWriter(outfile, ref_file) as writer: + with osmium.BackReferenceWriter(outfile, ref_file) as writer: writer.add_way(TestWay()) ids = IDCollector() - o.apply(outfile, ids) + osmium.apply(outfile, ids) assert ids.nodes == [3, 5, 6] assert ids.ways == [34] @@ -35,7 +36,7 @@ def test_do_not_write_on_exception(test_data, tmp_path): outfile = tmp_path / 'test.osm' with pytest.raises(RuntimeError, match="inner error"): - with o.BackReferenceWriter(str(outfile), ref_file) as writer: + with osmium.BackReferenceWriter(str(outfile), ref_file): raise RuntimeError("inner error") assert not outfile.exists() diff --git a/test/test_dangling_references.py b/test/test_dangling_references.py index e524d2c..c949e28 100644 --- a/test/test_dangling_references.py +++ b/test/test_dangling_references.py @@ -1,16 +1,16 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. - +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. from pathlib import Path import pytest +import osmium TEST_DIR = (Path(__file__) / '..').resolve() -import osmium as o class DanglingReferenceBase: """ Base class for tests that try to keep a reference to the object @@ -27,8 +27,8 @@ def keep(self, obj, func): self.refkeeper.append((obj, func)) def test_keep_reference(self): - h = o.make_simple_handler(node=self.node, way=self.way, - relation=self.relation, area=self.area) + h = osmium.make_simple_handler(node=self.node, way=self.way, + relation=self.relation, area=self.area) h.apply_file(TEST_DIR / 'example-test.osc') assert self.refkeeper @@ -40,7 +40,7 @@ def test_keep_reference(self): repr(obj) def test_keep_reference_generator(self): - for obj in o.FileProcessor(TEST_DIR / 'example-test.osc').with_areas(): + for obj in osmium.FileProcessor(TEST_DIR / 'example-test.osc').with_areas(): if obj.type_str() == 'n' and self.node is not None: self.node(obj) elif obj.type_str() == 'w' and self.way is not None: @@ -65,63 +65,75 @@ class TestKeepNodeRef(DanglingReferenceBase): def node(self, n): self.keep(n, lambda n: n.id) + class TestKeepWayRef(DanglingReferenceBase): def way(self, w): self.keep(w, lambda n: n.id) + class TestKeepRelationRef(DanglingReferenceBase): def relation(self, r): self.keep(r, lambda n: n.id) + class TestKeepAreaRef(DanglingReferenceBase): def area(self, a): self.keep(a, lambda n: n.id) + class TestKeepNodeTagsRef(DanglingReferenceBase): def node(self, n): self.keep(n.tags, lambda t: 'foo' in t) + class TestKeepWayTagsRef(DanglingReferenceBase): def way(self, w): self.keep(w.tags, lambda t: 'foo' in t) + class TestKeepRelationTagsRef(DanglingReferenceBase): def relation(self, r): self.keep(r.tags, lambda t: 'foo' in t) + class TestKeepAreaTagsRef(DanglingReferenceBase): def area(self, a): self.keep(a.tags, lambda t: 'foo' in t) + class TestKeepTagListIterator(DanglingReferenceBase): def node(self, n): self.keep(n.tags.__iter__(), lambda t: next(t)) + class TestKeepOuterRingIterator(DanglingReferenceBase): def area(self, r): self.keep(r.outer_rings(), lambda t: next(t)) + class TestKeepOuterRing(DanglingReferenceBase): def area(self, r): for ring in r.outer_rings(): self.keep(ring, lambda t: len(t)) + class TestKeepInnerRingIterator(DanglingReferenceBase): def area(self, r): for ring in r.outer_rings(): self.keep(r.inner_rings(ring), lambda t: next(t)) + class TestKeepInnerRing(DanglingReferenceBase): def area(self, r): @@ -129,13 +141,13 @@ def area(self, r): for inner in r.inner_rings(outer): self.keep(inner, lambda t: len(t)) + class TestKeepRelationMemberIterator(DanglingReferenceBase): def relation(self, r): self.keep(r.members, lambda t: next(t)) - class NotADanglingReferenceBase: """ Base class for tests that ensure that the callback does not bail out because of dangling references when POD types are @@ -152,8 +164,8 @@ def keep(self, obj, func): self.refkeeper.append((obj, func)) def test_keep_reference(self): - h = o.make_simple_handler(node=self.node, way=self.way, - relation=self.relation, area=self.area) + h = osmium.make_simple_handler(node=self.node, way=self.way, + relation=self.relation, area=self.area) h.apply_file(TEST_DIR / 'example-test.pbf') assert self.refkeeper @@ -161,7 +173,7 @@ def test_keep_reference(self): func(obj) def test_keep_reference_generator(self): - for obj in o.FileProcessor(TEST_DIR / 'example-test.pbf').with_areas(): + for obj in osmium.FileProcessor(TEST_DIR / 'example-test.pbf').with_areas(): if obj.is_node() and self.node is not None: self.node(obj) elif obj.is_way() and self.way is not None: @@ -180,7 +192,8 @@ def test_keep_reference_generator(self): class TestKeepLocation(NotADanglingReferenceBase): def node(self, n): - self.keep(n.location, lambda l: l.x) + self.keep(n.location, lambda loc: loc.x) + class TestKeepNode(NotADanglingReferenceBase): @@ -188,6 +201,7 @@ def node(self, n): for t in n.tags: self.keep(t, lambda t: t.k) + class TestKeepMember(NotADanglingReferenceBase): def relation(self, r): diff --git a/test/test_empty_tag_filter.py b/test/test_empty_tag_filter.py index 10a933a..e0ca92e 100644 --- a/test/test_empty_tag_filter.py +++ b/test/test_empty_tag_filter.py @@ -1,14 +1,15 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann. -import osmium as o - +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import pytest +import osmium from helpers import IDCollector + @pytest.fixture def reader(opl_reader): return opl_reader("""\ @@ -22,10 +23,11 @@ def reader(opl_reader): c223 """) + def test_filter_default_config(reader): pre = IDCollector() post = IDCollector() - o.apply(reader, pre, o.filter.EmptyTagFilter(), post) + osmium.apply(reader, pre, osmium.filter.EmptyTagFilter(), post) assert pre.nodes == [1, 2] assert post.nodes == [2] @@ -40,7 +42,9 @@ def test_filter_default_config(reader): def test_filter_restrict_entity(reader): pre = IDCollector() post = IDCollector() - o.apply(reader, pre, o.filter.EmptyTagFilter().enable_for(o.osm.WAY | o.osm.RELATION), post) + osmium.apply(reader, pre, + osmium.filter.EmptyTagFilter().enable_for(osmium.osm.WAY | osmium.osm.RELATION), + post) assert pre.nodes == [1, 2] assert post.nodes == [1, 2] @@ -53,10 +57,10 @@ def test_filter_restrict_entity(reader): def test_filter_chained(reader): pre = IDCollector() post = IDCollector() - o.apply(reader, pre, - o.filter.EmptyTagFilter().enable_for(o.osm.NODE), - o.filter.EmptyTagFilter().enable_for(o.osm.WAY), - post) + osmium.apply(reader, pre, + osmium.filter.EmptyTagFilter().enable_for(osmium.osm.NODE), + osmium.filter.EmptyTagFilter().enable_for(osmium.osm.WAY), + post) assert pre.nodes == [1, 2] assert post.nodes == [2] diff --git a/test/test_entity_filter.py b/test/test_entity_filter.py index 016408c..42b072c 100644 --- a/test/test_entity_filter.py +++ b/test/test_entity_filter.py @@ -2,17 +2,17 @@ # # This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann and others. +# Copyright (C) 2025 Sarah Hoffmann and others. # For a full list of authors see the git log. import pytest -import osmium as o - +import osmium from helpers import CountingHandler -@pytest.mark.parametrize('ent,cnt', [(o.osm.NODE, (1, 0, 0)), - (o.osm.NODE | o.osm.WAY, (1, 1, 0)), - (o.osm.ALL, (1, 1, 1))]) + +@pytest.mark.parametrize('ent,cnt', [(osmium.osm.NODE, (1, 0, 0)), + (osmium.osm.NODE | osmium.osm.WAY, (1, 1, 0)), + (osmium.osm.ALL, (1, 1, 1))]) def test_entity_filter_simple(opl_reader, ent, cnt): data = """\ n1 Ttype=node @@ -22,6 +22,6 @@ def test_entity_filter_simple(opl_reader, ent, cnt): processed = CountingHandler() - o.apply(opl_reader(data), o.filter.EntityFilter(ent), processed) + osmium.apply(opl_reader(data), osmium.filter.EntityFilter(ent), processed) assert list(cnt) == processed.counts[:3] diff --git a/test/test_examples.py b/test/test_examples.py index 5b8e913..b3f1bf2 100644 --- a/test/test_examples.py +++ b/test/test_examples.py @@ -1,13 +1,15 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. """ Tests for all examples. """ from pathlib import Path + TEST_DIR = (Path(__file__) / '..').resolve() TEST_FILE = TEST_DIR / 'example-test.pbf' TEST_DIFF = TEST_DIR / 'example-test.osc' @@ -56,14 +58,14 @@ def test_osm_diff_stats(capsys): output = capsys.readouterr().out.splitlines() assert output == ['Nodes added: 305', - 'Nodes modified: 192', - 'Nodes deleted: 20', - 'Ways added: 31', - 'Ways modified: 93', - 'Ways deleted: 0', - 'Relations added: 0', - 'Relations modified: 0', - 'Relations deleted: 0'] + 'Nodes modified: 192', + 'Nodes deleted: 20', + 'Ways added: 31', + 'Ways modified: 93', + 'Ways deleted: 0', + 'Relations added: 0', + 'Relations modified: 0', + 'Relations deleted: 0'] def test_osm_file_stats(capsys): diff --git a/test/test_file_processor.py b/test/test_file_processor.py index c3d90ab..32f25e0 100644 --- a/test/test_file_processor.py +++ b/test/test_file_processor.py @@ -2,28 +2,31 @@ # # This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann and others. +# Copyright (C) 2025 Sarah Hoffmann and others. # For a full list of authors see the git log. import pytest -import osmium as o +import osmium from helpers import IDCollector + @pytest.mark.parametrize('init', [None, 1]) def test_file_processor_bad_init(init): with pytest.raises(TypeError): - for obj in o.FileProcessor(init): + for obj in osmium.FileProcessor(init): pass + def test_simple_generator(opl_buffer): count = 0 - for obj in o.FileProcessor(opl_buffer('n1 x5 y5')): + for obj in osmium.FileProcessor(opl_buffer('n1 x5 y5')): assert obj.type_str() == 'n' assert obj.id == 1 count += 1 assert count == 1 + def test_generator_with_location(opl_buffer): data = opl_buffer("""\ n1 x10 y20 @@ -32,7 +35,7 @@ def test_generator_with_location(opl_buffer): """) count = 0 - for obj in o.FileProcessor(data).with_locations(): + for obj in osmium.FileProcessor(data).with_locations(): count += 1 if obj.type_str() == 'w': assert len(obj.nodes) == 2 @@ -42,6 +45,7 @@ def test_generator_with_location(opl_buffer): assert count == 3 + def test_generator_with_areas(opl_buffer): data = opl_buffer("""\ n10 x3 y3 @@ -52,7 +56,7 @@ def test_generator_with_areas(opl_buffer): """) count = 0 - for obj in o.FileProcessor(data).with_areas(): + for obj in osmium.FileProcessor(data).with_areas(): if obj.type_str() == 'a': count += 1 assert obj.from_way() @@ -73,14 +77,15 @@ def test_generator_with_areas_with_filter(opl_buffer): """) count = 0 - for obj in o.FileProcessor(data)\ - .with_areas()\ - .with_filter(o.filter.EntityFilter(o.osm.AREA)): + for obj in osmium.FileProcessor(data)\ + .with_areas()\ + .with_filter(osmium.filter.EntityFilter(osmium.osm.AREA)): assert obj.is_area() count += 1 assert count == 1 + def test_generator_with_areas_with_area_filter(opl_buffer): data = opl_buffer("""\ n10 x3 y3 @@ -94,9 +99,9 @@ def test_generator_with_areas_with_area_filter(opl_buffer): """) count = 0 - for obj in o.FileProcessor(data)\ - .with_areas(o.filter.KeyFilter('building'))\ - .with_filter(o.filter.EntityFilter(o.osm.AREA)): + for obj in osmium.FileProcessor(data)\ + .with_areas(osmium.filter.KeyFilter('building'))\ + .with_filter(osmium.filter.EntityFilter(osmium.osm.AREA)): assert obj.is_area() assert obj.id == 3 count += 1 @@ -111,13 +116,14 @@ def test_generator_with_filter(opl_buffer): """) count = 0 - for obj in o.FileProcessor(data).with_filter(o.filter.EmptyTagFilter()): + for obj in osmium.FileProcessor(data).with_filter(osmium.filter.EmptyTagFilter()): count += 1 assert obj.type_str() == 'n' assert obj.id == 11 assert count == 1 + def test_file_processor_header(tmp_path): fn = tmp_path / 'empty.xml' fn.write_text(""" @@ -126,15 +132,16 @@ def test_file_processor_header(tmp_path): """) - h = o.FileProcessor(fn).header + h = osmium.FileProcessor(fn).header assert not h.has_multiple_object_versions assert h.box().valid() assert h.box().size() == 64800.0 + def test_file_processor_access_nodestore(opl_buffer): - fp = o.FileProcessor(opl_buffer('n56 x3 y-3'))\ - .with_locations(o.index.create_map('sparse_mem_map')) + fp = osmium.FileProcessor(opl_buffer('n56 x3 y-3'))\ + .with_locations(osmium.index.create_map('sparse_mem_map')) for _ in fp: pass @@ -142,9 +149,10 @@ def test_file_processor_access_nodestore(opl_buffer): assert fp.node_location_storage.get(56).lat == -3 assert fp.node_location_storage.get(56).lon == 3 + def test_file_processor_bad_location_type(opl_buffer): with pytest.raises(TypeError, match='LocationTable'): - o.FileProcessor(opl_buffer('n56 x3 y-3')).with_locations(67) + osmium.FileProcessor(opl_buffer('n56 x3 y-3')).with_locations(67) def test_propagate_data_from_filters(opl_buffer): @@ -153,14 +161,14 @@ def node(self, n): n.saved = 'test' return False - fp = o.FileProcessor(opl_buffer('n56 x3 y-3')).with_filter(MyFilter()) + fp = osmium.FileProcessor(opl_buffer('n56 x3 y-3')).with_filter(MyFilter()) for obj in fp: assert obj.saved == 'test' def test_simple_zip(opl_buffer): - fp1 = o.FileProcessor(opl_buffer("""\ + fp1 = osmium.FileProcessor(opl_buffer("""\ n1 n3 n5 @@ -168,7 +176,7 @@ def test_simple_zip(opl_buffer): r1 Mw1@ """)) - fp2 = o.FileProcessor(opl_buffer("""\ + fp2 = osmium.FileProcessor(opl_buffer("""\ n2 n3 n456 @@ -177,18 +185,18 @@ def test_simple_zip(opl_buffer): """)) results = [] - for o1, o2 in o.zip_processors(fp1, fp2): + for o1, o2 in osmium.zip_processors(fp1, fp2): results.append(((None if o1 is None else o1.type_str() + str(o1.id)), (None if o2 is None else o2.type_str() + str(o2.id)))) assert results == [('n1', None), - (None, 'n2'), - ('n3', 'n3'), - ('n5', None), - (None, 'n456'), - ('w10', None), - (None, 'w12'), - ('r1', 'r1')] + (None, 'n2'), + ('n3', 'n3'), + ('n5', None), + (None, 'n456'), + ('w10', None), + (None, 'w12'), + ('r1', 'r1')] def test_filtered_handler_python(opl_buffer): @@ -204,9 +212,9 @@ def test_filtered_handler_python(opl_buffer): processed = [] - fp = o.FileProcessor(data)\ - .handler_for_filtered(ids)\ - .with_filter(o.filter.EmptyTagFilter()) + fp = osmium.FileProcessor(data)\ + .handler_for_filtered(ids)\ + .with_filter(osmium.filter.EmptyTagFilter()) for obj in fp: processed.append(f"{obj.type_str()}{obj.id}") @@ -228,10 +236,10 @@ def test_filtered_handler_basehandler(opl_buffer, tmp_path): testf = tmp_path / 'test.opl' - with o.SimpleWriter(str(testf)) as writer: - fp = o.FileProcessor(data)\ + with osmium.SimpleWriter(str(testf)) as writer: + fp = osmium.FileProcessor(data)\ .handler_for_filtered(writer)\ - .with_filter(o.filter.EmptyTagFilter()) + .with_filter(osmium.filter.EmptyTagFilter()) processed = [] for obj in fp: @@ -241,9 +249,8 @@ def test_filtered_handler_basehandler(opl_buffer, tmp_path): ids = IDCollector() - o.apply(testf, ids) + osmium.apply(testf, ids) assert ids.nodes == [3] assert ids.ways == [2] assert ids.relations == [4] - diff --git a/test/test_forward_reference_writer.py b/test/test_forward_reference_writer.py index 198920d..5de61ee 100644 --- a/test/test_forward_reference_writer.py +++ b/test/test_forward_reference_writer.py @@ -2,14 +2,15 @@ # # This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann and others. +# Copyright (C) 2025 Sarah Hoffmann and others. # For a full list of authors see the git log. import pytest -import osmium as o +import osmium from helpers import IDCollector + @pytest.fixture def ref_file(test_data): return test_data("""\ @@ -33,12 +34,12 @@ def __init__(self, nid): def test_simple_forward_no_back_reference(ref_file, tmp_path): outfile = str(tmp_path / 'test.osm') - with o.ForwardReferenceWriter(outfile, ref_file, back_references=False) as writer: + with osmium.ForwardReferenceWriter(outfile, ref_file, back_references=False) as writer: writer.add_node(DummyNode(2)) writer.add_node(DummyNode(99)) ids = IDCollector() - o.apply(outfile, ids) + osmium.apply(outfile, ids) assert ids.nodes == [2, 99] assert ids.ways == [12] @@ -48,15 +49,15 @@ def test_simple_forward_no_back_reference(ref_file, tmp_path): def test_simple_forward_with_back_reference(ref_file, tmp_path): outfile = str(tmp_path / 'test.osm') - with o.ForwardReferenceWriter(outfile, ref_file) as writer: + with osmium.ForwardReferenceWriter(outfile, ref_file) as writer: writer.add_node(DummyNode(2)) writer.add_node(DummyNode(99)) ids = IDCollector() - for obj in o.FileProcessor(outfile)\ - .with_filter(ids)\ - .with_filter(o.filter.EntityFilter(o.osm.NODE)): + for obj in osmium.FileProcessor(outfile)\ + .with_filter(ids)\ + .with_filter(osmium.filter.EntityFilter(osmium.osm.NODE)): if obj.id in (2, 99): assert obj.lat == 4 assert obj.lon == 3 diff --git a/test/test_geo_interface_filter.py b/test/test_geo_interface_filter.py index 7bb2386..a16f3a4 100644 --- a/test/test_geo_interface_filter.py +++ b/test/test_geo_interface_filter.py @@ -2,17 +2,17 @@ # # This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann and others. +# Copyright (C) 2025 Sarah Hoffmann and others. # For a full list of authors see the git log. import pytest -import osmium as o - +import osmium from helpers import IDCollector + def test_node_geometry(opl_buffer): - fp = o.FileProcessor(opl_buffer("n23 x3 y4"))\ - .with_filter(o.filter.GeoInterfaceFilter()) + fp = osmium.FileProcessor(opl_buffer("n23 x3 y4"))\ + .with_filter(osmium.filter.GeoInterfaceFilter()) for n in fp: assert n.__geo_interface__ == \ @@ -31,17 +31,17 @@ def test_way_geometry(opl_buffer): w1 Nn1,n2 """ - fp = o.FileProcessor(opl_buffer(data))\ - .with_locations()\ - .with_filter(o.filter.EntityFilter(o.osm.WAY))\ - .with_filter(o.filter.GeoInterfaceFilter()) + fp = osmium.FileProcessor(opl_buffer(data))\ + .with_locations()\ + .with_filter(osmium.filter.EntityFilter(osmium.osm.WAY))\ + .with_filter(osmium.filter.GeoInterfaceFilter()) for w in fp: assert w.__geo_interface__ == \ - dict(type='Feature', properties={}, - geometry=dict(type='LineString', - coordinates=[[pytest.approx(0.001), pytest.approx(0)], - [pytest.approx(0.002), pytest.approx(0)]])) + dict(type='Feature', properties={}, + geometry=dict(type='LineString', + coordinates=[[pytest.approx(0.001), pytest.approx(0)], + [pytest.approx(0.002), pytest.approx(0)]])) break else: assert False @@ -57,20 +57,20 @@ def test_area_geometry(opl_buffer): r1 Ttype=multipolygon Mw1@,w2@ """ - fp = o.FileProcessor(opl_buffer(data))\ - .with_areas()\ - .with_filter(o.filter.GeoInterfaceFilter()) + fp = osmium.FileProcessor(opl_buffer(data))\ + .with_areas()\ + .with_filter(osmium.filter.GeoInterfaceFilter()) for r in fp: print(r) if r.is_area(): assert r.__geo_interface__ == \ - dict(type='Feature', properties={}, - geometry=dict(type='MultiPolygon', - coordinates=[[[[pytest.approx(0.001), pytest.approx(0)], - [pytest.approx(0.002), pytest.approx(0)], - [pytest.approx(0.001), pytest.approx(0.001)], - [pytest.approx(0.001), pytest.approx(0)]]]])) + dict(type='Feature', properties={}, + geometry=dict(type='MultiPolygon', + coordinates=[[[[pytest.approx(0.001), pytest.approx(0)], + [pytest.approx(0.002), pytest.approx(0)], + [pytest.approx(0.001), pytest.approx(0.001)], + [pytest.approx(0.001), pytest.approx(0)]]]])) break else: assert False @@ -80,21 +80,22 @@ def test_area_geometry_without_drop(opl_reader): data = """\ n1 x0.001 y0 n2 x0.002 y0 - n3 + n3 """ ids = IDCollector() - o.apply(opl_reader(data), o.filter.GeoInterfaceFilter(), ids) + osmium.apply(opl_reader(data), osmium.filter.GeoInterfaceFilter(), ids) assert ids.nodes == [1, 2] ids = IDCollector() - o.apply(opl_reader(data), o.filter.GeoInterfaceFilter(drop_invalid_geometries=False), ids) + osmium.apply(opl_reader(data), + osmium.filter.GeoInterfaceFilter(drop_invalid_geometries=False), + ids) assert ids.nodes == [1, 2, 3] - def test_property_tag_filter(opl_buffer): data = """\ n1 x0.001 y0 Ta=1,b=1,c=1,d=1 @@ -102,8 +103,8 @@ def test_property_tag_filter(opl_buffer): n3 x0.001 y0 Ta=1,c=3 """ - fp = o.FileProcessor(opl_buffer(data))\ - .with_filter(o.filter.GeoInterfaceFilter(tags=['a', 'b'])) + fp = osmium.FileProcessor(opl_buffer(data))\ + .with_filter(osmium.filter.GeoInterfaceFilter(tags=['a', 'b'])) count = 0 for obj in fp: diff --git a/test/test_geom.py b/test/test_geom.py index 6a9c48d..2e97c6f 100644 --- a/test/test_geom.py +++ b/test/test_geom.py @@ -1,25 +1,28 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import json import pytest -import osmium as o +import osmium import osmium.geom -wkbfab = o.geom.WKBFactory() +wkbfab = osmium.geom.WKBFactory() + @pytest.fixture def node_geom(test_data): def _run(factory, data='n1 x-23.3 y28.0'): geoms = [] + def _mk_point(node): geoms.append(factory.create_point(node)) - handler = o.make_simple_handler(node=_mk_point) + handler = osmium.make_simple_handler(node=_mk_point) handler.apply_file(test_data(data)) assert len(geoms) == 1 @@ -29,7 +32,7 @@ def _mk_point(node): def test_wkb_create_node(node_geom): - wkb = node_geom(o.geom.WKBFactory()) + wkb = node_geom(osmium.geom.WKBFactory()) if wkb.startswith('01'): assert wkb.startswith('0101000000') else: @@ -37,12 +40,12 @@ def test_wkb_create_node(node_geom): def test_wkt_create_node(node_geom): - wkt = node_geom(o.geom.WKTFactory()) + wkt = node_geom(osmium.geom.WKTFactory()) assert wkt.startswith('POINT(') def test_geojson_create_node(node_geom): - geom = node_geom(o.geom.GeoJSONFactory()) + geom = node_geom(osmium.geom.GeoJSONFactory()) geom = json.loads(geom) assert geom['type'], 'Point' @@ -53,14 +56,15 @@ def way_geom(test_data): def _run(factory): opl = test_data(['n1 x0 y0', 'n2 x1 y0', 'n3 x0 y1', 'w1 Nn1,n2,n3']) geoms = [] + def _mk_way(w): geoms.append(factory.create_linestring(w)) - geoms.append(factory.create_linestring(w, - direction=o.geom.direction.BACKWARD)) - geoms.append(factory.create_linestring(w, - use_nodes=o.geom.use_nodes.ALL)) + geoms.append(factory.create_linestring( + w, direction=osmium.geom.direction.BACKWARD)) + geoms.append(factory.create_linestring( + w, use_nodes=osmium.geom.use_nodes.ALL)) - handler = o.make_simple_handler(way=_mk_way) + handler = osmium.make_simple_handler(way=_mk_way) handler.apply_file(opl, locations=True) assert len(geoms) == 3 @@ -70,7 +74,7 @@ def _mk_way(w): def test_wkb_create_way(way_geom): - wkbs = way_geom(o.geom.WKBFactory()) + wkbs = way_geom(osmium.geom.WKBFactory()) for wkb in wkbs: if wkb.startswith('01'): @@ -78,13 +82,15 @@ def test_wkb_create_way(way_geom): else: assert wkb.startswith('00') + def test_wkt_create_way(way_geom): - wkts = way_geom(o.geom.WKTFactory()) + wkts = way_geom(osmium.geom.WKTFactory()) assert all(wkt.startswith('LINESTRING(') for wkt in wkts) + def test_geojson_create_way(way_geom): - geoms = way_geom(o.geom.GeoJSONFactory()) + geoms = way_geom(osmium.geom.GeoJSONFactory()) assert all(json.loads(geom)['type'] == 'LineString' for geom in geoms) @@ -95,10 +101,11 @@ def area_geom(test_data): def _run(factory): opl = test_data(['n1 x0 y0', 'n2 x1 y0', 'n3 x0 y1', 'w23 Nn1,n2,n3,n1 Tarea=yes']) geoms = [] + def _mk_area(a): geoms.append(factory.create_multipolygon(a)) - handler = o.make_simple_handler(area=_mk_area) + handler = osmium.make_simple_handler(area=_mk_area) handler.apply_file(opl, locations=True) assert len(geoms) == 1 @@ -108,7 +115,7 @@ def _mk_area(a): def test_wkb_create_poly(area_geom): - wkb = area_geom(o.geom.WKBFactory()) + wkb = area_geom(osmium.geom.WKBFactory()) if wkb.startswith('01'): assert wkb.startswith('010600000001'), "wkb: " + wkb else: @@ -116,30 +123,30 @@ def test_wkb_create_poly(area_geom): def test_wkt_create_poly(area_geom): - wkt = area_geom(o.geom.WKTFactory()) + wkt = area_geom(osmium.geom.WKTFactory()) assert wkt.startswith('MULTIPOLYGON(') def test_geojson_create_poly(area_geom): - geom = area_geom(o.geom.GeoJSONFactory()) + geom = area_geom(osmium.geom.GeoJSONFactory()) geom = json.loads(geom) assert geom['type'] == 'MultiPolygon' def test_lonlat_to_mercator(): - c = o.geom.lonlat_to_mercator(o.geom.Coordinates(3.4,-7.3)) + c = osmium.geom.lonlat_to_mercator(osmium.geom.Coordinates(3.4, -7.3)) assert c.x == pytest.approx(378486.2686971) assert c.y == pytest.approx(-814839.8325696) def test_mercator_lonlat(): - c = o.geom.mercator_to_lonlat(o.geom.Coordinates(0.03,10.2)) + c = osmium.geom.mercator_to_lonlat(osmium.geom.Coordinates(0.03, 10.2)) assert c.x == pytest.approx(0.00000026, rel=1e-1) assert c.y == pytest.approx(0.00009162, rel=1e-1) def test_coordinate_from_location(): - c = o.geom.Coordinates(o.osm.Location(10.0, -3.0)) + c = osmium.geom.Coordinates(osmium.osm.Location(10.0, -3.0)) assert c.x == pytest.approx(10.0) assert c.y == pytest.approx(-3.0) @@ -148,10 +155,11 @@ def test_haversine(): data = ['n1 x0 y0', 'n2 x1 y0', 'n3 x0 y1', 'w1 Nn1,n2,n3'] results = [] + def call_haversine(w): - results.append(o.geom.haversine_distance(w.nodes)) + results.append(osmium.geom.haversine_distance(w.nodes)) - handler = o.make_simple_handler(way=call_haversine) + handler = osmium.make_simple_handler(way=call_haversine) handler.apply_buffer('\n'.join(data).encode('utf-8'), 'opl', locations=True) assert 1 == len(results) @@ -162,22 +170,25 @@ def test_haversine_invalid_object(): data = ['n1 x0 y0', 'n2 x1 y0', 'n3 x0 y1', 'w1 Nn1,n2,n3'] results = [] + def call_haversine(w): results.append(w.nodes) - handler = o.make_simple_handler(way=call_haversine) + handler = osmium.make_simple_handler(way=call_haversine) handler.apply_buffer('\n'.join(data).encode('utf-8'), 'opl', locations=True) assert results with pytest.raises(RuntimeError, match="removed OSM object"): - o.geom.haversine_distance(results[0]) + osmium.geom.haversine_distance(results[0]) def test_haversine_coordinates(): - dist = o.geom.haversine_distance(o.geom.Coordinates(0,0), o.geom.Coordinates(1,1)) + dist = osmium.geom.haversine_distance(osmium.geom.Coordinates(0, 0), + osmium.geom.Coordinates(1, 1)) assert dist == pytest.approx(157293.74877) def test_haversine_location(): - dist = o.geom.haversine_distance(o.osm.Location(0,0), o.osm.Location(1,1)) + dist = osmium.geom.haversine_distance(osmium.osm.Location(0, 0), + osmium.osm.Location(1, 1)) assert dist == pytest.approx(157293.74877) diff --git a/test/test_id_filter.py b/test/test_id_filter.py index 21bc26f..a714b05 100644 --- a/test/test_id_filter.py +++ b/test/test_id_filter.py @@ -2,17 +2,17 @@ # # This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann and others. +# Copyright (C) 2025 Sarah Hoffmann and others. # For a full list of authors see the git log. import pytest -import osmium as o - +import osmium from helpers import IDCollector + def test_id_filter_bad_argument(): with pytest.raises(TypeError): - o.filter.IdFilter(None) + osmium.filter.IdFilter(None) def test_id_filter_simple(opl_reader): @@ -25,6 +25,6 @@ def test_id_filter_simple(opl_reader): ids = IDCollector() - o.apply(opl_reader(data), o.filter.IdFilter([2, 5, 200, 201]), ids) + osmium.apply(opl_reader(data), osmium.filter.IdFilter([2, 5, 200, 201]), ids) assert ids.nodes == [2, 200] diff --git a/test/test_id_tracker.py b/test/test_id_tracker.py index 53c5e58..0e17ec1 100644 --- a/test/test_id_tracker.py +++ b/test/test_id_tracker.py @@ -2,11 +2,12 @@ # # This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann and others. +# Copyright (C) 2025 Sarah Hoffmann and others. # For a full list of authors see the git log. import pytest -import osmium as o +import osmium + def assert_tracker_content(ids, nodes, ways, rels): assert len(ids.node_ids()) == len(nodes) @@ -21,7 +22,7 @@ def assert_tracker_content(ids, nodes, ways, rels): def test_add_node(): - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_node(45) @@ -33,7 +34,7 @@ def test_add_node(): def test_add_way(): - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_way(45) @@ -45,7 +46,7 @@ def test_add_way(): def test_add_relation(): - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_relation(45) @@ -63,9 +64,9 @@ def test_add_references_from_file(opl_buffer): r1 Mn1000@,w23@,r1@ """ - ids = o.IdTracker() + ids = osmium.IdTracker() - for obj in o.FileProcessor(opl_buffer(data)): + for obj in osmium.FileProcessor(opl_buffer(data)): ids.add_references(obj) assert len(ids.node_ids()) == 6 @@ -79,7 +80,7 @@ def test_add_references_from_file(opl_buffer): def test_add_reference_from_python_way(): - ids = o.IdTracker() + ids = osmium.IdTracker() class Way: nodes = [5, 7, 23, 1, 5] @@ -91,7 +92,7 @@ class Way: def test_add_reference_from_python_relation(): - ids = o.IdTracker() + ids = osmium.IdTracker() class Member: type = 'r' @@ -116,44 +117,45 @@ class Rel: def test_contains_references_in_node(opl_buffer): - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_node(45) - for obj in o.FileProcessor(opl_buffer('n45')): + for obj in osmium.FileProcessor(opl_buffer('n45')): assert not ids.contains_any_references(obj) def test_contains_references_in_way(opl_buffer): - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_node(45) - for obj in o.FileProcessor(opl_buffer('w3 Nn12,n45')): + for obj in osmium.FileProcessor(opl_buffer('w3 Nn12,n45')): assert ids.contains_any_references(obj) def test_contains_references_not_in_way(opl_buffer): - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_way(3) - for obj in o.FileProcessor(opl_buffer('w3 Nn12,n45')): + for obj in osmium.FileProcessor(opl_buffer('w3 Nn12,n45')): assert not ids.contains_any_references(obj) def test_contains_references_in_relation(opl_buffer): - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_node(45) - for obj in o.FileProcessor(opl_buffer('r3 Mn12@,n45@')): + for obj in osmium.FileProcessor(opl_buffer('r3 Mn12@,n45@')): assert ids.contains_any_references(obj) def test_contains_references_not_in_relation(opl_buffer): - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_way(3) - for obj in o.FileProcessor(opl_buffer('r3 Mn12@,n45@')): + for obj in osmium.FileProcessor(opl_buffer('r3 Mn12@,n45@')): assert not ids.contains_any_references(obj) + REF_SRC = """\ w12 Nn1,n2 w90 Nn10,n11 @@ -161,15 +163,16 @@ def test_contains_references_not_in_relation(opl_buffer): r10 Mn100@,w90@,r2@ """ + @pytest.mark.parametrize('depth', range(3)) def test_complete_backward_references(tmp_path, depth): if depth == 0: - data_file = o.io.FileBuffer(REF_SRC.encode('utf-8'), 'opl') + data_file = osmium.io.FileBuffer(REF_SRC.encode('utf-8'), 'opl') else: data_file = tmp_path / 'test.opl' data_file.write_text(REF_SRC) - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_way(12) ids.add_relation(10) @@ -186,12 +189,12 @@ def test_complete_backward_references(tmp_path, depth): @pytest.mark.parametrize('depth', range(-1, 2)) def test_complete_forward_references(tmp_path, depth): if depth == 0: - data_file = o.io.FileBuffer(REF_SRC.encode('utf-8'), 'opl') + data_file = osmium.io.FileBuffer(REF_SRC.encode('utf-8'), 'opl') else: data_file = tmp_path / 'test.opl' data_file.write_text(REF_SRC) - ids = o.IdTracker() + ids = osmium.IdTracker() ids.add_node(1) ids.add_node(99) @@ -206,8 +209,8 @@ def test_complete_forward_references(tmp_path, depth): def test_clear_node_id_set(): - ids = o.IdTracker() - for i in range (1000, 1003): + ids = osmium.IdTracker() + for i in range(1000, 1003): ids.add_node(i) assert len(ids.node_ids()) == 3 diff --git a/test/test_index_idset.py b/test/test_index_idset.py index 1f3c65e..999aa67 100644 --- a/test/test_index_idset.py +++ b/test/test_index_idset.py @@ -2,14 +2,13 @@ # # This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann and others. +# Copyright (C) 2025 Sarah Hoffmann and others. # For a full list of authors see the git log. -import pytest +import osmium -import osmium as o def test_set_unset_empty(): - ids = o.index.IdSet() + ids = osmium.index.IdSet() assert ids.empty() assert not ids @@ -23,9 +22,9 @@ def test_set_unset_empty(): def test_set_get(): - ids = o.index.IdSet() + ids = osmium.index.IdSet() - for i in (1,100,2): + for i in (1, 100, 2): ids.set(i) assert ids.get(100) @@ -35,11 +34,11 @@ def test_set_get(): def test_clear_and_size(): - ids = o.index.IdSet() + ids = osmium.index.IdSet() assert len(ids) == 0 - for i in (1,100,2): + for i in (1, 100, 2): ids.set(i) assert len(ids) == 3 diff --git a/test/test_index_location.py b/test/test_index_location.py index 316a434..cb5d1f4 100644 --- a/test/test_index_location.py +++ b/test/test_index_location.py @@ -1,58 +1,67 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import pytest -import osmium as o +import osmium + def test_list_types(): - ml = o.index.map_types() + ml = osmium.index.map_types() assert isinstance(ml, list) assert ml @pytest.fixture def table(): - return o.index.create_map("flex_mem") + return osmium.index.create_map("flex_mem") + @pytest.mark.parametrize('use_get', [True, False]) @pytest.mark.parametrize('use_set', [True, False]) def test_set_get(table, use_set, use_get): if use_set: - table.set(4, o.osm.Location(3.4, -5.6)) + table.set(4, osmium.osm.Location(3.4, -5.6)) else: - table[4] = o.osm.Location(3.4, -5.6) + table[4] = osmium.osm.Location(3.4, -5.6) if use_get: - l = table.get(4) + loc = table.get(4) else: - l = table[4] - assert l.lon == pytest.approx(3.4) - assert l.lat == pytest.approx(-5.6) + loc = table[4] + assert loc.lon == pytest.approx(3.4) + assert loc.lat == pytest.approx(-5.6) + def test_get_unset(table): with pytest.raises(KeyError): table.get(56) + def test_array_get_unset(table): with pytest.raises(KeyError): table[56] + def test_set_negative(table): with pytest.raises(TypeError): - table.set(-4, o.osm.Location(3.4, -5.6)) + table.set(-4, osmium.osm.Location(3.4, -5.6)) + def test_array_set_negative(table): with pytest.raises(TypeError): - table[-4] = o.osm.Location(3.4, -5.6) + table[-4] = osmium.osm.Location(3.4, -5.6) + def test_used_memory(table): - table.set(4, o.osm.Location(3.4, -5.6)) + table.set(4, osmium.osm.Location(3.4, -5.6)) assert table.used_memory() > 0 + def test_clear(table): - table.set(593, o.osm.Location(0.35, 45.3)) + table.set(593, osmium.osm.Location(0.35, 45.3)) table.get(593) table.clear() with pytest.raises(KeyError): diff --git a/test/test_io.py b/test/test_io.py index 5a30a6d..4677b00 100644 --- a/test/test_io.py +++ b/test/test_io.py @@ -1,22 +1,24 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import pytest -import osmium as o - +import osmium from helpers import CountingHandler + class NullHandler: def node(self, n): pass + def _run_file(fn): - with o.io.Reader(fn) as rd: - o.apply(rd, NullHandler()) + with osmium.io.Reader(fn) as rd: + osmium.apply(rd, NullHandler()) @pytest.mark.parametrize('as_string', [True, False]) @@ -27,7 +29,7 @@ def test_file_simple(tmp_path, as_string): if as_string: fn = str(fn) - for n in o.FileProcessor(o.io.File(fn)): + for n in osmium.FileProcessor(osmium.io.File(fn)): assert n.is_node() assert n.id == 1 @@ -40,7 +42,7 @@ def test_file_with_format(tmp_path, as_string): if as_string: fn = str(fn) - for n in o.FileProcessor(o.io.File(fn, 'opl')): + for n in osmium.FileProcessor(osmium.io.File(fn, 'opl')): assert n.is_node() assert n.id == 1 @@ -72,9 +74,9 @@ def test_relation_with_tags(test_data): def test_broken_timestamp(test_data): fn = test_data('n1 tx') - with o.io.Reader(fn) as rd: + with osmium.io.Reader(fn) as rd: with pytest.raises(RuntimeError): - o.apply(rd, NullHandler()) + osmium.apply(rd, NullHandler()) @pytest.mark.parametrize('as_string', [True, False]) @@ -89,7 +91,7 @@ def test_file_header(tmp_path, as_string): if as_string: fn = str(fn) - with o.io.Reader(fn) as rd: + with osmium.io.Reader(fn) as rd: h = rd.header() assert not h.has_multiple_object_versions assert h.box().valid() @@ -97,9 +99,9 @@ def test_file_header(tmp_path, as_string): def test_reader_with_filebuffer(): - rd = o.io.Reader(o.io.FileBuffer('n1 x4 y1'.encode('utf-8'), 'opl')) + rd = osmium.io.Reader(osmium.io.FileBuffer('n1 x4 y1'.encode('utf-8'), 'opl')) handler = CountingHandler() - o.apply(rd, handler) + osmium.apply(rd, handler) assert handler.counts == [1, 0, 0, 0] diff --git a/test/test_key_filter.py b/test/test_key_filter.py index 06ad71d..2585f61 100644 --- a/test/test_key_filter.py +++ b/test/test_key_filter.py @@ -1,23 +1,24 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann. -import osmium as o +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. +import osmium import pytest - from helpers import IDCollector + def test_filter_no_keys(): with pytest.raises(TypeError, match="keys to filter"): - o.filter.KeyFilter() + osmium.filter.KeyFilter() @pytest.mark.parametrize('key', [None, 1, IDCollector(), 'a'.encode('utf-8')]) def test_filter_bad_argument_types(key): with pytest.raises(TypeError, match="must be strings"): - o.filter.KeyFilter("foo", key) + osmium.filter.KeyFilter("foo", key) @pytest.mark.parametrize('key,nodes,changesets', [('foo', [1], [10]), @@ -35,7 +36,7 @@ def test_filter_simple(opl_reader, key, nodes, changesets): post = IDCollector() - o.apply(opl_reader(data), o.filter.KeyFilter(key), post) + osmium.apply(opl_reader(data), osmium.filter.KeyFilter(key), post) assert post.nodes == nodes assert post.changesets == changesets diff --git a/test/test_memberlist.py b/test/test_memberlist.py index a0a79b9..fb93fc0 100644 --- a/test/test_memberlist.py +++ b/test/test_memberlist.py @@ -1,10 +1,10 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. -import osmium as o def test_member_list_length(simple_handler): data = """\ @@ -14,6 +14,7 @@ def test_member_list_length(simple_handler): """ rels = {} + def cb(rel): rels[rel.id] = len(rel.members) diff --git a/test/test_nodelist.py b/test/test_nodelist.py index fb35440..5d51e24 100644 --- a/test/test_nodelist.py +++ b/test/test_nodelist.py @@ -1,11 +1,13 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import pytest -import osmium as o +import osmium + def test_waynode_length(simple_handler): data = """\ @@ -15,16 +17,18 @@ def test_waynode_length(simple_handler): """ lens = {} + def way(w): lens[w.id] = len(w.nodes) simple_handler(data, way=way) - assert lens == { 593 : 0, 4 : 3, 8 : 4 } + assert lens == {593: 0, 4: 3, 8: 4} def test_node_ids(simple_handler): refs = [] + def way(w): refs.extend(n.ref for n in w.nodes) assert w.nodes[-2].ref == -34 @@ -45,12 +49,13 @@ def test_missing_location_without_location_handler(simple_handler): """ refs = [] + def way(w): refs.extend(n.ref for n in w.nodes) assert not w.nodes[0].location.valid() - with pytest.raises(o.InvalidLocationError): + with pytest.raises(osmium.InvalidLocationError): w.nodes[0].location.lat - with pytest.raises(o.InvalidLocationError): + with pytest.raises(osmium.InvalidLocationError): w.nodes[0].location.lon simple_handler(data, way=way) @@ -65,6 +70,7 @@ def test_valid_locations(simple_handler): """ locations = [] + def way(w): assert all(n.location.valid() for n in w.nodes) locations.extend((int(10 * n.location.lon), int(10 * n.location.lat)) diff --git a/test/test_osm.py b/test/test_osm.py index a8d449c..6603c30 100644 --- a/test/test_osm.py +++ b/test/test_osm.py @@ -1,22 +1,24 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import re from itertools import count import pytest from helpers import mkdate -import osmium as o +import osmium + def apply_simple(handler, data, locations, tmp_path): handler.apply_buffer(data.encode('utf-8'), 'opl', locations=locations) def apply_with_merge(handler, data, locations, tmp_path): - mir = o.MergeInputReader() + mir = osmium.MergeInputReader() mir.add_buffer(data.encode('utf-8'), format='opl') @@ -31,6 +33,7 @@ def _make_importer_factory(apply_func, tmp_path, to_opl): def _run(data, node=None, way=None, relation=None, area=None, changeset=None, locations=False): cnt = count() + def _m(func): if func is None: return None @@ -40,9 +43,9 @@ def _inner(obj): func(obj) return _inner - handler = o.make_simple_handler(node=_m(node), way=_m(way), - relation=_m(relation), area=_m(area), - changeset=_m(changeset)) + handler = osmium.make_simple_handler(node=_m(node), way=_m(way), + relation=_m(relation), area=_m(area), + changeset=_m(changeset)) apply_func(handler, to_opl(data), locations, tmp_path) return next(cnt) @@ -61,22 +64,22 @@ def area_importer(request, tmp_path, to_opl): def test_invalid_location(): - loc = o.osm.Location() + loc = osmium.osm.Location() assert not loc.valid() assert str(loc) == 'invalid' assert repr(loc) == 'osmium.osm.Location()' - with pytest.raises(o.InvalidLocationError): - lat = loc.lat - with pytest.raises(o.InvalidLocationError): - lon = loc.lon + with pytest.raises(osmium.InvalidLocationError): + loc.lat + with pytest.raises(osmium.InvalidLocationError): + loc.lon # these two don't raise an exception assert loc.lat_without_check() is not None assert loc.lon_without_check() is not None def test_valid_location(): - loc = o.osm.Location(-1, 10) + loc = osmium.osm.Location(-1, 10) assert loc.lon == pytest.approx(-1) assert loc.lat == pytest.approx(10) assert loc.x == -10000000 @@ -92,7 +95,7 @@ def test_valid_location(): 'w34 Nn34', 'r45 Tfoo=rte']) def test_object_attribute_do_not_overwrite(opl_buffer, attrname, osmdata): - for n in o.FileProcessor(opl_buffer(osmdata)): + for n in osmium.FileProcessor(opl_buffer(osmdata)): with pytest.raises(AttributeError): setattr(n, attrname, 3) @@ -100,35 +103,40 @@ def test_object_attribute_do_not_overwrite(opl_buffer, attrname, osmdata): def test_node_attributes(opl_buffer): node_data = 'n1 v5 c58674 t2014-01-31T06:23:35Z i42 uänonymous' - for n in o.FileProcessor(opl_buffer(node_data)): - assert n.deleted == False - assert n.visible == True + for n in osmium.FileProcessor(opl_buffer(node_data)): + assert n.deleted is False + assert n.visible is True assert n.version == 5 assert n.changeset == 58674 assert n.uid == 42 - assert n.user_is_anonymous() == False + assert n.user_is_anonymous() is False assert n.timestamp == mkdate(2014, 1, 31, 6, 23, 35) assert n.user == u'änonymous' assert n.positive_id() == 1 assert n.is_node() - assert not n.is_way() + assert n.is_way() is False assert n.type_str() == 'n' assert str(n) == 'n1: location=invalid tags={}' - assert repr(n) == "osmium.osm.Node(id=1, deleted=False, visible=True, version=5, changeset=58674, uid=42, timestamp=datetime.datetime(2014, 1, 31, 6, 23, 35, tzinfo=datetime.timezone.utc), user='änonymous', tags=osmium.osm.TagList({}), location=osmium.osm.Location())" + assert repr(n) == 'osmium.osm.Node(id=1, deleted=False, visible=True, ' \ + 'version=5, changeset=58674, uid=42, ' \ + 'timestamp=datetime.datetime(2014, 1, 31, 6, 23, 35,' \ + ' tzinfo=datetime.timezone.utc), ' \ + "user='änonymous', tags=osmium.osm.TagList({}), " \ + 'location=osmium.osm.Location())' break else: assert False def test_node_location(opl_buffer): - for n in o.FileProcessor(opl_buffer("n1 x4 y5")): + for n in osmium.FileProcessor(opl_buffer("n1 x4 y5")): assert n.lat == 5.0 assert n.lon == 4.0 @pytest.mark.parametrize('nid', (23, 0, -68373, 17179869418, -17179869417)) def test_node_positive_id(opl_buffer, nid): - for n in o.FileProcessor(opl_buffer(f"n{nid} v5 c58674")): + for n in osmium.FileProcessor(opl_buffer(f"n{nid} v5 c58674")): assert n.id == nid assert n.positive_id() == abs(nid) break @@ -139,12 +147,12 @@ def test_node_positive_id(opl_buffer, nid): def test_way_attributes(test_importer): def way(o): assert o.id == 1 - assert o.deleted == False - assert o.visible == True + assert o.deleted is False + assert o.visible is True assert o.version == 5 assert o.changeset == 58674 assert o.uid == 42 - assert o.user_is_anonymous() == False + assert o.user_is_anonymous() is False assert o.timestamp == mkdate(2014, 1, 31, 6, 23, 35) assert o.user == 'anonymous' assert o.positive_id() == 1 @@ -155,10 +163,23 @@ def way(o): assert not o.ends_have_same_location() assert str(o) == 'w1: nodes=[1@0.0000000/0.0000000,2,3@1.0000000/1.0000000] tags={}' - assert repr(o) == "osmium.osm.Way(id=1, deleted=False, visible=True, version=5, changeset=58674, uid=42, timestamp=datetime.datetime(2014, 1, 31, 6, 23, 35, tzinfo=datetime.timezone.utc), user='anonymous', tags=osmium.osm.TagList({}), nodes=osmium.osm.WayNodeList([osmium.osm.NodeRef(ref=1, location=osmium.osm.Location(x=0, y=0)), osmium.osm.NodeRef(ref=2, location=osmium.osm.Location()), osmium.osm.NodeRef(ref=3, location=osmium.osm.Location(x=10000000, y=10000000))]))" + assert repr(o) == 'osmium.osm.Way(id=1, deleted=False, visible=True, ' \ + 'version=5, changeset=58674, uid=42, ' \ + 'timestamp=datetime.datetime(2014, 1, 31, 6, 23, 35,' \ + ' tzinfo=datetime.timezone.utc), ' \ + "user='anonymous', tags=osmium.osm.TagList({}), " \ + 'nodes=osmium.osm.WayNodeList([osmium.osm.NodeRef(ref=1,' \ + ' location=osmium.osm.Location(x=0, y=0)), ' \ + 'osmium.osm.NodeRef(ref=2, location=osmium.osm.Location()), ' \ + 'osmium.osm.NodeRef(ref=3, location=osmium.osm.Location(' \ + 'x=10000000, y=10000000))]))' assert str(o.nodes) == '[1@0.0000000/0.0000000,2,3@1.0000000/1.0000000]' - assert repr(o.nodes) == "osmium.osm.WayNodeList([osmium.osm.NodeRef(ref=1, location=osmium.osm.Location(x=0, y=0)), osmium.osm.NodeRef(ref=2, location=osmium.osm.Location()), osmium.osm.NodeRef(ref=3, location=osmium.osm.Location(x=10000000, y=10000000))])" + assert repr(o.nodes) == 'osmium.osm.WayNodeList([osmium.osm.NodeRef(ref=1, ' \ + 'location=osmium.osm.Location(x=0, y=0)), '\ + 'osmium.osm.NodeRef(ref=2, location=osmium.osm.Location()), '\ + 'osmium.osm.NodeRef(ref=3, location=osmium.osm.Location(' \ + 'x=10000000, y=10000000))])' assert 1 == test_importer(['n1 x0 y0', 'n3 x1 y1', 'w1 v5 c58674 t2014-01-31T06:23:35Z i42 uanonymous Nn1,n2,n3'], @@ -169,20 +190,20 @@ def test_way_attribute_do_not_overwrite(opl_buffer): data = """\ w34 Nn34 """ - for w in o.FileProcessor(opl_buffer(data)): + for w in osmium.FileProcessor(opl_buffer(data)): with pytest.raises(AttributeError): - w.nodes = [3,4,5] + w.nodes = [3, 4, 5] def test_relation_attributes(test_importer): def relation(o): assert o.id == 1 - assert o.deleted == False - assert o.visible == True + assert o.deleted is False + assert o.visible is True assert o.version == 5 assert o.changeset == 58674 assert o.uid == 42 - assert o.user_is_anonymous() == False + assert o.user_is_anonymous() is False assert o.timestamp == mkdate(2014, 1, 31, 6, 23, 35) assert o.user == ' anonymous' assert o.positive_id() == 1 @@ -190,10 +211,17 @@ def relation(o): assert o.type_str() == 'r' assert str(o) == 'r1: members=[w1], tags={}' - assert repr(o) == "osmium.osm.Relation(id=1, deleted=False, visible=True, version=5, changeset=58674, uid=42, timestamp=datetime.datetime(2014, 1, 31, 6, 23, 35, tzinfo=datetime.timezone.utc), user=' anonymous', tags=osmium.osm.TagList({}), members=osmium.osm.RelationMemberList([osmium.osm.RelationMember(ref=1, type='w', role='')]))" + assert repr(o) == 'osmium.osm.Relation(id=1, deleted=False, visible=True, ' \ + 'version=5, changeset=58674, uid=42, ' \ + 'timestamp=datetime.datetime(2014, 1, 31, 6, 23, 35,' \ + ' tzinfo=datetime.timezone.utc), ' \ + "user=' anonymous', tags=osmium.osm.TagList({}), " \ + 'members=osmium.osm.RelationMemberList(' \ + "[osmium.osm.RelationMember(ref=1, type='w', role='')]))" assert str(o.members) == '[w1]' - assert repr(o.members) == "osmium.osm.RelationMemberList([osmium.osm.RelationMember(ref=1, type='w', role='')])" + assert repr(o.members) == 'osmium.osm.RelationMemberList('\ + "[osmium.osm.RelationMember(ref=1, type='w', role='')])" assert 1 == test_importer('r1 v5 c58674 t2014-01-31T06:23:35Z i42 u%20%anonymous Mw1@', relation=relation) @@ -203,40 +231,42 @@ def test_relation_attribute_do_not_overwrite(opl_buffer): data = """\ r34 Mn23@,w34@ """ - for r in o.FileProcessor(opl_buffer(data)): + for r in osmium.FileProcessor(opl_buffer(data)): with pytest.raises(AttributeError): - r.members = [3,4,5] + r.members = [3, 4, 5] def test_area_from_way_attributes(area_importer): def area(o): assert o.id == 46 - assert o.deleted == False - assert o.visible == True + assert o.deleted is False + assert o.visible is True assert o.version == 5 assert o.changeset == 58674 assert o.uid == 42 - assert o.user_is_anonymous() == False + assert o.user_is_anonymous() is False assert o.timestamp == mkdate(2014, 1, 31, 6, 23, 35) assert o.user == 'anonymous' assert o.positive_id() == 46 assert o.orig_id() == 23 - assert o.from_way() == True + assert o.from_way() is True assert o.is_area() assert o.type_str() == 'a' - assert o.is_multipolygon() == False + assert o.is_multipolygon() is False assert o.num_rings() == (1, 0) assert len(list(o.outer_rings())) == 1 - oring = list(o.outer_rings())[0] + + oring = next(o.outer_rings()) assert len(list(oring)) == 4 - assert set((1,2,3)) == set([x.ref for x in oring]) + assert {1, 2, 3} == {x.ref for x in oring} assert oring.is_closed() assert oring.ends_have_same_id() assert oring.ends_have_same_location() assert len(list(o.inner_rings(oring))) == 0 assert 1 == area_importer(['n1 x0 y0', 'n2 x1 y0', 'n3 x0 y1', - 'w23 v5 c58674 t2014-01-31T06:23:35Z i42 uanonymous Nn1,n2,n3,n1 Tarea=yes'], + 'w23 v5 c58674 t2014-01-31T06:23:35Z i42 ' + 'uanonymous Nn1,n2,n3,n1 Tarea=yes'], area=area) @@ -244,23 +274,24 @@ def area(o): def test_area_from_multipolygon_relation(area_importer, mptype): def area(o): assert o.id == 3 - assert o.deleted == False - assert o.visible == True + assert o.deleted is False + assert o.visible is True assert o.version == 3 assert o.changeset == 7654 assert o.uid == 42 - assert o.user_is_anonymous() == False + assert o.user_is_anonymous() is False assert o.timestamp == mkdate(2014, 1, 31, 6, 23, 35) assert o.user == 'Anon' assert o.positive_id() == 3 assert o.orig_id() == 1 - assert o.from_way() == False - assert o.is_multipolygon() == False + assert o.from_way() is False + assert o.is_multipolygon() is False assert o.num_rings() == (1, 0) assert len(list(o.outer_rings())) == 1 - oring = list(o.outer_rings())[0] + + oring = next(o.outer_rings()) assert len(list(oring)) == 4 - assert set((1,2,3)) == set([x.ref for x in oring]) + assert {1, 2, 3} == {x.ref for x in oring} assert oring.is_closed() assert oring.ends_have_same_id() assert oring.ends_have_same_location() @@ -268,9 +299,9 @@ def area(o): assert 1 == area_importer(['n1 x0 y0', 'n2 x1 y0', 'n3 x0 y1', 'w23 Nn1,n2,n3', 'w24 Nn3,n1', - 'r1 v3 c7654 t2014-01-31T06:23:35Z i42 uAnon Mw23@outer,w24@outer Ttype={}'.format(mptype)], - area=area) - + 'r1 v3 c7654 t2014-01-31T06:23:35Z i42 uAnon ' + f"Mw23@outer,w24@outer Ttype={mptype}"], + area=area) def test_changest_attributes(area_importer): @@ -289,19 +320,30 @@ def changeset(c): assert -1465242 == c.bounds.bottom_left.x assert 515288506 == c.bounds.bottom_left.y assert c.type_str() == 'c' - assert str(c) == 'c34: closed_at=2005-04-09 20:54:39+00:00, bounds=(-0.1465242/51.5288506 -0.1464925/51.5288620), tags={}' - assert repr(c) == "osmium.osm.Changeset(id=34, uid=1, created_at=datetime.datetime(2005, 4, 9, 19, 54, 13, tzinfo=datetime.timezone.utc), closed_at=datetime.datetime(2005, 4, 9, 20, 54, 39, tzinfo=datetime.timezone.utc), open=False, num_changes=2, bounds=osmium.osm.Box(bottom_left=osmium.osm.Location(x=-1465242, y=515288506), top_right=osmium.osm.Location(x=-1464925, y=515288620)), user='Steve', tags=osmium.osm.TagList({}))" + assert str(c) == 'c34: closed_at=2005-04-09 20:54:39+00:00, '\ + 'bounds=(-0.1465242/51.5288506 -0.1464925/51.5288620), tags={}' + assert repr(c) == 'osmium.osm.Changeset(id=34, uid=1, ' \ + 'created_at=datetime.datetime(2005, 4, 9, 19, 54, 13,' \ + ' tzinfo=datetime.timezone.utc), ' \ + 'closed_at=datetime.datetime(2005, 4, 9, 20, 54, 39,' \ + ' tzinfo=datetime.timezone.utc), '\ + 'open=False, num_changes=2, '\ + 'bounds=osmium.osm.Box(bottom_left=' \ + 'osmium.osm.Location(x=-1465242, y=515288506), ' \ + 'top_right=osmium.osm.Location(x=-1464925, y=515288620)), '\ + "user='Steve', tags=osmium.osm.TagList({}))" assert 1 == area_importer('c34 k2 s2005-04-09T19:54:13Z e2005-04-09T20:54:39Z ' - 'd34 i1 uSteve x-0.1465242 y51.5288506 X-0.1464925 Y51.5288620', + 'd34 i1 uSteve x-0.1465242 y51.5288506 X-0.1464925 Y51.5288620', changeset=changeset) def test_entity_operations(): - assert not o.osm.NOTHING - assert o.osm.NODE + assert not osmium.osm.NOTHING + assert osmium.osm.NODE - assert o.osm.AREA | o.osm.NODE | o.osm.WAY | o.osm.RELATION == o.osm.OBJECT - assert o.osm.ALL & o.osm.RELATION == o.osm.RELATION + assert osmium.osm.AREA | osmium.osm.NODE | osmium.osm.WAY | osmium.osm.RELATION \ + == osmium.osm.OBJECT + assert osmium.osm.ALL & osmium.osm.RELATION == osmium.osm.RELATION - assert ~o.osm.CHANGESET == o.osm.OBJECT + assert ~osmium.osm.CHANGESET == osmium.osm.OBJECT diff --git a/test/test_osmium.py b/test/test_osmium.py index 342828c..70e63b2 100644 --- a/test/test_osmium.py +++ b/test/test_osmium.py @@ -1,22 +1,23 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import pytest -import osmium as o +import osmium def test_read_node_location_with_handler(opl_reader): - idx = o.index.create_map("flex_mem") - hdlr = o.NodeLocationsForWays(idx) + idx = osmium.index.create_map("flex_mem") + hdlr = osmium.NodeLocationsForWays(idx) data = """\ n1 x6 y7 n45 x-3 y0 """ - o.apply(opl_reader(data), hdlr) + osmium.apply(opl_reader(data), hdlr) assert idx.get(1).lon == pytest.approx(6) assert idx.get(1).lat == pytest.approx(7) @@ -27,10 +28,10 @@ def test_read_node_location_with_handler(opl_reader): idx.get(2) -@pytest.mark.parametrize('ignore_error', [(True, False)]) +@pytest.mark.parametrize('ignore_error', [True, False]) def test_apply_node_location_handler(opl_reader, ignore_error): - hdlr = o.NodeLocationsForWays(o.index.create_map("flex_mem")) + hdlr = osmium.NodeLocationsForWays(osmium.index.create_map("flex_mem")) if ignore_error: hdlr.ignore_errors() @@ -42,10 +43,9 @@ def __init__(self): def way(self, w): try: self.collect.append((w.id, [(n.lon, n.lat) for n in w.nodes])) - except o.InvalidLocationError: + except osmium.InvalidLocationError: self.with_error.append(w.id) - data = """\ n1 x6 y7 n2 x6 y7.1 @@ -58,14 +58,14 @@ def way(self, w): tester = WayNodeHandler() if ignore_error: - o.apply(opl_reader(data), hdlr, tester) + osmium.apply(opl_reader(data), hdlr, tester) assert tester.collect == [(3, [(pytest.approx(6), pytest.approx(7)), - (pytest.approx(6), pytest.approx(7.1))])] + (pytest.approx(6), pytest.approx(7.1))])] assert tester.with_error == [4] else: - with pytest.raises(osmium.InvalidLocationError): - o.apply(opl.reader(data), hdlr, tester) + with pytest.raises(KeyError): + osmium.apply(opl_reader(data), hdlr, tester) def test_apply_invalid_handler_object(opl_reader): @@ -74,13 +74,13 @@ def some_func(): print('A') with pytest.raises(TypeError): - o.apply(opl_reader("n1 x2 z4"), DummyHandler()) + osmium.apply(opl_reader("n1 x2 z4"), DummyHandler()) def test_mixed_handlers(opl_reader): logged = [] - class OldStyle(o.SimpleHandler): + class OldStyle(osmium.SimpleHandler): def node(self, n): logged.append('old') @@ -88,7 +88,7 @@ class NewStyle: def node(self, n): logged.append('new') - o.apply(opl_reader("n1 x0 y0"), NewStyle(), OldStyle(), NewStyle(), OldStyle()) + osmium.apply(opl_reader("n1 x0 y0"), NewStyle(), OldStyle(), NewStyle(), OldStyle()) assert logged == ['new', 'old', 'new', 'old'] @@ -104,6 +104,6 @@ class SecondHandler: def node(self, n): logged.append(n.saved) - o.apply(opl_reader("n1 x0 y0"), FirstHandler(), SecondHandler()) + osmium.apply(opl_reader("n1 x0 y0"), FirstHandler(), SecondHandler()) assert logged == [45674] diff --git a/test/test_pyosmium_get_changes.py b/test/test_pyosmium_get_changes.py index a590a5a..59168bd 100644 --- a/test/test_pyosmium_get_changes.py +++ b/test/test_pyosmium_get_changes.py @@ -1,8 +1,9 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2023 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. """ Tests for the pyosmium-get-changes script. """ from pathlib import Path @@ -10,7 +11,7 @@ import pytest import osmium.replication.server -import osmium as o +import osmium from helpers import IDCollector @@ -26,15 +27,13 @@ class TestPyosmiumGetChanges: def setup(self): self.script = dict() - filename = (Path(__file__) / ".." / ".." / "tools"/ "pyosmium-get-changes").resolve() + filename = Path(__file__, "..", "..", "tools", "pyosmium-get-changes").resolve() with filename.open("rb") as f: exec(compile(f.read(), str(filename), 'exec'), self.script) - def main(self, httpserver, *args): return self.script['main'](['--server', httpserver.url_for('')] + list(args)) - def test_init_id(self, capsys, httpserver): assert 0 == self.main(httpserver, '-I', '453') @@ -42,7 +41,6 @@ def test_init_id(self, capsys, httpserver): assert output == '453' - def test_init_date(self, capsys, httpserver): httpserver.expect_request('/state.txt').respond_with_data(dedent("""\ sequenceNumber=100 @@ -58,14 +56,12 @@ def test_init_date(self, capsys, httpserver): assert output == '-1' - def test_init_to_file(self, tmp_path, httpserver): fname = tmp_path / 'db.seq' assert 0 == self.main(httpserver, '-I', '453', '-f', str(fname)) assert fname.read_text() == '453' - def test_init_from_seq_file(self, tmp_path, httpserver): fname = tmp_path / 'db.seq' fname.write_text('453') @@ -73,7 +69,6 @@ def test_init_from_seq_file(self, tmp_path, httpserver): assert 0 == self.main(httpserver, '-f', str(fname)) assert fname.read_text() == '453' - def test_init_date_with_cookie(self, capsys, tmp_path, httpserver): httpserver.expect_request('/state.txt').respond_with_data(dedent("""\ sequenceNumber=100 @@ -95,7 +90,6 @@ def test_init_date_with_cookie(self, capsys, tmp_path, httpserver): assert output == '-1' - def test_get_simple_update(self, tmp_path, httpserver): outfile = tmp_path / 'outfile.opl' @@ -114,7 +108,7 @@ def test_get_simple_update(self, tmp_path, httpserver): '-I', '453', '-o', str(outfile)) ids = IDCollector() - o.apply(str(outfile), ids) + osmium.apply(str(outfile), ids) assert ids.nodes == [12, 13] assert ids.ways == [2] diff --git a/test/test_replication.py b/test/test_replication.py index 023c9cd..2917fc6 100644 --- a/test/test_replication.py +++ b/test/test_replication.py @@ -1,8 +1,9 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2023 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import logging import time from textwrap import dedent @@ -13,7 +14,6 @@ from helpers import mkdate, CountingHandler -import osmium as o import osmium.replication.server as rserv import osmium.replication @@ -364,7 +364,7 @@ def test_apply_diffs_permanent_error(httpserver, caplog): with caplog.at_level(logging.ERROR): with rserv.ReplicationServer(httpserver.url_for(''), "opl") as svr: h = CountingHandler() - assert None == svr.apply_diffs(h, 100, 10000) + assert svr.apply_diffs(h, 100, 10000) is None assert h.counts == [0, 0, 0, 0] assert 'Error during diff download' in caplog.text @@ -415,8 +415,6 @@ def test_apply_diffs_transient_error(httpserver, caplog): assert 'Error during diff download' not in caplog.text - - def test_apply_diffs_transient_error_permanent(httpserver, caplog): httpserver.expect_ordered_request('/state.txt').respond_with_data("""\ sequenceNumber=101 diff --git a/test/test_replication_utils.py b/test/test_replication_utils.py index f911e8d..eff4a0a 100644 --- a/test/test_replication_utils.py +++ b/test/test_replication_utils.py @@ -1,13 +1,14 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. - +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import osmium.replication.utils as rutil from helpers import mkdate + def test_get_replication_header_empty(tmp_path): fn = tmp_path / 'test.opl' fn.write_text('n6365 v1 c63965061 t2018-10-29T03:56:07Z i8369524 ux x1 y7') diff --git a/test/test_tag_filter.py b/test/test_tag_filter.py index dc9a0f5..9985aee 100644 --- a/test/test_tag_filter.py +++ b/test/test_tag_filter.py @@ -2,17 +2,17 @@ # # This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2024 Sarah Hoffmann and others. +# Copyright (C) 2025 Sarah Hoffmann and others. # For a full list of authors see the git log. import pytest -import osmium as o - +import osmium from helpers import IDCollector + def test_tag_filter_no_keys(): with pytest.raises(TypeError, match="tags to filter"): - o.filter.TagFilter() + osmium.filter.TagFilter() @pytest.mark.parametrize('kv', ['something', 'so', ('a', 'b', 'c'), @@ -20,12 +20,13 @@ def test_tag_filter_no_keys(): (34, 'a'), ('a', 0)]) def test_tag_filter_bad_arguments(kv): with pytest.raises(TypeError, match="Each tag must be a tuple"): - o.filter.TagFilter(kv) + osmium.filter.TagFilter(kv) + @pytest.mark.parametrize('tags,filt', [('foo=bar', [('foo', 'bar')]), ('a=1,b=2', [('x', 'x'), ('a', '1')]), ('a=1,b=2', [('x', 'x'), ('b', '2')]) - ]) + ]) def test_tag_filter_pass(opl_reader, tags, filt): data = f"""\ n1 T{tags} @@ -36,7 +37,7 @@ def test_tag_filter_pass(opl_reader, tags, filt): ids = IDCollector() - o.apply(opl_reader(data), o.filter.TagFilter(*filt), ids) + osmium.apply(opl_reader(data), osmium.filter.TagFilter(*filt), ids) assert ids.nodes == [1] assert ids.ways == [2] @@ -46,7 +47,7 @@ def test_tag_filter_pass(opl_reader, tags, filt): @pytest.mark.parametrize('tags,filt', [('foo=bar', [('foo', 'bars')]), ('a=1,b=2', [('x', 'x'), ('a', '2')]) - ]) + ]) def test_tag_filter_fail(opl_reader, tags, filt): data = f"""\ n1 T{tags} @@ -57,7 +58,7 @@ def test_tag_filter_fail(opl_reader, tags, filt): ids = IDCollector() - o.apply(opl_reader(data), o.filter.TagFilter(*filt), ids) + osmium.apply(opl_reader(data), osmium.filter.TagFilter(*filt), ids) assert ids.nodes == [] assert ids.ways == [] diff --git a/test/test_taglist.py b/test/test_taglist.py index 8f923a2..df77f8d 100644 --- a/test/test_taglist.py +++ b/test/test_taglist.py @@ -1,17 +1,18 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import pytest -import osmium as o @pytest.fixture def tag_handler(simple_handler): def _handle(data, tests): - tags = {None: None} # marker that handler hasn't run yet + tags = {None: None} # marker that handler hasn't run yet + def node(n): if None in tags: del tags[None] @@ -46,8 +47,8 @@ def tests(n): def test_empty_taglist_get(tag_handler): def tests(n): - assert None == n.tags.get("foo") - assert None == n.tags.get("foo", None) + assert n.tags.get("foo") is None + assert n.tags.get("foo", None) is None assert "fs" == n.tags.get("foo", "fs") tags = tag_handler("n234 x1 y2", tests) @@ -73,13 +74,14 @@ def test_taglist_length(simple_handler): """ lens = {} + def node(n): lens[n.id] = len(n.tags) assert n.tags simple_handler(data, node=node) - lens = {1 : 1, 2 : 1, 3 : 3} + assert lens == {1: 1, 2: 1, 3: 3} def test_taglist_contains(tag_handler): @@ -112,7 +114,7 @@ def tests(n): assert tags == {'abba': 'x', '2': 'vvv', 'xx': 'abba'} -def test_taglist_indexop(tag_handler): +def test_taglist_indexop_get(tag_handler): def tests(n): assert "x" == n.tags.get("abba") assert "vvv" == n.tags.get("2", None) diff --git a/test/test_threaded.py b/test/test_threaded.py index 6517d5e..1b0a476 100644 --- a/test/test_threaded.py +++ b/test/test_threaded.py @@ -1,12 +1,13 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. import threading from helpers import CountingHandler -import osmium as o + def test_threaded_processing(): """ Process a file in a different thread and make sure that processing @@ -24,4 +25,4 @@ def import_data(): function_complete.wait(timeout=2) assert function_complete.is_set() - assert c.counts == [1, 0, 0 ,0] + assert c.counts == [1, 0, 0, 0] diff --git a/test/test_writer.py b/test/test_writer.py index e8d7cd1..d9cd7a8 100644 --- a/test/test_writer.py +++ b/test/test_writer.py @@ -1,8 +1,9 @@ -# SPDX-License-Identifier: BSD +# SPDX-License-Identifier: BSD-2-Clause # -# This file is part of Pyosmium. +# This file is part of pyosmium. (https://osmcode.org/pyosmium/) # -# Copyright (C) 2022 Sarah Hoffmann. +# Copyright (C) 2025 Sarah Hoffmann and others. +# For a full list of authors see the git log. from contextlib import contextmanager from collections import OrderedDict from datetime import datetime, timezone, timedelta @@ -10,7 +11,7 @@ import pytest -import osmium as o +import osmium from helpers import mkdate @@ -19,12 +20,11 @@ def test_writer(tmp_path): @contextmanager def _WriteExpect(filename, expected): - with o.SimpleWriter(str(filename), 1024*1024) as writer: + with osmium.SimpleWriter(str(filename), 1024*1024) as writer: yield writer assert filename.read_text().strip() == expected - def _create(expected): filename = tmp_path / (str(uuid.uuid4()) + '.opl') return _WriteExpect(filename, expected) @@ -32,9 +32,9 @@ def _create(expected): return _create -class O: +class O: # noqa: E742 def __init__(self, **params): - for k,v in params.items(): + for k, v in params.items(): setattr(self, k, v) @@ -55,7 +55,8 @@ def __init__(self, **params): (O(uid=987), '0 v0 dV c0 t i987 u T'), (O(timestamp='2012-04-14T20:58:35Z'), '0 v0 dV c0 t2012-04-14T20:58:35Z i0 u T'), (O(timestamp=mkdate(2009, 4, 14, 20, 58, 35)), '0 v0 dV c0 t2009-04-14T20:58:35Z i0 u T'), - (O(timestamp=datetime(2009, 4, 14, 20, 58, 35, tzinfo=timezone(timedelta(hours=1)))), '0 v0 dV c0 t2009-04-14T19:58:35Z i0 u T'), + (O(timestamp=datetime(2009, 4, 14, 20, 58, 35, tzinfo=timezone(timedelta(hours=1)))), + '0 v0 dV c0 t2009-04-14T19:58:35Z i0 u T'), (O(timestamp='1970-01-01T00:00:01Z'), '0 v0 dV c0 t1970-01-01T00:00:01Z i0 u T') ]) class TestWriteAttributes: @@ -78,7 +79,7 @@ def test_relation_simple_attr(self, test_writer, osmobj, out_attr): ({}, 'T'), ((("foo", "bar"), ), 'Tfoo=bar'), ((("foo", "bar"), ("2", "1")), 'Tfoo=bar,2=1'), - ({'test' : 'drive'}, 'Ttest=drive'), + ({'test': 'drive'}, 'Ttest=drive'), (OrderedDict((('a', 'b'), ('c', '3'))), 'Ta=b,c=3'), ]) class TestWriteTags: @@ -128,7 +129,7 @@ def test_relation_members(test_writer): w.add_relation(O(members=(('n', 34, 'foo'), ('r', 200, ''), ('w', 1111, 'x') - ))) + ))) def test_relation_members_generic(test_writer): @@ -136,7 +137,7 @@ def test_relation_members_generic(test_writer): w.add(O(members=(('n', 34, 'foo'), ('r', 200, ''), ('w', 1111, 'x') - ))) + ))) def test_relation_members_None(test_writer): @@ -234,30 +235,30 @@ def test_member_object(test_writer, simple_handler): def test_set_custom_header(tmp_path): fn = str(tmp_path / 'test.xml') - h = o.io.Header() + h = osmium.io.Header() h.set('generator', 'foo') - h.add_box(o.osm.Box(0.1, -4, 10, 45)) + h.add_box(osmium.osm.Box(0.1, -4, 10, 45)) - writer = o.SimpleWriter(fn, 4000, h) + writer = osmium.SimpleWriter(fn, 4000, h) try: writer.add_node({}) finally: writer.close() - with o.io.Reader(fn) as rd: + with osmium.io.Reader(fn) as rd: h = rd.header() assert h.get('generator') == 'foo' assert h.box().valid() - assert h.box().bottom_left == o.osm.Location(0.1, -4) - assert h.box().top_right == o.osm.Location(10, 45) + assert h.box().bottom_left == osmium.osm.Location(0.1, -4) + assert h.box().top_right == osmium.osm.Location(10, 45) def test_add_node_after_close(tmp_path, simple_handler): node_opl = "n235 v1 dV c0 t i0 u Telephant=yes x98.7 y-3.45" filename = tmp_path / (str(uuid.uuid4()) + '.opl') - writer = o.SimpleWriter(str(filename), 1024*1024) + writer = osmium.SimpleWriter(str(filename), 1024*1024) writer.close() with pytest.raises(RuntimeError, match='closed'): @@ -268,17 +269,18 @@ def test_add_way_after_close(tmp_path, simple_handler): node_opl = "w1 Nn1" filename = tmp_path / (str(uuid.uuid4()) + '.opl') - writer = o.SimpleWriter(str(filename), 1024*1024) + writer = osmium.SimpleWriter(str(filename), 1024*1024) writer.close() with pytest.raises(RuntimeError, match='closed'): simple_handler(node_opl, way=lambda o: writer.add_way(o)) + def test_add_relation_after_close(tmp_path, simple_handler): node_opl = "r54 Mn1@,w3@foo" filename = tmp_path / (str(uuid.uuid4()) + '.opl') - writer = o.SimpleWriter(str(filename), 1024*1024) + writer = osmium.SimpleWriter(str(filename), 1024*1024) writer.close() with pytest.raises(RuntimeError, match='closed'): @@ -289,12 +291,12 @@ def test_add_relation_after_close(tmp_path, simple_handler): def test_catch_errors_in_add_node(tmp_path, final_item): test_file = tmp_path / 'test.opl' - with o.SimpleWriter(str(test_file), 4000) as writer: - writer.add_node(o.osm.mutable.Node(id=123)) + with osmium.SimpleWriter(str(test_file), 4000) as writer: + writer.add_node(osmium.osm.mutable.Node(id=123)) with pytest.raises(TypeError): - writer.add_node(o.osm.mutable.Node(id=124, tags=34)) + writer.add_node(osmium.osm.mutable.Node(id=124, tags=34)) if not final_item: - writer.add_node(o.osm.mutable.Node(id=125)) + writer.add_node(osmium.osm.mutable.Node(id=125)) output = test_file.read_text() @@ -309,12 +311,12 @@ def test_catch_errors_in_add_node(tmp_path, final_item): def test_catch_errors_in_add_way(tmp_path, final_item): test_file = tmp_path / 'test.opl' - with o.SimpleWriter(test_file, 4000) as writer: - writer.add_way(o.osm.mutable.Way(id=123, nodes=[1, 2, 3])) + with osmium.SimpleWriter(test_file, 4000) as writer: + writer.add_way(osmium.osm.mutable.Way(id=123, nodes=[1, 2, 3])) with pytest.raises(TypeError): - writer.add_way(o.osm.mutable.Way(id=124, nodes=34)) + writer.add_way(osmium.osm.mutable.Way(id=124, nodes=34)) if not final_item: - writer.add_way(o.osm.mutable.Way(id=125, nodes=[11, 12])) + writer.add_way(osmium.osm.mutable.Way(id=125, nodes=[11, 12])) output = test_file.read_text() @@ -329,12 +331,12 @@ def test_catch_errors_in_add_way(tmp_path, final_item): def test_catch_errors_in_add_relation(tmp_path, final_item): test_file = tmp_path / 'test.opl' - with o.SimpleWriter(filename=str(test_file), bufsz=4000) as writer: - writer.add_relation(o.osm.mutable.Relation(id=123)) + with osmium.SimpleWriter(filename=str(test_file), bufsz=4000) as writer: + writer.add_relation(osmium.osm.mutable.Relation(id=123)) with pytest.raises(TypeError): - writer.add_relation(o.osm.mutable.Relation(id=124, members=34)) + writer.add_relation(osmium.osm.mutable.Relation(id=124, members=34)) if not final_item: - writer.add_relation(o.osm.mutable.Relation(id=125)) + writer.add_relation(osmium.osm.mutable.Relation(id=125)) output = test_file.read_text() @@ -348,27 +350,26 @@ def test_catch_errors_in_add_relation(tmp_path, final_item): def test_do_not_overwrite_by_default(tmp_path): test_file = tmp_path / 'test.opl' - with o.SimpleWriter(filename=str(test_file), bufsz=4000) as writer: - writer.add_node(o.osm.mutable.Node(id=123)) + with osmium.SimpleWriter(filename=str(test_file), bufsz=4000) as writer: + writer.add_node(osmium.osm.mutable.Node(id=123)) # try to open again with pytest.raises(RuntimeError, match='Open failed'): - o.SimpleWriter(filename=str(test_file)) + osmium.SimpleWriter(filename=str(test_file)) def test_do_overwrite(tmp_path): test_file = tmp_path / 'test.opl' - with o.SimpleWriter(filename=str(test_file), bufsz=4000) as writer: - writer.add_node(o.osm.mutable.Node(id=123)) + with osmium.SimpleWriter(filename=str(test_file), bufsz=4000) as writer: + writer.add_node(osmium.osm.mutable.Node(id=123)) - with o.SimpleWriter(filename=str(test_file), overwrite=True) as writer: + with osmium.SimpleWriter(filename=str(test_file), overwrite=True) as writer: pass - def test_write_to_file(tmp_path): test_file = tmp_path / 'test.txt' - with o.SimpleWriter(o.io.File(test_file, 'opl'), bufsz=4000) as writer: - writer.add_node(o.osm.mutable.Node(id=123)) + with osmium.SimpleWriter(osmium.io.File(test_file, 'opl'), bufsz=4000) as writer: + writer.add_node(osmium.osm.mutable.Node(id=123))