diff --git a/libpysal/cg/ops/tests/test_accessors.py b/libpysal/cg/ops/tests/test_accessors.py index 38472de41..4c5debd66 100644 --- a/libpysal/cg/ops/tests/test_accessors.py +++ b/libpysal/cg/ops/tests/test_accessors.py @@ -1,26 +1,23 @@ -from ....io.geotable.file import read_files as rf -from .. import _accessors as to_test -from ...shapes import Point, Chain, Polygon, Rectangle, LineSegment -from ....common import pandas, RTOL, ATOL -from ....examples import get_path import numpy as np -import unittest as ut +import pytest -PANDAS_EXTINCT = pandas is None +from ....common import ATOL, RTOL, pandas +from ....examples import get_path +from ....io.geotable.file import read_files as rf +from ...shapes import Chain, LineSegment, Point, Polygon, Rectangle +from .. import _accessors as to_test -@ut.skipIf(PANDAS_EXTINCT, "Missing pandas.") -class Test_Accessors(ut.TestCase): - def setUp(self): +class TestAccessors: + def setup_method(self): self.polygons = rf(get_path("Polygon.shp")) self.points = rf(get_path("Point.shp")) self.lines = rf(get_path("Line.shp")) def test_area(self): - - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.area(self.points) - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.area(self.lines) areas = to_test.area(self.polygons).values @@ -28,10 +25,9 @@ def test_area(self): np.testing.assert_allclose(answer, areas, rtol=RTOL, atol=ATOL * 10) def test_bbox(self): - - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.bbox(self.points) - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.bbox(self.lines) answer = [ @@ -60,7 +56,7 @@ def test_bbox(self): np.testing.assert_allclose(ans, bbox, rtol=RTOL, atol=ATOL) def test_bounding_box(self): - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.bounding_box(self.points) line_rects = to_test.bounding_box(self.lines).tolist() @@ -106,12 +102,12 @@ def test_bounding_box(self): for bbox, answer in zip(pgon_bboxes, pgon_answers): np.testing.assert_allclose(bbox, answer, atol=ATOL, rtol=RTOL) for rectangle in line_rects + pgon_rects: - self.assertIsInstance(rectangle, Rectangle) + assert isinstance(rectangle, Rectangle) def test_centroid(self): - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.centroid(self.points) - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.centroid(self.lines) centroids = to_test.centroid(self.polygons).tolist() @@ -127,16 +123,16 @@ def test_centroid(self): def test_holes(self): holed_polygons = rf(get_path("Polygon_Holes.shp")) - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.centroid(self.points) - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.centroid(self.lines) no_holes = to_test.holes(self.polygons).tolist() holes = to_test.holes(holed_polygons).tolist() for elist in no_holes: - self.assertEqual(elist, [[]]) + assert elist == [[]] answers = [ [ @@ -195,7 +191,7 @@ def test_holes(self): np.testing.assert_allclose(sub_hole, sub_answer, rtol=RTOL, atol=ATOL) def test_len(self): - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.len(self.points) line_len = to_test.len(self.lines) @@ -212,7 +208,7 @@ def test_len(self): np.testing.assert_allclose(pgon_len, pgon_answers, rtol=RTOL, atol=ATOL) def test_parts(self): - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.parts(self.points) line_parts = to_test.parts(self.lines) @@ -318,9 +314,9 @@ def test_parts(self): np.testing.assert_allclose(piece, sub_answer, rtol=RTOL, atol=ATOL) def test_perimeter(self): - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.perimeter(self.points) - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.perimeter(self.lines) pgon_perim = to_test.perimeter(self.polygons) @@ -331,9 +327,9 @@ def test_perimeter(self): ) def test_segments(self): - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.segments(self.points) - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.segments(self.polygons) line_segments = to_test.segments(self.lines) @@ -396,12 +392,12 @@ def test_segments(self): for parts, points in zip(flattened, answers): for piece, answer in zip(parts, points): - self.assertIsInstance(piece, LineSegment) + assert isinstance(piece, LineSegment) p1, p2 = piece.p1, piece.p2 np.testing.assert_allclose([p1, p2], answer) def test_vertices(self): - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): to_test.vertices(self.points) line_verts = to_test.vertices(self.lines).tolist() diff --git a/libpysal/cg/ops/tests/test_shapely.py b/libpysal/cg/ops/tests/test_shapely.py index f116fb1ac..ab51a534d 100644 --- a/libpysal/cg/ops/tests/test_shapely.py +++ b/libpysal/cg/ops/tests/test_shapely.py @@ -1,4 +1,4 @@ -import unittest as ut +import pytest from .. import _shapely as sht from ...shapes import Point, Chain, Polygon @@ -10,9 +10,9 @@ from warnings import warn -@ut.skip("Skipping shapely during reorg.") -class Test_Shapely(ut.TestCase): - def setUp(self): +@pytest.mark.skip("Skipping shapely during reorg.") +class Test_Shapely: + def setup_method(self): self.polygons = rf(get_path("Polygon.shp")) self.points = rf(get_path("Point.shp")) self.lines = rf(get_path("Line.shp")) @@ -36,7 +36,7 @@ def compare(self, func_name, df, **kwargs): if comp.is_shape(tabular) and comp.is_shape(shapely): comp.equal(tabular, shapely) else: - self.assertEqual(tabular, shapely) + assert tabular == shapely except NotImplementedError as e: warn("The shapely/PySAL bridge is not implemented: {}.".format(e)) return True @@ -123,13 +123,13 @@ def test_has_z(self): def test_is_empty(self): """ PySAL doesn't really support empty shapes. Like, the following errors out: - + ``` ps.cg.Polygon([[]]) ``` - + and you can make it work by: - + ``` ps.cg.Polygon([[()]]) ``` @@ -137,7 +137,7 @@ def test_is_empty(self): but that won't convert over to shapely. So, we're only testing the negative here. - + """ for df in self.dframes: self.compare("is_empty", df) @@ -219,5 +219,5 @@ def test_interpolate(self): if isinstance(df.geometry[0], Chain): self.compare("interpolate", df, distance=np.random.randint(10)) else: - with self.assertRaises(TypeError): + with pytest.raises(TypeError): self.compare("interpolate", df, distance=np.random.randint(10)) diff --git a/libpysal/cg/ops/tests/test_tabular.py b/libpysal/cg/ops/tests/test_tabular.py index e2c64a696..9585b5ea3 100644 --- a/libpysal/cg/ops/tests/test_tabular.py +++ b/libpysal/cg/ops/tests/test_tabular.py @@ -1,24 +1,16 @@ -import unittest as ut -from .. import tabular as ta -from ....common import RTOL, ATOL, pandas, requires as _requires +import numpy as np + +from ....common import ATOL, RTOL, pandas +from ....common import requires as _requires from ....examples import get_path -from ...shapes import Polygon from ....io import geotable as pdio from ... import ops as GIS -import numpy as np - -try: - import shapely as shp -except ImportError: - shp = None - -PANDAS_EXTINCT = pandas is None -SHAPELY_EXTINCT = shp is None +from ...shapes import Polygon +from .. import tabular as ta -@ut.skipIf(PANDAS_EXTINCT or SHAPELY_EXTINCT, "Missing pandas or shapely.") -class Test_Tabular(ut.TestCase): - def setUp(self): +class TestTabular: + def setup_method(self): import pandas as pd self.columbus = pdio.read_files(get_path("columbus.shp")) @@ -40,11 +32,11 @@ def test_round_trip(self): import pandas as pd geodf = GIS.tabular.to_gdf(self.columbus) - self.assertIsInstance(geodf, gpd.GeoDataFrame) + assert isinstance(geodf, gpd.GeoDataFrame) new_df = GIS.tabular.to_df(geodf) - self.assertIsInstance(new_df, pd.DataFrame) + assert isinstance(new_df, pd.DataFrame) for new, old in zip(new_df.geometry, self.columbus.geometry): - self.assertEqual(new, old) + assert new == old def test_spatial_join(self): pass @@ -54,18 +46,17 @@ def test_spatial_overlay(self): def test_dissolve(self): out = GIS.tabular.dissolve(self.exdf, by="regime") - self.assertEqual(out[0].area, 2.0) - self.assertEqual(out[1].area, 2.0) + assert out[0].area == 2.0 + assert out[1].area == 2.0 answer_vertices0 = set([(0, 0), (0, 1), (0, 2), (1, 2), (1, 1), (1, 0), (0, 0)]) answer_vertices1 = set([(2, 1), (2, 0), (1, 0), (1, 1), (1, 2), (2, 2), (2, 1)]) - s0 = set([tuple(map(int,t)) for t in out[0].vertices]) - s1 = set([tuple(map(int,t)) for t in out[1].vertices]) - - self.assertTrue(s0==answer_vertices0) - self.assertTrue(s1==answer_vertices1) + s0 = set([tuple(map(int, t)) for t in out[0].vertices]) + s1 = set([tuple(map(int, t)) for t in out[1].vertices]) + assert s0 == answer_vertices0 + assert s1 == answer_vertices1 def test_clip(self): pass @@ -75,7 +66,7 @@ def test_erase(self): def test_union(self): new_geom = GIS.tabular.union(self.exdf) - self.assertEqual(new_geom.area, 4) + assert new_geom.area == 4 def test_intersection(self): pass diff --git a/libpysal/cg/tests/test_ashapes.py b/libpysal/cg/tests/test_ashapes.py index c2a1e7502..c0c5b3bb5 100644 --- a/libpysal/cg/tests/test_ashapes.py +++ b/libpysal/cg/tests/test_ashapes.py @@ -18,8 +18,8 @@ @skipIf(GEOPANDAS_EXTINCT, "Geopandas is missing, so test will not run.") -class Test_Alpha_Shapes(TestCase): - def setUp(self): +class Test_Alpha_Shapes: + def setup_method(self): eberly = geopandas.read_file(get_path("eberly_net.shp")) eberly_vertices = eberly.geometry.apply( lambda x: np.hstack(x.xy).reshape(2, 2).T diff --git a/libpysal/cg/tests/test_geoJSON.py b/libpysal/cg/tests/test_geoJSON.py index f952f592b..ca7deb3ea 100644 --- a/libpysal/cg/tests/test_geoJSON.py +++ b/libpysal/cg/tests/test_geoJSON.py @@ -1,15 +1,13 @@ from ..shapes import Point, Chain, asShape from ...io.fileio import FileIO as psopen from ... import examples as pysal_examples -import doctest -import unittest -class test_MultiPloygon(unittest.TestCase): +class Testtest_MultiPloygon: def test___init__1(self): """Tests conversion of polygons with multiple shells to geoJSON multipolygons and back. - + """ ncovr = pysal_examples.load_example("NCOVR") @@ -19,12 +17,12 @@ def test___init__1(self): for poly in multipolygons: json = poly.__geo_interface__ shape = asShape(json) - self.assertEqual(json["type"], "MultiPolygon") - self.assertEqual(str(shape.holes), str(poly.holes)) - self.assertEqual(str(shape.parts), str(poly.parts)) + assert json["type"] == "MultiPolygon" + assert str(shape.holes) == str(poly.holes) + assert str(shape.parts) == str(poly.parts) -class test_MultiLineString(unittest.TestCase): +class Testtest_MultiLineString: def test_multipart_chain(self): vertices = [ [Point((0, 0)), Point((1, 0)), Point((1, 5))], @@ -39,22 +37,16 @@ def test_multipart_chain(self): chain2 = Chain(vertices) json = chain0.__geo_interface__ - self.assertEqual(json["type"], "LineString") - self.assertEqual(len(json["coordinates"]), 3) + assert json["type"] == "LineString" + assert len(json["coordinates"]) == 3 json = chain1.__geo_interface__ - self.assertEqual(json["type"], "LineString") - self.assertEqual(len(json["coordinates"]), 3) + assert json["type"] == "LineString" + assert len(json["coordinates"]) == 3 json = chain2.__geo_interface__ - self.assertEqual(json["type"], "MultiLineString") - self.assertEqual(len(json["coordinates"]), 2) + assert json["type"] == "MultiLineString" + assert len(json["coordinates"]) == 2 chain3 = asShape(json) - self.assertEqual(chain2.parts, chain3.parts) - - -if __name__ == "__main__": - unittest.main() - # runner = unittest.TextTestRunner() - # runner.run(suite) + assert chain2.parts == chain3.parts diff --git a/libpysal/cg/tests/test_locators.py b/libpysal/cg/tests/test_locators.py index 30aa4318c..a8d157cb6 100644 --- a/libpysal/cg/tests/test_locators.py +++ b/libpysal/cg/tests/test_locators.py @@ -1,11 +1,10 @@ """locators Unittest.""" -from ..shapes import * from ..locators import * -import unittest +from ..shapes import * -class PolygonLocator_Tester(unittest.TestCase): - def setUp(self): +class TestPolygonLocator: + def setup_method(self): p1 = Polygon([Point((0, 1)), Point((4, 5)), Point((5, 1))]) p2 = Polygon([Point((3, 9)), Point((6, 7)), Point((1, 1))]) p3 = Polygon([Point((7, 1)), Point((8, 7)), Point((9, 1))]) @@ -27,39 +26,28 @@ def setUp(self): polys.append(pg([sw, se, ne, nw])) self.pl2 = PolygonLocator(polys) - def test_PolygonLocator(self): + def test_polygon_locator(self): qr = Rectangle(3, 7, 5, 8) res = self.pl.inside(qr) - self.assertEqual(len(res), 0) + assert len(res) == 0 def test_inside(self): qr = Rectangle(3, 3, 5, 5) res = self.pl.inside(qr) - self.assertEqual(len(res), 0) + assert len(res) == 0 qr = Rectangle(0, 0, 5, 5) res = self.pl.inside(qr) - self.assertEqual(len(res), 1) + assert len(res) == 1 def test_overlapping(self): qr = Rectangle(3, 3, 5, 5) res = self.pl.overlapping(qr) - self.assertEqual(len(res), 2) + assert len(res) == 2 qr = Rectangle(8, 3, 10, 10) res = self.pl.overlapping(qr) - self.assertEqual(len(res), 1) + assert len(res) == 1 qr = Rectangle(2, 12, 35, 15) res = self.pl2.overlapping(qr) - self.assertEqual(len(res), 4) - - -suite = unittest.TestSuite() -test_classes = [PolygonLocator_Tester] -for i in test_classes: - a = unittest.TestLoader().loadTestsFromTestCase(i) - suite.addTest(a) - -if __name__ == "__main__": - runner = unittest.TextTestRunner() - runner.run(suite) + assert len(res) == 4 \ No newline at end of file diff --git a/libpysal/cg/tests/test_polygonQuadTreeStructure.py b/libpysal/cg/tests/test_polygonQuadTreeStructure.py index 27528a831..c966c6e40 100644 --- a/libpysal/cg/tests/test_polygonQuadTreeStructure.py +++ b/libpysal/cg/tests/test_polygonQuadTreeStructure.py @@ -1,14 +1,13 @@ """locators Unittest.""" from ..polygonQuadTreeStructure import QuadTreeStructureSingleRing from ..shapes import Ring -import unittest -class TestQuadTreeStructureSingleRing(unittest.TestCase): - def test_QuadTreeStructureSingleRing(self): +class TestQuadTreeStructureSingleRing: + def test_quad_tree_structure_single_ring(self): """Tests if the class could successfully determine if a point is inside of a polygon. - + """ ring_texas = Ring( diff --git a/libpysal/cg/tests/test_rtree.py b/libpysal/cg/tests/test_rtree.py index caee13a1a..6980f14f3 100644 --- a/libpysal/cg/tests/test_rtree.py +++ b/libpysal/cg/tests/test_rtree.py @@ -1,10 +1,9 @@ """pyrtree Unittest.""" -from ..rtree import RTree, Rect -import unittest +from ..rtree import Rect, RTree -class Pyrtree_Tester(unittest.TestCase): - def setUp(self): +class TestPyrtree: + def setup_method(self): k = 10 w = 20 objects = {} @@ -23,43 +22,32 @@ def test_rtree(self): t = RTree() for object in self.objects: t.insert(object, self.objects[object]) - self.assertEqual(len(self.objects), 100) + assert len(self.objects) == 100 qr = Rect(5, 5, 25, 25) # find objects with mbrs intersecting with qr res = [r.leaf_obj() for r in t.query_rect(qr) if r.is_leaf()] - self.assertEqual(len(res), 4) + assert len(res) == 4 res.sort() - self.assertEqual(res, [0, 1, 10, 11]) + assert res == [0, 1, 10, 11] # vertices are shared by all coincident rectangles res = [r.leaf_obj() for r in t.query_point((20.0, 20.0)) if r.is_leaf()] - self.assertEqual(len(res), 4) + assert len(res) == 4 res = [r.leaf_obj() for r in t.query_point((21, 20)) if r.is_leaf()] - self.assertEqual(len(res), 2) + assert len(res) == 2 # single internal point res = [r.leaf_obj() for r in t.query_point((21, 21)) if r.is_leaf()] - self.assertEqual(len(res), 1) + assert len(res) == 1 # single external point res = [r.leaf_obj() for r in t.query_point((-12, 21)) if r.is_leaf()] - self.assertEqual(len(res), 0) + assert len(res) == 0 qr = Rect(5, 6, 65, 7) res = [r.leaf_obj() for r in t.query_rect((qr)) if r.is_leaf()] - self.assertEqual(len(res), 4) - - -suite = unittest.TestSuite() -test_classes = [Pyrtree_Tester] -for i in test_classes: - a = unittest.TestLoader().loadTestsFromTestCase(i) - suite.addTest(a) - -if __name__ == "__main__": - runner = unittest.TextTestRunner() - runner.run(suite) + assert len(res) == 4 diff --git a/libpysal/cg/tests/test_segmentLocator.py b/libpysal/cg/tests/test_segmentLocator.py index d2ce4e00a..98c3db429 100644 --- a/libpysal/cg/tests/test_segmentLocator.py +++ b/libpysal/cg/tests/test_segmentLocator.py @@ -1,11 +1,10 @@ """Segment Locator Unittest.""" from ..shapes import * from ..segmentLocator import * -import unittest -class SegmentGrid_Tester(unittest.TestCase): - def setUp(self): +class TestSegmentGrid: + def setup_method(self): # 10x10 grid with four line segments, one for each edge of the grid. self.grid = SegmentGrid(Rectangle(0, 0, 10, 10), 1) self.grid.add(LineSegment(Point((0.0, 0.0)), Point((0.0, 10.0))), 0) @@ -15,33 +14,22 @@ def setUp(self): def test_nearest_1(self): # Center - self.assertEqual([0, 1, 2, 3], self.grid.nearest(Point((5.0, 5.0)))) + assert [0, 1, 2, 3] == self.grid.nearest(Point((5.0, 5.0))) # Left Edge - self.assertEqual([0], self.grid.nearest(Point((0.0, 5.0)))) + assert [0] == self.grid.nearest(Point((0.0, 5.0))) # Top Edge - self.assertEqual([1], self.grid.nearest(Point((5.0, 10.0)))) + assert [1] == self.grid.nearest(Point((5.0, 10.0))) # Right Edge - self.assertEqual([2], self.grid.nearest(Point((10.0, 5.0)))) + assert [2] == self.grid.nearest(Point((10.0, 5.0))) # Bottom Edge - self.assertEqual([3], self.grid.nearest(Point((5.0, 0.0)))) + assert [3] == self.grid.nearest(Point((5.0, 0.0))) def test_nearest_2(self): # Left Edge - self.assertEqual([0, 1, 3], self.grid.nearest(Point((-100000.0, 5.0)))) + assert [0, 1, 3] == self.grid.nearest(Point((-100000.0, 5.0))) # Right Edge - self.assertEqual([1, 2, 3], self.grid.nearest(Point((100000.0, 5.0)))) + assert [1, 2, 3] == self.grid.nearest(Point((100000.0, 5.0))) # Bottom Edge - self.assertEqual([0, 2, 3], self.grid.nearest(Point((5.0, -100000.0)))) + assert [0, 2, 3] == self.grid.nearest(Point((5.0, -100000.0))) # Top Edge - self.assertEqual([0, 1, 2], self.grid.nearest(Point((5.0, 100000.0)))) - - -suite = unittest.TestSuite() -test_classes = [SegmentGrid_Tester] -for i in test_classes: - a = unittest.TestLoader().loadTestsFromTestCase(i) - suite.addTest(a) - -if __name__ == "__main__": - runner = unittest.TextTestRunner() - runner.run(suite) + assert [0, 1, 2] == self.grid.nearest(Point((5.0, 100000.0))) \ No newline at end of file diff --git a/libpysal/cg/tests/test_shapes.py b/libpysal/cg/tests/test_shapes.py index 37530178d..42229fc8d 100644 --- a/libpysal/cg/tests/test_shapes.py +++ b/libpysal/cg/tests/test_shapes.py @@ -1,9 +1,8 @@ +import pytest from ..shapes import Point, LineSegment, Line, Ray, Chain, Rectangle, Polygon -import doctest -import unittest -class test_Point(unittest.TestCase): +class Testtest_Point: def test___init__1(self): """Tests whether points are created without issue.""" @@ -16,25 +15,25 @@ def test___str__1(self): for l in [(-5, 10), (0, -6.0), (float(1e300), -1e300)]: p = Point(l) # Recast to floats like point does - self.assertEqual(str(p), str((float(l[0]), float(l[1])))) + assert str(p) == str((float(l[0]), float(l[1]))) -class test_LineSegment(unittest.TestCase): +class Testtest_LineSegment: def test_is_ccw1(self): """Test corner cases for horizontal segment starting at origin.""" ls = LineSegment(Point((0, 0)), Point((5, 0))) # At positive boundary beyond segment - self.assertFalse(ls.is_ccw(Point((10, 0)))) + assert not ls.is_ccw(Point((10, 0))) # On segment - self.assertFalse(ls.is_ccw(Point((3, 0)))) + assert not ls.is_ccw(Point((3, 0))) # At negative boundary beyond segment - self.assertFalse(ls.is_ccw(Point((-10, 0)))) + assert not ls.is_ccw(Point((-10, 0))) # Endpoint of segment - self.assertFalse(ls.is_ccw(Point((0, 0)))) + assert not ls.is_ccw(Point((0, 0))) # Endpoint of segment - self.assertFalse(ls.is_ccw(Point((5, 0)))) + assert not ls.is_ccw(Point((5, 0))) def test_is_ccw2(self): """Test corner cases for vertical segment ending at origin.""" @@ -42,15 +41,15 @@ def test_is_ccw2(self): ls = LineSegment(Point((0, -5)), Point((0, 0))) # At positive boundary beyond segment - self.assertFalse(ls.is_ccw(Point((0, 10)))) + assert not ls.is_ccw(Point((0, 10))) # On segment - self.assertFalse(ls.is_ccw(Point((0, -3)))) + assert not ls.is_ccw(Point((0, -3))) # At negative boundary beyond segment - self.assertFalse(ls.is_ccw(Point((0, -10)))) + assert not ls.is_ccw(Point((0, -10))) # Endpoint of segment - self.assertFalse(ls.is_ccw(Point((0, -5)))) + assert not ls.is_ccw(Point((0, -5))) # Endpoint of segment - self.assertFalse(ls.is_ccw(Point((0, 0)))) + assert not ls.is_ccw(Point((0, 0))) def test_is_ccw3(self): """Test corner cases for non-axis-aligned segment not through origin.""" @@ -58,15 +57,15 @@ def test_is_ccw3(self): ls = LineSegment(Point((0, 1)), Point((5, 6))) # At positive boundary beyond segment - self.assertFalse(ls.is_ccw(Point((10, 11)))) + assert not ls.is_ccw(Point((10, 11))) # On segment - self.assertFalse(ls.is_ccw(Point((3, 4)))) + assert not ls.is_ccw(Point((3, 4))) # At negative boundary beyond segment - self.assertFalse(ls.is_ccw(Point((-10, -9)))) + assert not ls.is_ccw(Point((-10, -9))) # Endpoint of segment - self.assertFalse(ls.is_ccw(Point((0, 1)))) + assert not ls.is_ccw(Point((0, 1))) # Endpoint of segment - self.assertFalse(ls.is_ccw(Point((5, 6)))) + assert not ls.is_ccw(Point((5, 6))) def test_is_cw1(self): """Test corner cases for horizontal segment starting at origin.""" @@ -74,15 +73,15 @@ def test_is_cw1(self): ls = LineSegment(Point((0, 0)), Point((5, 0))) # At positive boundary beyond segment - self.assertFalse(ls.is_cw(Point((10, 0)))) + assert not ls.is_cw(Point((10, 0))) # On segment - self.assertFalse(ls.is_cw(Point((3, 0)))) + assert not ls.is_cw(Point((3, 0))) # At negative boundary beyond segment - self.assertFalse(ls.is_cw(Point((-10, 0)))) + assert not ls.is_cw(Point((-10, 0))) # Endpoint of segment - self.assertFalse(ls.is_cw(Point((0, 0)))) + assert not ls.is_cw(Point((0, 0))) # Endpoint of segment - self.assertFalse(ls.is_cw(Point((5, 0)))) + assert not ls.is_cw(Point((5, 0))) def test_is_cw2(self): """Test corner cases for vertical segment ending at origin.""" @@ -90,15 +89,15 @@ def test_is_cw2(self): ls = LineSegment(Point((0, -5)), Point((0, 0))) # At positive boundary beyond segment - self.assertFalse(ls.is_cw(Point((0, 10)))) + assert not ls.is_cw(Point((0, 10))) # On segment - self.assertFalse(ls.is_cw(Point((0, -3)))) + assert not ls.is_cw(Point((0, -3))) # At negative boundary beyond segment - self.assertFalse(ls.is_cw(Point((0, -10)))) + assert not ls.is_cw(Point((0, -10))) # Endpoint of segment - self.assertFalse(ls.is_cw(Point((0, -5)))) + assert not ls.is_cw(Point((0, -5))) # Endpoint of segment - self.assertFalse(ls.is_cw(Point((0, 0)))) + assert not ls.is_cw(Point((0, 0))) def test_is_cw3(self): """Test corner cases for non-axis-aligned segment not through origin.""" @@ -106,68 +105,68 @@ def test_is_cw3(self): ls = LineSegment(Point((0, 1)), Point((5, 6))) # At positive boundary beyond segment - self.assertFalse(ls.is_cw(Point((10, 11)))) + assert not ls.is_cw(Point((10, 11))) # On segment - self.assertFalse(ls.is_cw(Point((3, 4)))) + assert not ls.is_cw(Point((3, 4))) # At negative boundary beyond segment - self.assertFalse(ls.is_cw(Point((-10, -9)))) + assert not ls.is_cw(Point((-10, -9))) # Endpoint of segment - self.assertFalse(ls.is_cw(Point((0, 1)))) + assert not ls.is_cw(Point((0, 1))) # Endpoint of segment - self.assertFalse(ls.is_cw(Point((5, 6)))) + assert not ls.is_cw(Point((5, 6))) def test_get_swap1(self): """Tests corner cases.""" ls = LineSegment(Point((0, 0)), Point((10, 0))) swap = ls.get_swap() - self.assertEqual(ls.p1, swap.p2) - self.assertEqual(ls.p2, swap.p1) + assert ls.p1 == swap.p2 + assert ls.p2 == swap.p1 ls = LineSegment(Point((-5, 0)), Point((5, 0))) swap = ls.get_swap() - self.assertEqual(ls.p1, swap.p2) - self.assertEqual(ls.p2, swap.p1) + assert ls.p1 == swap.p2 + assert ls.p2 == swap.p1 ls = LineSegment(Point((0, 0)), Point((0, 0))) swap = ls.get_swap() - self.assertEqual(ls.p1, swap.p2) - self.assertEqual(ls.p2, swap.p1) + assert ls.p1 == swap.p2 + assert ls.p2 == swap.p1 ls = LineSegment(Point((5, 5)), Point((5, 5))) swap = ls.get_swap() - self.assertEqual(ls.p1, swap.p2) - self.assertEqual(ls.p2, swap.p1) + assert ls.p1 == swap.p2 + assert ls.p2 == swap.p1 def test_bounding_box(self): """Tests corner cases.""" ls = LineSegment(Point((0, 0)), Point((0, 10))) - self.assertEqual(ls.bounding_box.left, 0) - self.assertEqual(ls.bounding_box.lower, 0) - self.assertEqual(ls.bounding_box.right, 0) - self.assertEqual(ls.bounding_box.upper, 10) + assert ls.bounding_box.left == 0 + assert ls.bounding_box.lower == 0 + assert ls.bounding_box.right == 0 + assert ls.bounding_box.upper == 10 ls = LineSegment(Point((0, 0)), Point((-3, -4))) - self.assertEqual(ls.bounding_box.left, -3) - self.assertEqual(ls.bounding_box.lower, -4) - self.assertEqual(ls.bounding_box.right, 0) - self.assertEqual(ls.bounding_box.upper, 0) + assert ls.bounding_box.left == -3 + assert ls.bounding_box.lower == -4 + assert ls.bounding_box.right == 0 + assert ls.bounding_box.upper == 0 ls = LineSegment(Point((-5, 0)), Point((3, 0))) - self.assertEqual(ls.bounding_box.left, -5) - self.assertEqual(ls.bounding_box.lower, 0) - self.assertEqual(ls.bounding_box.right, 3) - self.assertEqual(ls.bounding_box.upper, 0) + assert ls.bounding_box.left == -5 + assert ls.bounding_box.lower == 0 + assert ls.bounding_box.right == 3 + assert ls.bounding_box.upper == 0 def test_len1(self): """Tests corner cases.""" ls = LineSegment(Point((0, 0)), Point((0, 0))) - self.assertEqual(ls.len, 0) + assert ls.len == 0 ls = LineSegment(Point((0, 0)), Point((-3, 0))) - self.assertEqual(ls.len, 3) + assert ls.len == 3 def test_line1(self): """Tests corner cases.""" @@ -175,30 +174,30 @@ def test_line1(self): import math ls = LineSegment(Point((0, 0)), Point((1, 0))) - self.assertEqual(ls.line.m, 0) - self.assertEqual(ls.line.b, 0) + assert ls.line.m == 0 + assert ls.line.b == 0 ls = LineSegment(Point((0, 0)), Point((0, 1))) - self.assertEqual(ls.line.m, float("inf")) - self.assertTrue(math.isnan(ls.line.b)) + assert ls.line.m == float("inf") + assert math.isnan(ls.line.b) ls = LineSegment(Point((0, 0)), Point((0, -1))) - self.assertEqual(ls.line.m, float("inf")) - self.assertTrue(math.isnan(ls.line.b)) + assert ls.line.m == float("inf") + assert math.isnan(ls.line.b) ls = LineSegment(Point((0, 0)), Point((0, 0))) - self.assertEqual(ls.line, None) + assert ls.line == None ls = LineSegment(Point((5, 0)), Point((10, 0))) ls1 = LineSegment(Point((5, 0)), Point((10, 1))) - self.assertTrue(ls.intersect(ls1)) + assert ls.intersect(ls1) ls2 = LineSegment(Point((5, 1)), Point((10, 1))) - self.assertFalse(ls.intersect(ls2)) + assert not ls.intersect(ls2) ls2 = LineSegment(Point((7, -1)), Point((7, 2))) - self.assertTrue(ls.intersect(ls2)) + assert ls.intersect(ls2) -class test_Line(unittest.TestCase): +class Testtest_Line: def test___init__1(self): """Tests a variety of generic cases.""" @@ -209,19 +208,19 @@ def test_y1(self): """Tests a variety of generic and special cases (+-infinity).""" l = Line(0, 0) - self.assertEqual(l.y(0), 0) - self.assertEqual(l.y(-1e600), 0) - self.assertEqual(l.y(1e600), 0) + assert l.y(0) == 0 + assert l.y(-1e600) == 0 + assert l.y(1e600) == 0 l = Line(1, 1) - self.assertEqual(l.y(2), 3) - self.assertEqual(l.y(-1e600), -1e600) - self.assertEqual(l.y(1e600), 1e600) + assert l.y(2) == 3 + assert l.y(-1e600) == -1e600 + assert l.y(1e600) == 1e600 l = Line(-1, 1) - self.assertEqual(l.y(2), -1) - self.assertEqual(l.y(-1e600), 1e600) - self.assertEqual(l.y(1e600), -1e600) + assert l.y(2) == -1 + assert l.y(-1e600) == 1e600 + assert l.y(1e600) == -1e600 def test_x1(self): """Tests a variety of generic and special cases (+-infinity).""" @@ -229,25 +228,25 @@ def test_x1(self): l = Line(0, 0) # self.assertEquals(l.x(0), 0) - with self.assertRaises(ArithmeticError): + with pytest.raises(ArithmeticError): l.x(0) - with self.assertRaises(ArithmeticError): + with pytest.raises(ArithmeticError): l.x(-1e600) - with self.assertRaises(ArithmeticError): + with pytest.raises(ArithmeticError): l.x(1e600) l = Line(1, 1) - self.assertEqual(l.x(3), 2) - self.assertEqual(l.x(-1e600), -1e600) - self.assertEqual(l.x(1e600), 1e600) + assert l.x(3) == 2 + assert l.x(-1e600) == -1e600 + assert l.x(1e600) == 1e600 l = Line(-1, 1) - self.assertEqual(l.x(2), -1) - self.assertEqual(l.x(-1e600), 1e600) - self.assertEqual(l.x(1e600), -1e600) + assert l.x(2) == -1 + assert l.x(-1e600) == 1e600 + assert l.x(1e600) == -1e600 -class test_Ray(unittest.TestCase): +class Testtest_Ray: def test___init__1(self): """Tests generic cases.""" @@ -255,7 +254,7 @@ def test___init__1(self): r = Ray(Point((8, -3)), Point((-5, 9))) -class test_Chain(unittest.TestCase): +class Testtest_Chain: def test___init__1(self): """Generic testing that no exception is thrown.""" @@ -273,13 +272,13 @@ def test_vertices1(self): Point((1, 1)), Point((2, 5)), ] - self.assertEqual(Chain(vertices).vertices, vertices) + assert Chain(vertices).vertices == vertices vertices = [ [Point((0, 0)), Point((1, 1)), Point((2, 5))], [Point((0, 0)), Point((1, 1)), Point((2, 5))], ] - self.assertEqual(Chain(vertices).vertices, vertices[0] + vertices[1]) + assert Chain(vertices).vertices == vertices[0] + vertices[1] def test_parts1(self): """Generic testing of parts functionality.""" @@ -292,13 +291,13 @@ def test_parts1(self): Point((1, 1)), Point((2, 5)), ] - self.assertEqual(Chain(vertices).parts, [vertices]) + assert Chain(vertices).parts == [vertices] vertices = [ [Point((0, 0)), Point((1, 1)), Point((2, 5))], [Point((0, 0)), Point((1, 1)), Point((2, 5))], ] - self.assertEqual(Chain(vertices).parts, vertices) + assert Chain(vertices).parts == vertices def test_bounding_box1(self): """Test correctness with multiple parts.""" @@ -308,25 +307,25 @@ def test_bounding_box1(self): [Point((-5, -5)), Point((0, 0)), Point((2, 5))], ] bb = Chain(vertices).bounding_box - self.assertEqual(bb.left, -5) - self.assertEqual(bb.lower, -5) - self.assertEqual(bb.right, 2) - self.assertEqual(bb.upper, 6) + assert bb.left == -5 + assert bb.lower == -5 + assert bb.right == 2 + assert bb.upper == 6 def test_len1(self): """Test correctness with multiple parts and zero-length point-to-point distances. - + """ vertices = [ [Point((0, 0)), Point((1, 0)), Point((1, 5))], [Point((-5, -5)), Point((-5, 0)), Point((0, 0)), Point((0, 0))], ] - self.assertEqual(Chain(vertices).len, 6 + 10) + assert Chain(vertices).len == 6 + 10 -class test_Polygon(unittest.TestCase): +class Testtest_Polygon: def test___init__1(self): """Test various input configurations (list vs. lists of lists, holes).""" @@ -383,7 +382,7 @@ def test_area1(self): [Point((30, 30)), Point((40, 30)), Point((40, 40)), Point((30, 40))], ] ) - self.assertEqual(p.area, 200) + assert p.area == 200 def test_area2(self): """Test holes.""" @@ -392,7 +391,7 @@ def test_area2(self): [Point((0, 0)), Point((10, 0)), Point((10, 10)), Point((0, 10))], holes=[Point((2, 2)), Point((4, 2)), Point((4, 4)), Point((2, 4))], ) - self.assertEqual(p.area, 100 - 4) + assert p.area == 100 - 4 p = Polygon( [Point((0, 0)), Point((10, 0)), Point((10, 10)), Point((0, 10))], @@ -401,7 +400,7 @@ def test_area2(self): [Point((6, 6)), Point((6, 8)), Point((8, 8)), Point((8, 6))], ], ) - self.assertEqual(p.area, 100 - (4 + 4)) + assert p.area == 100 - (4 + 4) p = Polygon( [ @@ -413,16 +412,16 @@ def test_area2(self): [Point((36, 36)), Point((36, 38)), Point((38, 38)), Point((38, 36))], ], ) - self.assertEqual(p.area, 200 - (4 + 4)) + assert p.area == 200 - (4 + 4) def test_area4(self): """Test polygons with vertices in both orders (cw, ccw).""" p = Polygon([Point((0, 0)), Point((10, 0)), Point((10, 10)), Point((0, 10))]) - self.assertEqual(p.area, 100) + assert p.area == 100 p = Polygon([Point((0, 0)), Point((0, 10)), Point((10, 10)), Point((10, 0))]) - self.assertEqual(p.area, 100) + assert p.area == 100 def test_bounding_box1(self): """Test polygons with multiple parts.""" @@ -434,10 +433,10 @@ def test_bounding_box1(self): ] ) bb = p.bounding_box - self.assertEqual(bb.left, 0) - self.assertEqual(bb.lower, 0) - self.assertEqual(bb.right, 40) - self.assertEqual(bb.upper, 40) + assert bb.left == 0 + assert bb.lower == 0 + assert bb.right == 40 + assert bb.upper == 40 def test_centroid1(self): """Test polygons with multiple parts of the same size.""" @@ -449,8 +448,8 @@ def test_centroid1(self): ] ) c = p.centroid - self.assertEqual(c[0], 20) - self.assertEqual(c[1], 20) + assert c[0] == 20 + assert c[1] == 20 def test_centroid2(self): """Test polygons with multiple parts of different size.""" @@ -462,8 +461,8 @@ def test_centroid2(self): ] ) c = p.centroid - self.assertEqual(c[0], 10.5) - self.assertEqual(c[1], 10.5) + assert c[0] == 10.5 + assert c[1] == 10.5 def test_holes1(self): """Test for correct vertex values/order.""" @@ -472,17 +471,14 @@ def test_holes1(self): [Point((0, 0)), Point((10, 0)), Point((10, 10)), Point((0, 10))], holes=[Point((2, 2)), Point((4, 2)), Point((4, 4)), Point((2, 4))], ) - self.assertEqual(len(p.holes), 1) + assert len(p.holes) == 1 e_holes = [Point((2, 2)), Point((2, 4)), Point((4, 4)), Point((4, 2))] - self.assertTrue( - p.holes[0] - in [ - e_holes, - [e_holes[-1]] + e_holes[:3], - e_holes[-2:] + e_holes[:2], - e_holes[-3:] + [e_holes[0]], - ] - ) + assert p.holes[0] in [ + e_holes, + [e_holes[-1]] + e_holes[:3], + e_holes[-2:] + e_holes[:2], + e_holes[-3:] + [e_holes[0]], + ] def test_holes2(self): """Test for multiple holes.""" @@ -495,7 +491,7 @@ def test_holes2(self): ], ) holes = p.holes - self.assertEqual(len(holes), 2) + assert len(holes) == 2 def test_parts1(self): """Test for correct vertex values/order.""" @@ -506,38 +502,28 @@ def test_parts1(self): [Point((30, 30)), Point((40, 30)), Point((30, 40))], ] ) - self.assertEqual(len(p.parts), 2) + assert len(p.parts) == 2 part1 = [Point((0, 0)), Point((0, 10)), Point((10, 10)), Point((10, 0))] part2 = [Point((30, 30)), Point((30, 40)), Point((40, 30))] if len(p.parts[0]) == 4: - self.assertTrue( - p.parts[0] - in [ - part1, - part1[-1:] + part1[:3], - part1[-2:] + part1[:2], - part1[-3:] + part1[:1], - ] - ) - self.assertTrue( - p.parts[1] in [part2, part2[-1:] + part2[:2], part2[-2:] + part2[:1]] - ) + assert p.parts[0] in [ + part1, + part1[-1:] + part1[:3], + part1[-2:] + part1[:2], + part1[-3:] + part1[:1], + ] + assert p.parts[1] in [part2, part2[-1:] + part2[:2], part2[-2:] + part2[:1]] elif len(p.parts[0]) == 3: - self.assertTrue( - p.parts[0] in [part2, part2[-1:] + part2[:2], part2[-2:] + part2[:1]] - ) - self.assertTrue( - p.parts[1] - in [ - part1, - part1[-1:] + part1[:3], - part1[-2:] + part1[:2], - part1[-3:] + part1[:1], - ] - ) + assert p.parts[0] in [part2, part2[-1:] + part2[:2], part2[-2:] + part2[:1]] + assert p.parts[1] in [ + part1, + part1[-1:] + part1[:3], + part1[-2:] + part1[:2], + part1[-3:] + part1[:1], + ] else: - self.fail() + pytest.fail() def test_perimeter1(self): """Test with multiple parts.""" @@ -548,7 +534,7 @@ def test_perimeter1(self): [Point((30, 30)), Point((40, 30)), Point((40, 40)), Point((30, 40))], ] ) - self.assertEqual(p.perimeter, 80) + assert p.perimeter == 80 def test_perimeter2(self): """Test with holes.""" @@ -563,23 +549,20 @@ def test_perimeter2(self): [Point((6, 6)), Point((6, 8)), Point((8, 8)), Point((8, 6))], ], ) - self.assertEqual(p.perimeter, 80 + 16) + assert p.perimeter == 80 + 16 def test_vertices1(self): """Test for correct values/order of vertices.""" p = Polygon([Point((0, 0)), Point((10, 0)), Point((10, 10)), Point((0, 10))]) - self.assertEqual(len(p.vertices), 4) + assert len(p.vertices) == 4 e_verts = [Point((0, 0)), Point((0, 10)), Point((10, 10)), Point((10, 0))] - self.assertTrue( - p.vertices - in [ - e_verts, - e_verts[-1:] + e_verts[:3], - e_verts[-2:] + e_verts[:2], - e_verts[-3:] + e_verts[:1], - ] - ) + assert p.vertices in [ + e_verts, + e_verts[-1:] + e_verts[:3], + e_verts[-2:] + e_verts[:2], + e_verts[-3:] + e_verts[:1], + ] def test_vertices2(self): """Test for multiple parts.""" @@ -590,20 +573,20 @@ def test_vertices2(self): [Point((30, 30)), Point((40, 30)), Point((40, 40)), Point((30, 40))], ] ) - self.assertEqual(len(p.vertices), 8) + assert len(p.vertices) == 8 def test_contains_point(self): p = Polygon( [Point((0, 0)), Point((10, 0)), Point((10, 10)), Point((0, 10))], [Point((1, 2)), Point((2, 2)), Point((2, 1)), Point((1, 1))], ) - self.assertEqual(p.contains_point((0, 0)), 0) - self.assertEqual(p.contains_point((1, 1)), 0) - self.assertEqual(p.contains_point((5, 5)), 1) - self.assertEqual(p.contains_point((10, 10)), 0) + assert p.contains_point((0, 0)) == 0 + assert p.contains_point((1, 1)) == 0 + assert p.contains_point((5, 5)) == 1 + assert p.contains_point((10, 10)) == 0 -class test_Rectangle(unittest.TestCase): +class Testtest_Rectangle: def test___init__1(self): """Test exceptions are thrown correctly.""" @@ -613,7 +596,7 @@ def test___init__1(self): except ArithmeticError: pass else: - self.fail() + pytest.fail() try: # upper < lower @@ -621,7 +604,7 @@ def test___init__1(self): except ArithmeticError: pass else: - self.fail() + pytest.fail() def test_set_centroid1(self): """Test with rectangles of zero width or height.""" @@ -629,26 +612,26 @@ def test_set_centroid1(self): # Zero width r = Rectangle(5, 5, 5, 10) r.set_centroid(Point((0, 0))) - self.assertEqual(r.left, 0) - self.assertEqual(r.lower, -2.5) - self.assertEqual(r.right, 0) - self.assertEqual(r.upper, 2.5) + assert r.left == 0 + assert r.lower == -2.5 + assert r.right == 0 + assert r.upper == 2.5 # Zero height r = Rectangle(10, 5, 20, 5) r.set_centroid(Point((40, 40))) - self.assertEqual(r.left, 35) - self.assertEqual(r.lower, 40) - self.assertEqual(r.right, 45) - self.assertEqual(r.upper, 40) + assert r.left == 35 + assert r.lower == 40 + assert r.right == 45 + assert r.upper == 40 # Zero width and height r = Rectangle(0, 0, 0, 0) r.set_centroid(Point((-4, -4))) - self.assertEqual(r.left, -4) - self.assertEqual(r.lower, -4) - self.assertEqual(r.right, -4) - self.assertEqual(r.upper, -4) + assert r.left == -4 + assert r.lower == -4 + assert r.right == -4 + assert r.upper == -4 def test_set_scale1(self): """Test repeated scaling.""" @@ -656,16 +639,16 @@ def test_set_scale1(self): r = Rectangle(2, 2, 4, 4) r.set_scale(0.5) - self.assertEqual(r.left, 2.5) - self.assertEqual(r.lower, 2.5) - self.assertEqual(r.right, 3.5) - self.assertEqual(r.upper, 3.5) + assert r.left == 2.5 + assert r.lower == 2.5 + assert r.right == 3.5 + assert r.upper == 3.5 r.set_scale(2) - self.assertEqual(r.left, 2) - self.assertEqual(r.lower, 2) - self.assertEqual(r.right, 4) - self.assertEqual(r.upper, 4) + assert r.left == 2 + assert r.lower == 2 + assert r.right == 4 + assert r.upper == 4 def test_set_scale2(self): """Test scaling of rectangles with zero width/height.""" @@ -673,76 +656,60 @@ def test_set_scale2(self): # Zero width r = Rectangle(5, 5, 5, 10) r.set_scale(2) - self.assertEqual(r.left, 5) - self.assertEqual(r.lower, 2.5) - self.assertEqual(r.right, 5) - self.assertEqual(r.upper, 12.5) + assert r.left == 5 + assert r.lower == 2.5 + assert r.right == 5 + assert r.upper == 12.5 # Zero height r = Rectangle(10, 5, 20, 5) r.set_scale(2) - self.assertEqual(r.left, 5) - self.assertEqual(r.lower, 5) - self.assertEqual(r.right, 25) - self.assertEqual(r.upper, 5) + assert r.left == 5 + assert r.lower == 5 + assert r.right == 25 + assert r.upper == 5 # Zero width and height r = Rectangle(0, 0, 0, 0) r.set_scale(100) - self.assertEqual(r.left, 0) - self.assertEqual(r.lower, 0) - self.assertEqual(r.right, 0) - self.assertEqual(r.upper, 0) + assert r.left == 0 + assert r.lower == 0 + assert r.right == 0 + assert r.upper == 0 # Zero width and height r = Rectangle(0, 0, 0, 0) r.set_scale(0.01) - self.assertEqual(r.left, 0) - self.assertEqual(r.lower, 0) - self.assertEqual(r.right, 0) - self.assertEqual(r.upper, 0) + assert r.left == 0 + assert r.lower == 0 + assert r.right == 0 + assert r.upper == 0 def test_area1(self): """Test rectangles with zero width/height.""" # Zero width r = Rectangle(5, 5, 5, 10) - self.assertEqual(r.area, 0) + assert r.area == 0 # Zero height r = Rectangle(10, 5, 20, 5) - self.assertEqual(r.area, 0) + assert r.area == 0 # Zero width and height r = Rectangle(0, 0, 0, 0) - self.assertEqual(r.area, 0) + assert r.area == 0 def test_height1(self): """Test rectangles with zero height.""" # Zero height r = Rectangle(10, 5, 20, 5) - self.assertEqual(r.height, 0) + assert r.height == 0 def test_width1(self): """Test rectangles with zero width.""" # Zero width r = Rectangle(5, 5, 5, 10) - self.assertEqual(r.width, 0) - - -# suite = unittest.TestSuite() -# suite.addTest(doctest.DocTestSuite('pysal.cg.shapes')) -# A = unittest.TestLoader().loadTestsFromTestCase(_TestPoint) -# B = unittest.TestLoader().loadTestsFromTestCase(_TestLineSegment) -# C = unittest.TestLoader().loadTestsFromTestCase(_TestLine) -# D = unittest.TestLoader().loadTestsFromTestCase(_TestRay) -# E = unittest.TestLoader().loadTestsFromTestCase(_TestChain) -# F = unittest.TestLoader().loadTestsFromTestCase(_TestPolygon) -# G = unittest.TestLoader().loadTestsFromTestCase(_TestRectangle) -# suite.addTests([A,B,C,D,E,D,G]) -if __name__ == "__main__": - unittest.main() - # runner = unittest.TextTestRunner() - # runner.run(suite) + assert r.width == 0 diff --git a/libpysal/cg/tests/test_sphere.py b/libpysal/cg/tests/test_sphere.py index be02ff41c..c3a930af7 100644 --- a/libpysal/cg/tests/test_sphere.py +++ b/libpysal/cg/tests/test_sphere.py @@ -1,13 +1,13 @@ +import pytest from .. import sphere from ...io.fileio import FileIO as psopen from ... import examples as pysal_examples import math -import unittest import numpy as np -class Sphere(unittest.TestCase): - def setUp(self): +class TestSphere: + def setup_method(self): self.pt0 = (0, 0) self.pt1 = (180, 0) f = psopen(pysal_examples.get_path("stl_hom.shp"), "r") @@ -19,34 +19,34 @@ def setUp(self): def test_arcdist(self): d = sphere.arcdist(self.pt0, self.pt1, sphere.RADIUS_EARTH_MILES) - self.assertEqual(d, math.pi * sphere.RADIUS_EARTH_MILES) + assert d == math.pi * sphere.RADIUS_EARTH_MILES def test_arcdist2linear(self): d = sphere.arcdist(self.pt0, self.pt1, sphere.RADIUS_EARTH_MILES) ld = sphere.arcdist2linear(d, sphere.RADIUS_EARTH_MILES) - self.assertEqual(ld, 2.0) + assert ld == 2.0 def test_radangle(self): p0 = (-87.893517, 41.981417) p1 = (-87.519295, 41.657498) - self.assertAlmostEqual(sphere.radangle(p0, p1), 0.007460167953189258) + assert sphere.radangle(p0, p1) == pytest.approx(0.007460167953189258) def test_linear2arcdist(self): d = sphere.arcdist(self.pt0, self.pt1, sphere.RADIUS_EARTH_MILES) ad = sphere.linear2arcdist(2.0, radius=sphere.RADIUS_EARTH_MILES) - self.assertEqual(d, ad) + assert d == ad def test_harcdist(self): d1 = sphere.harcdist(self.p0, self.p1, radius=sphere.RADIUS_EARTH_MILES) - self.assertAlmostEqual(d1, 29.532983644123796) + assert d1 == pytest.approx(29.532983644123796) d1 = sphere.harcdist(self.p3, self.p4, radius=sphere.RADIUS_EARTH_MILES) - self.assertAlmostEqual(d1, 25.871647470233675) + assert d1 == pytest.approx(25.871647470233675) def test_geointerpolate(self): pn1 = sphere.geointerpolate(self.p0, self.p1, 0.1) - self.assertAlmostEqual(pn1, (-87.85592403438788, 41.949079912574796)) + assert pn1 == pytest.approx((-87.85592403438788, 41.949079912574796)) pn2 = sphere.geointerpolate(self.p3, self.p4, 0.1, lonx=False) - self.assertAlmostEqual(pn2, (41.949079912574796, -87.85592403438788)) + assert pn2 == pytest.approx((41.949079912574796, -87.85592403438788)) def test_geogrid(self): grid = [ @@ -76,7 +76,7 @@ def test_geogrid(self): grid1 = sphere.geogrid(pup, pdown, 3, lonx=False) np.testing.assert_array_almost_equal(grid, grid1) - def test_toXYZ(self): + def test_to_xyz(self): w2 = { 0: [2, 5, 6, 10], 1: [4, 7, 9, 14], @@ -160,8 +160,4 @@ def test_toXYZ(self): pts = [shape.centroid for shape in self.shapes] pts = list(map(sphere.toXYZ, pts)) - self.assertAlmostEqual(sphere.brute_knn(pts, 4, "xyz"), w2) - - -if __name__ == "__main__": - unittest.main() + assert sphere.brute_knn(pts, 4, "xyz") == pytest.approx(w2) diff --git a/libpysal/cg/tests/test_standalone.py b/libpysal/cg/tests/test_standalone.py index 622620338..9025ad301 100644 --- a/libpysal/cg/tests/test_standalone.py +++ b/libpysal/cg/tests/test_standalone.py @@ -1,4 +1,4 @@ -import unittest +import pytest import numpy as np import math @@ -6,89 +6,81 @@ from ..standalone import * -class TestBbcommon(unittest.TestCase): +class TestBbcommon: def test_bbcommon(self): b0 = [0, 0, 10, 10] b1 = [5, 5, 15, 15] - self.assertEqual(1, bbcommon(b0, b1)) + assert 1 == bbcommon(b0, b1) def test_bbcommon_same(self): b0 = [0, 0, 10, 10] b1 = [0, 0, 10, 10] - self.assertEqual(1, bbcommon(b0, b1)) + assert 1 == bbcommon(b0, b1) def test_bbcommon_nested(self): b0 = [0, 0, 10, 10] b1 = [1, 1, 9, 9] - self.assertEqual(1, bbcommon(b0, b1)) + assert 1 == bbcommon(b0, b1) def test_bbcommon_top(self): b0 = [0, 0, 10, 10] b1 = [3, 5, 6, 15] - self.assertEqual(1, bbcommon(b0, b1)) + assert 1 == bbcommon(b0, b1) def test_bbcommon_shared_edge(self): b0 = [0, 0, 10, 10] b1 = [0, 10, 10, 20] - self.assertEqual(1, bbcommon(b0, b1)) + assert 1 == bbcommon(b0, b1) def test_bbcommon_shared_corner(self): b0 = [0, 0, 10, 10] b1 = [10, 10, 20, 20] - self.assertEqual(1, bbcommon(b0, b1)) + assert 1 == bbcommon(b0, b1) def test_bbcommon_floats(self): b0 = [0.0, 0.0, 0.1, 0.1] b1 = [0.05, 0.05, 0.15, 0.15] - self.assertEqual(1, bbcommon(b0, b1)) + assert 1 == bbcommon(b0, b1) -class TestGetBoundingBox(unittest.TestCase): +class TestGetBoundingBox: def test_get_bounding_box(self): items = [Point((-1, 5)), Rectangle(0, 6, 11, 12)] expected = [-1, 5, 11, 12] - self.assertEqual(expected, get_bounding_box(items)[:]) + assert expected == get_bounding_box(items)[:] -class TestGetAngleBetween(unittest.TestCase): +class TestGetAngleBetween: def test_get_angle_between(self): ray1 = Ray(Point((0, 0)), Point((1, 0))) ray2 = Ray(Point((0, 0)), Point((1, 0))) - self.assertEqual(0.0, get_angle_between(ray1, ray2)) + assert 0.0 == get_angle_between(ray1, ray2) def test_get_angle_between_expect45(self): ray1 = Ray(Point((0, 0)), Point((1, 0))) ray2 = Ray(Point((0, 0)), Point((1, 1))) - self.assertEqual(45.0, math.degrees(get_angle_between(ray1, ray2))) + assert 45.0 == math.degrees(get_angle_between(ray1, ray2)) def test_get_angle_between_expect90(self): ray1 = Ray(Point((0, 0)), Point((1, 0))) ray2 = Ray(Point((0, 0)), Point((0, 1))) - self.assertEqual(90.0, math.degrees(get_angle_between(ray1, ray2))) + assert 90.0 == math.degrees(get_angle_between(ray1, ray2)) -class TestIsCollinear(unittest.TestCase): +class TestIsCollinear: def test_is_collinear(self): - self.assertEqual( - True, is_collinear(Point((0, 0)), Point((1, 1)), Point((5, 5))) - ) + assert True == is_collinear(Point((0, 0)), Point((1, 1)), Point((5, 5))) - def test_is_collinear_expectFalse(self): - self.assertEqual( - False, is_collinear(Point((0, 0)), Point((1, 1)), Point((5, 0))) - ) + def test_is_collinear_expect_false(self): + assert False == is_collinear(Point((0, 0)), Point((1, 1)), Point((5, 0))) - def test_is_collinear_AlongX(self): - self.assertEqual( - True, is_collinear(Point((0, 0)), Point((1, 0)), Point((5, 0))) - ) + def test_is_collinear_along_x(self): + assert True == is_collinear(Point((0, 0)), Point((1, 0)), Point((5, 0))) - def test_is_collinear_AlongY(self): - self.assertEqual( - True, is_collinear(Point((0, 0)), Point((0, 1)), Point((0, -1))) - ) + def test_is_collinear_along_y(self): + assert True == is_collinear(Point((0, 0)), Point((0, 1)), Point((0, -1))) - def test_is_collinear_smallFloat(self): + def test_is_collinear_small_float(self): """ Given: p1 = (0.1, 0.2), p2 = (0.2, 0.3), p3 = (0.3, 0.4) @@ -109,374 +101,367 @@ def test_is_collinear_smallFloat(self): y = 1*x + 0.1 Line(p1, p2) == Line(p2 ,p3) - + Therefore ``p1, p2, p3`` are collinear. Due to floating point rounding areas the standard test, - + ((p2[0]-p1[0])*(p3[1]-p1[1]) - (p2[1]-p1[1])*(p3[0]-p1[0])) == 0 - + will fail. To get around this we use an epsilon. The ``numpy.finfo`` function return an smallest epsilon for the given data types such that, - + (numpy.finfo(float).eps + 1.0) != 1.0 Therefore if - + abs( (p2[0]-p1[0]) * (p3[1]-p1[1]) - (p2[1]-p1[1]) * (p3[0]-p1[0]) ) < numpy.finfo(p1[0]).eps - + The points are collinear. - + """ - self.assertEqual( - True, is_collinear(Point((0.1, 0.2)), Point((0.2, 0.3)), Point((0.3, 0.4))) + assert True == is_collinear( + Point((0.1, 0.2)), Point((0.2, 0.3)), Point((0.3, 0.4)) ) def test_is_collinear_random(self): for i in range(10): a, b, c = np.random.random(3) * 10 ** (i) - self.assertEqual( - True, is_collinear(Point((a, a)), Point((b, b)), Point((c, c))) - ) + assert True == is_collinear(Point((a, a)), Point((b, b)), Point((c, c))) def test_is_collinear_random2(self): for i in range(1000): a, b, c = np.random.random(3) - self.assertEqual( - True, is_collinear(Point((a, a)), Point((b, b)), Point((c, c))) - ) + assert True == is_collinear(Point((a, a)), Point((b, b)), Point((c, c))) -class TestGetSegmentsIntersect(unittest.TestCase): +class TestGetSegmentsIntersect: def test_get_segments_intersect(self): seg1 = LineSegment(Point((0, 0)), Point((0, 10))) seg2 = LineSegment(Point((-5, 5)), Point((5, 5))) - self.assertEqual((0.0, 5.0), get_segments_intersect(seg1, seg2)[:]) + assert (0.0, 5.0) == get_segments_intersect(seg1, seg2)[:] def test_get_segments_intersect_shared_vert(self): seg1 = LineSegment(Point((0, 0)), Point((0, 10))) seg2 = LineSegment(Point((-5, 5)), Point((0, 10))) - self.assertEqual((0.0, 10.0), get_segments_intersect(seg1, seg2)[:]) + assert (0.0, 10.0) == get_segments_intersect(seg1, seg2)[:] def test_get_segments_intersect_floats(self): seg1 = LineSegment(Point((0, 0)), Point((0, 0.10))) seg2 = LineSegment(Point((-0.5, 0.05)), Point((0.5, 0.05))) - self.assertEqual((0.0, 0.05), get_segments_intersect(seg1, seg2)[:]) + assert (0.0, 0.05) == get_segments_intersect(seg1, seg2)[:] def test_get_segments_intersect_angles(self): seg1 = LineSegment(Point((0, 0)), Point((1, 1))) seg2 = LineSegment(Point((1, 0)), Point((0, 1))) - self.assertEqual((0.5, 0.5), get_segments_intersect(seg1, seg2)[:]) + assert (0.5, 0.5) == get_segments_intersect(seg1, seg2)[:] def test_get_segments_intersect_no_intersect(self): seg1 = LineSegment(Point((-5, 5)), Point((5, 5))) seg2 = LineSegment(Point((100, 100)), Point((100, 101))) - self.assertEqual(None, get_segments_intersect(seg1, seg2)) + assert None is get_segments_intersect(seg1, seg2) def test_get_segments_intersect_overlap(self): seg1 = LineSegment(Point((0.1, 0.1)), Point((0.6, 0.6))) seg2 = LineSegment(Point((0.3, 0.3)), Point((0.9, 0.9))) expected = LineSegment(Point((0.3, 0.3)), Point((0.6, 0.6))) - self.assertEqual(expected, get_segments_intersect(seg1, seg2)) + assert expected == get_segments_intersect(seg1, seg2) def test_get_segments_intersect_same(self): seg1 = LineSegment(Point((-5, 5)), Point((5, 5))) - self.assertEqual(seg1, get_segments_intersect(seg1, seg1)) + assert seg1 == get_segments_intersect(seg1, seg1) def test_get_segments_intersect_nested(self): seg1 = LineSegment(Point((0.1, 0.1)), Point((0.9, 0.9))) seg2 = LineSegment(Point((0.3, 0.3)), Point((0.6, 0.6))) - self.assertEqual(seg2, get_segments_intersect(seg1, seg2)) + assert seg2 == get_segments_intersect(seg1, seg2) -class TestGetSegmentPointIntersect(unittest.TestCase): +class TestGetSegmentPointIntersect: def test_get_segment_point_intersect(self): seg = LineSegment(Point((0, 0)), Point((0, 10))) pt = Point((0, 5)) - self.assertEqual(pt, get_segment_point_intersect(seg, pt)) + assert pt == get_segment_point_intersect(seg, pt) def test_get_segment_point_intersect_left_end(self): seg = LineSegment(Point((0, 0)), Point((0, 10))) pt = seg.p1 - self.assertEqual(pt, get_segment_point_intersect(seg, pt)) + assert pt == get_segment_point_intersect(seg, pt) def test_get_segment_point_intersect_right_end(self): seg = LineSegment(Point((0, 0)), Point((0, 10))) pt = seg.p2 - self.assertEqual(pt, get_segment_point_intersect(seg, pt)) + assert pt == get_segment_point_intersect(seg, pt) def test_get_segment_point_intersect_angle(self): seg = LineSegment(Point((0, 0)), Point((1, 1))) pt = Point((0.1, 0.1)) - self.assertEqual(pt, get_segment_point_intersect(seg, pt)) + assert pt == get_segment_point_intersect(seg, pt) def test_get_segment_point_intersect_no_intersect(self): seg = LineSegment(Point((0, 0)), Point((0, 10))) pt = Point((5, 5)) - self.assertEqual(None, get_segment_point_intersect(seg, pt)) + assert None is get_segment_point_intersect(seg, pt) def test_get_segment_point_intersect_no_intersect_collinear(self): seg = LineSegment(Point((0, 0)), Point((0, 10))) pt = Point((0, 20)) - self.assertEqual(None, get_segment_point_intersect(seg, pt)) + assert None is get_segment_point_intersect(seg, pt) def test_get_segment_point_intersect_floats(self): seg = LineSegment(Point((0.3, 0.3)), Point((0.9, 0.9))) pt = Point((0.5, 0.5)) - self.assertEqual(pt, get_segment_point_intersect(seg, pt)) + assert pt == get_segment_point_intersect(seg, pt) def test_get_segment_point_intersect_floats(self): seg = LineSegment( Point((0.0, 0.0)), Point((2.7071067811865475, 2.7071067811865475)) ) pt = Point((1.0, 1.0)) - self.assertEqual(pt, get_segment_point_intersect(seg, pt)) + assert pt == get_segment_point_intersect(seg, pt) def test_get_segment_point_intersect_floats_no_intersect(self): seg = LineSegment(Point((0.3, 0.3)), Point((0.9, 0.9))) pt = Point((0.1, 0.1)) - self.assertEqual(None, get_segment_point_intersect(seg, pt)) + assert None is get_segment_point_intersect(seg, pt) -class TestGetPolygonPointIntersect(unittest.TestCase): +class TestGetPolygonPointIntersect: def test_get_polygon_point_intersect(self): poly = Polygon([Point((0, 0)), Point((1, 0)), Point((1, 1)), Point((0, 1))]) pt = Point((0.5, 0.5)) - self.assertEqual(pt, get_polygon_point_intersect(poly, pt)) + assert pt == get_polygon_point_intersect(poly, pt) def test_get_polygon_point_intersect_on_edge(self): poly = Polygon([Point((0, 0)), Point((1, 0)), Point((1, 1)), Point((0, 1))]) pt = Point((1.0, 0.5)) - self.assertEqual(pt, get_polygon_point_intersect(poly, pt)) + assert pt == get_polygon_point_intersect(poly, pt) def test_get_polygon_point_intersect_on_vertex(self): poly = Polygon([Point((0, 0)), Point((1, 0)), Point((1, 1)), Point((0, 1))]) pt = Point((1.0, 1.0)) - self.assertEqual(pt, get_polygon_point_intersect(poly, pt)) + assert pt == get_polygon_point_intersect(poly, pt) def test_get_polygon_point_intersect_outside(self): poly = Polygon([Point((0, 0)), Point((1, 0)), Point((1, 1)), Point((0, 1))]) pt = Point((2.0, 2.0)) - self.assertEqual(None, get_polygon_point_intersect(poly, pt)) + assert None is get_polygon_point_intersect(poly, pt) -class TestGetRectanglePointIntersect(unittest.TestCase): +class TestGetRectanglePointIntersect: def test_get_rectangle_point_intersect(self): rect = Rectangle(0, 0, 5, 5) pt = Point((1, 1)) - self.assertEqual(pt, get_rectangle_point_intersect(rect, pt)) + assert pt == get_rectangle_point_intersect(rect, pt) def test_get_rectangle_point_intersect_on_edge(self): rect = Rectangle(0, 0, 5, 5) pt = Point((2.5, 5)) - self.assertEqual(pt, get_rectangle_point_intersect(rect, pt)) + assert pt == get_rectangle_point_intersect(rect, pt) def test_get_rectangle_point_intersect_on_vertex(self): rect = Rectangle(0, 0, 5, 5) pt = Point((5, 5)) - self.assertEqual(pt, get_rectangle_point_intersect(rect, pt)) + assert pt == get_rectangle_point_intersect(rect, pt) def test_get_rectangle_point_intersect_outside(self): rect = Rectangle(0, 0, 5, 5) pt = Point((10, 10)) - self.assertEqual(None, get_rectangle_point_intersect(rect, pt)) + assert None is get_rectangle_point_intersect(rect, pt) -class TestGetRaySegmentIntersect(unittest.TestCase): +class TestGetRaySegmentIntersect: def test_get_ray_segment_intersect(self): ray = Ray(Point((0, 0)), Point((0, 1))) seg = LineSegment(Point((-1, 10)), Point((1, 10))) - self.assertEqual((0.0, 10.0), get_ray_segment_intersect(ray, seg)[:]) + assert (0.0, 10.0) == get_ray_segment_intersect(ray, seg)[:] def test_get_ray_segment_intersect_orgin(self): ray = Ray(Point((0, 0)), Point((0, 1))) seg = LineSegment(Point((-1, 0)), Point((1, 0))) - self.assertEqual((0.0, 0.0), get_ray_segment_intersect(ray, seg)[:]) + assert (0.0, 0.0) == get_ray_segment_intersect(ray, seg)[:] def test_get_ray_segment_intersect_edge(self): ray = Ray(Point((0, 0)), Point((0, 1))) seg = LineSegment(Point((0, 2)), Point((2, 2))) - self.assertEqual((0.0, 2.0), get_ray_segment_intersect(ray, seg)[:]) + assert (0.0, 2.0) == get_ray_segment_intersect(ray, seg)[:] def test_get_ray_segment_intersect_no_intersect(self): ray = Ray(Point((0, 0)), Point((0, 1))) seg = LineSegment(Point((10, 10)), Point((10, 11))) - self.assertEqual(None, get_ray_segment_intersect(ray, seg)) + assert None is get_ray_segment_intersect(ray, seg) def test_get_ray_segment_intersect_segment(self): ray = Ray(Point((0, 0)), Point((5, 5))) seg = LineSegment(Point((1, 1)), Point((2, 2))) - self.assertEqual(seg, get_ray_segment_intersect(ray, seg)) + assert seg == get_ray_segment_intersect(ray, seg) -class TestGetRectangleRectangleIntersection(unittest.TestCase): +class TestGetRectangleRectangleIntersection: def test_get_rectangle_rectangle_intersection_leftright(self): r0 = Rectangle(0, 4, 6, 9) r1 = Rectangle(4, 0, 9, 7) expected = [4.0, 4.0, 6.0, 7.0] - self.assertEqual(expected, get_rectangle_rectangle_intersection(r0, r1)[:]) + assert expected == get_rectangle_rectangle_intersection(r0, r1)[:] def test_get_rectangle_rectangle_intersection_topbottom(self): r0 = Rectangle(0, 0, 4, 4) r1 = Rectangle(2, 1, 6, 3) expected = [2.0, 1.0, 4.0, 3.0] - self.assertEqual(expected, get_rectangle_rectangle_intersection(r0, r1)[:]) + assert expected == get_rectangle_rectangle_intersection(r0, r1)[:] def test_get_rectangle_rectangle_intersection_nested(self): r0 = Rectangle(0, 0, 4, 4) r1 = Rectangle(2, 1, 3, 2) - self.assertEqual(r1, get_rectangle_rectangle_intersection(r0, r1)) + assert r1 == get_rectangle_rectangle_intersection(r0, r1) def test_get_rectangle_rectangle_intersection_shared_corner(self): r0 = Rectangle(0, 0, 4, 4) r1 = Rectangle(4, 4, 8, 8) - self.assertEqual(Point((4, 4)), get_rectangle_rectangle_intersection(r0, r1)) + assert Point((4, 4)) == get_rectangle_rectangle_intersection(r0, r1) def test_get_rectangle_rectangle_intersection_shared_edge(self): r0 = Rectangle(0, 0, 4, 4) r1 = Rectangle(0, 4, 4, 8) - self.assertEqual( - LineSegment(Point((0, 4)), Point((4, 4))), - get_rectangle_rectangle_intersection(r0, r1), - ) + assert LineSegment( + Point((0, 4)), Point((4, 4)) + ) == get_rectangle_rectangle_intersection(r0, r1) def test_get_rectangle_rectangle_intersection_shifted_edge(self): r0 = Rectangle(0, 0, 4, 4) r1 = Rectangle(2, 4, 6, 8) - self.assertEqual( - LineSegment(Point((2, 4)), Point((4, 4))), - get_rectangle_rectangle_intersection(r0, r1), - ) + assert LineSegment( + Point((2, 4)), Point((4, 4)) + ) == get_rectangle_rectangle_intersection(r0, r1) def test_get_rectangle_rectangle_intersection_no_intersect(self): r0 = Rectangle(0, 0, 4, 4) r1 = Rectangle(5, 5, 8, 8) - self.assertEqual(None, get_rectangle_rectangle_intersection(r0, r1)) + assert None is get_rectangle_rectangle_intersection(r0, r1) -class TestGetPolygonPointDist(unittest.TestCase): +class TestGetPolygonPointDist: def test_get_polygon_point_dist(self): poly = Polygon([Point((0, 0)), Point((1, 0)), Point((1, 1)), Point((0, 1))]) pt = Point((2, 0.5)) expected = 1.0 - self.assertEqual(expected, get_polygon_point_dist(poly, pt)) + assert expected == get_polygon_point_dist(poly, pt) def test_get_polygon_point_dist_inside(self): poly = Polygon([Point((0, 0)), Point((1, 0)), Point((1, 1)), Point((0, 1))]) pt = Point((0.5, 0.5)) expected = 0.0 - self.assertEqual(expected, get_polygon_point_dist(poly, pt)) + assert expected == get_polygon_point_dist(poly, pt) def test_get_polygon_point_dist_on_vertex(self): poly = Polygon([Point((0, 0)), Point((1, 0)), Point((1, 1)), Point((0, 1))]) pt = Point((1.0, 1.0)) expected = 0.0 - self.assertEqual(expected, get_polygon_point_dist(poly, pt)) + assert expected == get_polygon_point_dist(poly, pt) def test_get_polygon_point_dist_on_edge(self): poly = Polygon([Point((0, 0)), Point((1, 0)), Point((1, 1)), Point((0, 1))]) pt = Point((0.5, 1.0)) expected = 0.0 - self.assertEqual(expected, get_polygon_point_dist(poly, pt)) + assert expected == get_polygon_point_dist(poly, pt) -class TestGetPointsDist(unittest.TestCase): +class TestGetPointsDist: def test_get_points_dist(self): pt1 = Point((0.5, 0.5)) pt2 = Point((0.5, 0.5)) - self.assertEqual(0, get_points_dist(pt1, pt2)) + assert 0 == get_points_dist(pt1, pt2) def test_get_points_dist_diag(self): pt1 = Point((0, 0)) pt2 = Point((1, 1)) - self.assertEqual(2 ** (0.5), get_points_dist(pt1, pt2)) + assert 2 ** (0.5) == get_points_dist(pt1, pt2) - def test_get_points_dist_alongX(self): + def test_get_points_dist_along_x(self): pt1 = Point((-1000, 1 / 3.0)) pt2 = Point((1000, 1 / 3.0)) - self.assertEqual(2000, get_points_dist(pt1, pt2)) + assert 2000 == get_points_dist(pt1, pt2) - def test_get_points_dist_alongY(self): + def test_get_points_dist_along_y(self): pt1 = Point((1 / 3.0, -500)) pt2 = Point((1 / 3.0, 500)) - self.assertEqual(1000, get_points_dist(pt1, pt2)) + assert 1000 == get_points_dist(pt1, pt2) -class TestGetSegmentPointDist(unittest.TestCase): +class TestGetSegmentPointDist: def test_get_segment_point_dist(self): seg = LineSegment(Point((0, 0)), Point((10, 0))) pt = Point((5, 5)) - self.assertEqual((5.0, 0.5), get_segment_point_dist(seg, pt)) + assert (5.0, 0.5) == get_segment_point_dist(seg, pt) - def test_get_segment_point_dist_on_endPoint(self): + def test_get_segment_point_dist_on_end_point(self): seg = LineSegment(Point((0, 0)), Point((10, 0))) pt = Point((0, 0)) - self.assertEqual((0.0, 0.0), get_segment_point_dist(seg, pt)) + assert (0.0, 0.0) == get_segment_point_dist(seg, pt) def test_get_segment_point_dist_on_middle(self): seg = LineSegment(Point((0, 0)), Point((10, 0))) pt = Point((5, 0)) - self.assertEqual((0.0, 0.5), get_segment_point_dist(seg, pt)) + assert (0.0, 0.5) == get_segment_point_dist(seg, pt) def test_get_segment_point_diag(self): seg = LineSegment(Point((0, 0)), Point((10, 10))) pt = Point((5, 5)) - self.assertAlmostEqual(0.0, get_segment_point_dist(seg, pt)[0]) - self.assertAlmostEqual(0.5, get_segment_point_dist(seg, pt)[1]) + assert 0.0 == pytest.approx(get_segment_point_dist(seg, pt)[0]) + assert 0.5 == pytest.approx(get_segment_point_dist(seg, pt)[1]) def test_get_segment_point_diag_with_dist(self): seg = LineSegment(Point((0, 0)), Point((10, 10))) pt = Point((0, 10)) - self.assertAlmostEqual(50 ** (0.5), get_segment_point_dist(seg, pt)[0]) - self.assertAlmostEqual(0.5, get_segment_point_dist(seg, pt)[1]) + assert 50 ** (0.5) == pytest.approx(get_segment_point_dist(seg, pt)[0]) + assert 0.5 == pytest.approx(get_segment_point_dist(seg, pt)[1]) -class TestGetPointAtAngleAndDist(unittest.TestCase): +class TestGetPointAtAngleAndDist: def test_get_point_at_angle_and_dist(self): ray = Ray(Point((0, 0)), Point((1, 0))) pt = get_point_at_angle_and_dist(ray, math.pi, 1.0) - self.assertAlmostEqual(-1.0, pt[0]) - self.assertAlmostEqual(0.0, pt[1]) + assert -1.0 == pytest.approx(pt[0]) + assert 0.0 == pytest.approx(pt[1]) def test_get_point_at_angle_and_dist_diag(self): ray = Ray(Point((0, 0)), Point((1, 1))) pt = get_point_at_angle_and_dist(ray, math.pi, 2 ** (0.5)) - self.assertAlmostEqual(-1.0, pt[0]) - self.assertAlmostEqual(-1.0, pt[1]) + assert -1.0 == pytest.approx(pt[0]) + assert -1.0 == pytest.approx(pt[1]) def test_get_point_at_angle_and_dist_diag_90(self): ray = Ray(Point((0, 0)), Point((1, 1))) pt = get_point_at_angle_and_dist(ray, -math.pi / 2.0, 2 ** (0.5)) - self.assertAlmostEqual(1.0, pt[0]) - self.assertAlmostEqual(-1.0, pt[1]) + assert 1.0 == pytest.approx(pt[0]) + assert -1.0 == pytest.approx(pt[1]) def test_get_point_at_angle_and_dist_diag_45(self): ray = Ray(Point((0, 0)), Point((1, 1))) pt = get_point_at_angle_and_dist(ray, -math.pi / 4.0, 1) - self.assertAlmostEqual(1.0, pt[0]) - self.assertAlmostEqual(0.0, pt[1]) + assert 1.0 == pytest.approx(pt[0]) + assert 0.0 == pytest.approx(pt[1]) -class TestConvexHull(unittest.TestCase): +class TestConvexHull: def test_convex_hull(self): points = [Point((0, 0)), Point((4, 4)), Point((4, 0)), Point((3, 1))] - self.assertEqual( - [Point((0.0, 0.0)), Point((4.0, 0.0)), Point((4.0, 4.0))], - convex_hull(points), + assert [Point((0.0, 0.0)), Point((4.0, 0.0)), Point((4.0, 4.0))] == convex_hull( + points ) -class TestIsClockwise(unittest.TestCase): +class TestIsClockwise: def test_is_clockwise(self): vertices = [Point((0, 0)), Point((0, 10)), Point((10, 0))] - self.assertEqual(True, is_clockwise(vertices)) + assert True is is_clockwise(vertices) def test_is_clockwise_expect_false(self): vertices = [Point((0, 0)), Point((10, 0)), Point((0, 10))] - self.assertEqual(False, is_clockwise(vertices)) + assert False is is_clockwise(vertices) def test_is_clockwise_big(self): vertices = [ @@ -539,65 +524,65 @@ def test_is_clockwise_big(self): (-106.57679999999999, 35.174143999999998), (-106.57798, 35.174143999999998), ] - self.assertEqual(True, is_clockwise(vertices)) + assert True is is_clockwise(vertices) -class TestPointTouchesRectangle(unittest.TestCase): +class TestPointTouchesRectangle: def test_point_touches_rectangle_inside(self): rect = Rectangle(0, 0, 10, 10) point = Point((5, 5)) - self.assertEqual(True, point_touches_rectangle(point, rect)) + assert point_touches_rectangle(point, rect) def test_point_touches_rectangle_on_edge(self): rect = Rectangle(0, 0, 10, 10) point = Point((10, 5)) - self.assertEqual(True, point_touches_rectangle(point, rect)) + assert point_touches_rectangle(point, rect) def test_point_touches_rectangle_on_corner(self): rect = Rectangle(0, 0, 10, 10) point = Point((10, 10)) - self.assertEqual(True, point_touches_rectangle(point, rect)) + assert point_touches_rectangle(point, rect) def test_point_touches_rectangle_outside(self): rect = Rectangle(0, 0, 10, 10) point = Point((11, 11)) - self.assertEqual(False, point_touches_rectangle(point, rect)) + assert not point_touches_rectangle(point, rect) -class TestGetSharedSegments(unittest.TestCase): +class TestGetSharedSegments: def test_get_shared_segments(self): poly1 = Polygon([Point((0, 0)), Point((0, 1)), Point((1, 1)), Point((1, 0))]) poly2 = Polygon([Point((1, 0)), Point((1, 1)), Point((2, 1)), Point((2, 0))]) poly3 = Polygon([Point((0, 1)), Point((0, 2)), Point((1, 2)), Point((1, 1))]) poly4 = Polygon([Point((1, 1)), Point((1, 2)), Point((2, 2)), Point((2, 1))]) - self.assertEqual(True, get_shared_segments(poly1, poly2, bool_ret=True)) - self.assertEqual(True, get_shared_segments(poly1, poly3, bool_ret=True)) - self.assertEqual(True, get_shared_segments(poly3, poly4, bool_ret=True)) - self.assertEqual(True, get_shared_segments(poly4, poly2, bool_ret=True)) + assert True is get_shared_segments(poly1, poly2, bool_ret=True) + assert True is get_shared_segments(poly1, poly3, bool_ret=True) + assert True is get_shared_segments(poly3, poly4, bool_ret=True) + assert True is get_shared_segments(poly4, poly2, bool_ret=True) - self.assertEqual(False, get_shared_segments(poly1, poly4, bool_ret=True)) - self.assertEqual(False, get_shared_segments(poly3, poly2, bool_ret=True)) + assert False is get_shared_segments(poly1, poly4, bool_ret=True) + assert False is get_shared_segments(poly3, poly2, bool_ret=True) def test_get_shared_segments_non_bool(self): poly1 = Polygon([Point((0, 0)), Point((0, 1)), Point((1, 1)), Point((1, 0))]) poly2 = Polygon([Point((1, 0)), Point((1, 1)), Point((2, 1)), Point((2, 0))]) poly3 = Polygon([Point((0, 1)), Point((0, 2)), Point((1, 2)), Point((1, 1))]) poly4 = Polygon([Point((1, 1)), Point((1, 2)), Point((2, 2)), Point((2, 1))]) - self.assertEqual( - LineSegment(Point((1, 0)), Point((1, 1))), - get_shared_segments(poly1, poly2)[0], + assert ( + LineSegment(Point((1, 0)), Point((1, 1))) + == get_shared_segments(poly1, poly2)[0] ) - self.assertEqual( - LineSegment(Point((0, 1)), Point((1, 1))), - get_shared_segments(poly1, poly3)[0], + assert ( + LineSegment(Point((0, 1)), Point((1, 1))) + == get_shared_segments(poly1, poly3)[0] ) - self.assertEqual( - LineSegment(Point((1, 2)), Point((1, 1))), - get_shared_segments(poly3, poly4)[0], + assert ( + LineSegment(Point((1, 2)), Point((1, 1))) + == get_shared_segments(poly3, poly4)[0] ) - self.assertEqual( - LineSegment(Point((2, 1)), Point((1, 1))), - get_shared_segments(poly4, poly2)[0], + assert ( + LineSegment(Point((2, 1)), Point((1, 1))) + == get_shared_segments(poly4, poly2)[0] ) # expected = [LineSegment(Point((1, 1)), Point((1, 0)))] # assert expected == get_shared_segments(poly1, poly3) @@ -607,7 +592,7 @@ def test_get_shared_segments_non_bool(self): # assert expected == get_shared_segments(poly4, poly2) -class TestDistanceMatrix(unittest.TestCase): +class TestDistanceMatrix: def test_distance_matrix(self): points = [(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)] dist = distance_matrix(np.array(points), 2) @@ -616,8 +601,4 @@ def test_distance_matrix(self): x, y = points[i] X, Y = points[j] d = ((x - X) ** 2 + (y - Y) ** 2) ** (0.5) - self.assertEqual(dist[i, j], d) - - -if __name__ == "__main__": - unittest.main() + assert dist[i, j] == d diff --git a/libpysal/cg/tests/test_voronoi.py b/libpysal/cg/tests/test_voronoi.py index bf850d729..2f1a38239 100644 --- a/libpysal/cg/tests/test_voronoi.py +++ b/libpysal/cg/tests/test_voronoi.py @@ -1,21 +1,11 @@ -import unittest - import numpy as np -from ..voronoi import voronoi, voronoi_frames from ..shapes import Polygon, asShape - -import pytest - -try: - import shapely - HAS_SHAPELY = True -except ImportError: - HAS_SHAPELY = False +from ..voronoi import voronoi, voronoi_frames -class Voronoi(unittest.TestCase): - def setUp(self): +class TestVoronoi: + def setup_method(self): self.points = [(10.2, 5.1), (4.7, 2.2), (5.3, 5.7), (2.7, 5.3)] self.vertices = [ @@ -33,21 +23,11 @@ def setUp(self): def test_voronoi(self): regions, vertices = voronoi(self.points) - self.assertEqual(regions, [[1, 3, 2], [4, 5, 1, 0], [0, 1, 7, 6], [9, 0, 8]]) + assert regions == [[1, 3, 2], [4, 5, 1, 0], [0, 1, 7, 6], [9, 0, 8]] np.testing.assert_array_almost_equal(vertices, self.vertices) - @pytest.mark.skipif(not HAS_SHAPELY, reason="shapely needed") def test_voronoi_frames(self): r_df, p_df = voronoi_frames(self.points) region = r_df.iloc[0]["geometry"] - try: - import geopandas as df - - self.assertTrue(isinstance(asShape(region), Polygon)) - except ImportError: - self.assertTrue(isinstance(region, Polygon)) - - -if __name__ == "__main__": - unittest.main() + assert isinstance(asShape(region), Polygon) diff --git a/libpysal/examples/tests/test_available.py b/libpysal/examples/tests/test_available.py index 920184888..78eb12179 100644 --- a/libpysal/examples/tests/test_available.py +++ b/libpysal/examples/tests/test_available.py @@ -3,7 +3,6 @@ import os import platform import tempfile -import unittest import pandas from unittest.mock import MagicMock, patch @@ -19,34 +18,33 @@ original_makedirs = os.makedirs - -class Testexamples(unittest.TestCase): +class Testexamples: def test_available(self): examples = available() - self.assertEqual(type(examples), pandas.core.frame.DataFrame) - self.assertEqual(examples.shape, (98, 3)) + assert type(examples) == pandas.core.frame.DataFrame + assert examples.shape == (98, 3) def test_data_home(self): pth = get_data_home() head, tail = os.path.split(pth) - self.assertEqual(tail, "pysal") + assert tail == "pysal" if os_name == "Linux": if "XDG_DATA_HOME" in os.environ: - self.assertEqual(head, os.environ["XDG_DATA_HOME"]) + assert head == os.environ["XDG_DATA_HOME"] else: heads = head.split("/") - self.assertEqual(heads[-1], "share") - self.assertEqual(heads[-2], ".local") + assert heads[-1] == "share" + assert heads[-2] == ".local" elif os_name == "Darwin": heads = head.split("/") - self.assertEqual(heads[1], "Users") - self.assertEqual(heads[-1], "Application Support") - self.assertEqual(heads[-2], "Library") + assert heads[1] == "Users" + assert heads[-1] == "Application Support" + assert heads[-2] == "Library" elif os_name == "Windows": heads = head.split("\\") - self.assertEqual(heads[1], "Users") - self.assertEqual(heads[-2], "Local") - self.assertEqual(heads[-3], "AppData") + assert heads[1] == "Users" + assert heads[-2] == "Local" + assert heads[-3] == "AppData" @patch("os.makedirs") @patch("os.path.exists") @@ -68,23 +66,15 @@ def path_exists_side_effect(path): pth = get_data_home() head, tail = os.path.split(pth) - self.assertEqual(tail, "pysal") - self.assertEqual(head, tempfile.gettempdir()) - + assert tail == "pysal" + assert head == tempfile.gettempdir() def test_get_url(self): - self.assertEqual(get_url("10740"), None) + assert get_url("10740") == None url = "https://geodacenter.github.io/data-and-lab//data/baltimore.zip" - self.assertEqual(get_url("Baltimore"), url) + assert get_url("Baltimore") == url def test_load_example(self): taz = load_example("taz") flist = taz.get_file_list() - self.assertEqual(len(flist), 4) - - -suite = unittest.TestLoader().loadTestsFromTestCase(Testexamples) - -if __name__ == "__main__": - runner = unittest.TextTestRunner() - runner.run(suite) + assert len(flist) == 4 diff --git a/libpysal/io/geotable/tests/test_utils.py b/libpysal/io/geotable/tests/test_utils.py index a29330304..259c05ef1 100644 --- a/libpysal/io/geotable/tests/test_utils.py +++ b/libpysal/io/geotable/tests/test_utils.py @@ -1,10 +1,10 @@ from .. import utils from ..file import read_files as rf -import unittest as ut +import pytest -@ut.skip("skpping converters and metadata inserters") -class Test_Utils(ut.TestCase): +@pytest.mark.skip("skpping converters and metadata inserters") +class Test_Utils: def test_converters(self): """Make a round trip to geodataframe and back.""" diff --git a/libpysal/io/iohandlers/tests/test_arcgis_dbf.py b/libpysal/io/iohandlers/tests/test_arcgis_dbf.py index aa9cdf4fa..b91183360 100644 --- a/libpysal/io/iohandlers/tests/test_arcgis_dbf.py +++ b/libpysal/io/iohandlers/tests/test_arcgis_dbf.py @@ -1,21 +1,23 @@ -import unittest -from ...fileio import FileIO as psopen -from .... import examples as pysal_examples -from ..arcgis_dbf import ArcGISDbfIO -import tempfile import os +import tempfile import warnings +import pytest + +from .... import examples as pysal_examples +from ...fileio import FileIO as psopen +from ..arcgis_dbf import ArcGISDbfIO -class test_ArcGISDbfIO(unittest.TestCase): - def setUp(self): + +class Testtest_ArcGISDbfIO: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("arcgis_ohio.dbf") self.obj = ArcGISDbfIO(test_file, "r") def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): with warnings.catch_warnings(record=True) as warn: @@ -27,13 +29,13 @@ def test_read(self): "Missing Value Found, setting value to libpysal.MISSINGVALUE." in str(warn[0].message) ) - self.assertEqual(88, w.n) - self.assertEqual(5.25, w.mean_neighbors) - self.assertEqual([1.0, 1.0, 1.0, 1.0], list(w[1].values())) + assert w.n == 88 + assert w.mean_neighbors == 5.25 + assert [1.0, 1.0, 1.0, 1.0] == list(w[1].values()) def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj.read) + pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() @@ -56,9 +58,5 @@ def test_write(self): f = psopen(fname, "r", "arcgis_dbf") wnew = f.read() f.close() - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_arcgis_swm.py b/libpysal/io/iohandlers/tests/test_arcgis_swm.py index 114c3dad8..b5e946088 100644 --- a/libpysal/io/iohandlers/tests/test_arcgis_swm.py +++ b/libpysal/io/iohandlers/tests/test_arcgis_swm.py @@ -1,30 +1,32 @@ -import unittest -from ..arcgis_swm import ArcGISSwmIO -from ...fileio import FileIO as psopen -from .... import examples as pysal_examples -import tempfile import os +import tempfile + +import pytest +from .... import examples as pysal_examples +from ...fileio import FileIO as psopen +from ..arcgis_swm import ArcGISSwmIO -class test_ArcGISSwmIO(unittest.TestCase): - def setUp(self): + +class Testtest_ArcGISSwmIO: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("ohio.swm") self.obj = ArcGISSwmIO(test_file, "r") def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): w = self.obj.read() - self.assertEqual(88, w.n) - self.assertEqual(5.25, w.mean_neighbors) - self.assertEqual([1.0, 1.0, 1.0, 1.0], list(w[1].values())) + assert w.n == 88 + assert w.mean_neighbors == 5.25 + assert [1.0, 1.0, 1.0, 1.0] == list(w[1].values()) def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj.read) + pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() @@ -37,9 +39,5 @@ def test_write(self): o.write(w) o.close() wnew = psopen(fname, "r").read() - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_arcgis_txt.py b/libpysal/io/iohandlers/tests/test_arcgis_txt.py index 4c1f9b453..8c50d80d0 100644 --- a/libpysal/io/iohandlers/tests/test_arcgis_txt.py +++ b/libpysal/io/iohandlers/tests/test_arcgis_txt.py @@ -1,21 +1,23 @@ -import unittest -from ..arcgis_txt import ArcGISTextIO -from ...fileio import FileIO as psopen -from .... import examples as pysal_examples -import tempfile import os +import tempfile import warnings +import pytest + +from .... import examples as pysal_examples +from ...fileio import FileIO as psopen +from ..arcgis_txt import ArcGISTextIO -class test_ArcGISTextIO(unittest.TestCase): - def setUp(self): + +class Testtest_ArcGISTextIO: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("arcgis_txt.txt") self.obj = ArcGISTextIO(test_file, "r") def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): with warnings.catch_warnings(record=True) as warn: @@ -27,13 +29,13 @@ def test_read(self): "DBF relating to ArcGIS TEXT was not found, proceeding with unordered string IDs." in str(warn[0].message) ) - self.assertEqual(3, w.n) - self.assertEqual(2.0, w.mean_neighbors) - self.assertEqual([0.1, 0.05], list(w[2].values())) + assert w.n == 3 + assert w.mean_neighbors == 2.0 + assert [0.1, 0.05] == list(w[2].values()) def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj.read) + pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() @@ -62,9 +64,5 @@ def test_write(self): "DBF relating to ArcGIS TEXT was not found, proceeding with unordered string IDs." in str(warn[0].message) ) - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_csvWrapper.py b/libpysal/io/iohandlers/tests/test_csvWrapper.py index 3d6860b66..032e0c103 100644 --- a/libpysal/io/iohandlers/tests/test_csvWrapper.py +++ b/libpysal/io/iohandlers/tests/test_csvWrapper.py @@ -1,49 +1,47 @@ -import unittest +from sys import version as V + from .... import examples as pysal_examples -from .. import csvWrapper from ...util import WKTParser -import tempfile -import os -from sys import version as V +from .. import csvWrapper PY3 = int(V[0]) > 2 -class test_csvWrapper(unittest.TestCase): - def setUp(self): +class TesttestCsvWrapper: + def setup_method(self): stl = pysal_examples.load_example("stl") self.test_file = test_file = stl.get_path("stl_hom.csv") self.obj = csvWrapper.csvWrapper(test_file, "r") def test_len(self): - self.assertEqual(len(self.obj), 78) + assert len(self.obj) == 78 def test_tell(self): - self.assertEqual(self.obj.tell(), 0) + assert self.obj.tell() == 0 self.obj.read(1) - self.assertEqual(self.obj.tell(), 1) + assert self.obj.tell() == 1 self.obj.read(50) - self.assertEqual(self.obj.tell(), 51) + assert self.obj.tell() == 51 self.obj.read() - self.assertEqual(self.obj.tell(), 78) + assert self.obj.tell() == 78 def test_seek(self): self.obj.seek(0) - self.assertEqual(self.obj.tell(), 0) + assert self.obj.tell() == 0 self.obj.seek(55) - self.assertEqual(self.obj.tell(), 55) + assert self.obj.tell() == 55 self.obj.read(1) - self.assertEqual(self.obj.tell(), 56) + assert self.obj.tell() == 56 def test_read(self): self.obj.seek(0) objs = self.obj.read() - self.assertEqual(len(objs), 78) + assert len(objs) == 78 self.obj.seek(0) objsB = list(self.obj) - self.assertEqual(len(objsB), 78) + assert len(objsB) == 78 for rowA, rowB in zip(objs, objsB): - self.assertEqual(rowA, rowB) + assert rowA == rowB def test_casting(self): self.obj.cast("WKT", WKTParser()) @@ -67,23 +65,19 @@ def test_casting(self): ] if PY3: for i, pt in enumerate(self.obj.__next__()[0].vertices): - self.assertEqual(pt[:], verts[i]) + assert pt[:] == verts[i] else: for i, pt in enumerate(self.obj.next()[0].vertices): - self.assertEqual(pt[:], verts[i]) + assert pt[:] == verts[i] def test_by_col(self): for field in self.obj.header: - self.assertEqual(len(self.obj.by_col[field]), 78) + assert len(self.obj.by_col[field]) == 78 def test_slicing(self): chunk = self.obj[50:55, 1:3] - self.assertEqual(chunk[0], ["Jefferson", "Missouri"]) - self.assertEqual(chunk[1], ["Jefferson", "Illinois"]) - self.assertEqual(chunk[2], ["Miller", "Missouri"]) - self.assertEqual(chunk[3], ["Maries", "Missouri"]) - self.assertEqual(chunk[4], ["White", "Illinois"]) - - -if __name__ == "__main__": - unittest.main() + assert chunk[0] == ["Jefferson", "Missouri"] + assert chunk[1] == ["Jefferson", "Illinois"] + assert chunk[2] == ["Miller", "Missouri"] + assert chunk[3] == ["Maries", "Missouri"] + assert chunk[4] == ["White", "Illinois"] diff --git a/libpysal/io/iohandlers/tests/test_dat.py b/libpysal/io/iohandlers/tests/test_dat.py index f22c07397..c37ac6ed2 100644 --- a/libpysal/io/iohandlers/tests/test_dat.py +++ b/libpysal/io/iohandlers/tests/test_dat.py @@ -1,30 +1,32 @@ -import unittest +import os +import tempfile + +import pytest + +from .... import examples as pysal_examples from ...fileio import FileIO as psopen from ..dat import DatIO -from .... import examples as pysal_examples -import tempfile -import os -class test_DatIO(unittest.TestCase): - def setUp(self): +class Testtest_DatIO: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("wmat.dat") self.obj = DatIO(test_file, "r") def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): w = self.obj.read() - self.assertEqual(49, w.n) - self.assertEqual(4.7346938775510203, w.mean_neighbors) - self.assertEqual([0.5, 0.5], list(w[5.0].values())) + assert w.n == 49 + assert w.mean_neighbors == 4.7346938775510203 + assert [0.5, 0.5] == list(w[5.0].values()) def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj.read) + pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() @@ -37,9 +39,5 @@ def test_write(self): o.write(w) o.close() wnew = psopen(fname, "r").read() - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_db.py b/libpysal/io/iohandlers/tests/test_db.py index bc6530ffb..1ee5c1732 100644 --- a/libpysal/io/iohandlers/tests/test_db.py +++ b/libpysal/io/iohandlers/tests/test_db.py @@ -1,12 +1,13 @@ import os -from ... import geotable as pdio -from ...fileio import FileIO as psopen -import unittest as ut -from .... import examples as pysal_examples - import platform + +import pytest import shapely +from .... import examples as pysal_examples +from ... import geotable as pdio +from ...fileio import FileIO as psopen + try: import sqlalchemy @@ -18,10 +19,10 @@ windows = platform.system() == "Windows" -@ut.skipIf(windows, "Skipping Windows due to `PermissionError`.") -@ut.skipIf(missing_sql, f"Missing dependency: SQLAlchemy ({missing_sql}).") -class Test_sqlite_reader(ut.TestCase): - def setUp(self): +@pytest.mark.skipif(windows, reason="Skipping Windows due to `PermissionError`.") +@pytest.mark.skipif(missing_sql, reason="Missing dependency: SQLAlchemy.") +class TestSqliteReader: + def setup_method(self): path = pysal_examples.get_path("new_haven_merged.dbf") if path is None: pysal_examples.load_example("newHaven") @@ -49,15 +50,11 @@ def setUp(self): def test_deserialize(self): db = psopen(f"sqlite:///{self.dbf}") - self.assertEqual(db.tables, ["newhaven"]) + assert db.tables == ["newhaven"] gj = db._get_gjson("newhaven") - self.assertEqual(gj["type"], "FeatureCollection") + assert gj["type"] == "FeatureCollection" self.conn.close() os.remove(self.dbf) - - -if __name__ == "__main__": - ut.main() diff --git a/libpysal/io/iohandlers/tests/test_gal.py b/libpysal/io/iohandlers/tests/test_gal.py index b2be9d4d9..f42112832 100644 --- a/libpysal/io/iohandlers/tests/test_gal.py +++ b/libpysal/io/iohandlers/tests/test_gal.py @@ -1,36 +1,37 @@ """Unit tests for gal.py""" -import unittest import tempfile -import os -from ..gal import GalIO -from ...fileio import FileIO as psopen + +import pytest + from .... import examples as pysal_examples +from ...fileio import FileIO as psopen +from ..gal import GalIO -class test_GalIO(unittest.TestCase): - def setUp(self): +class Testtest_GalIO: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("sids2.gal") self.obj = GalIO(test_file, "r") def test___init__(self): - self.assertEqual(self.obj._typ, str) + assert self.obj._typ == str def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): # reading a GAL returns a W w = self.obj.read() - self.assertEqual(w.n, 100) - self.assertAlmostEqual(w.sd, 1.5151237573214935) - self.assertEqual(w.s0, 462.0) - self.assertEqual(w.s1, 924.0) + assert w.n == 100 + assert w.sd == pytest.approx(1.5151237573214935) + assert w.s0 == 462.0 + assert w.s1 == 924.0 def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj.read) + pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() @@ -43,8 +44,4 @@ def test_write(self): o.write(w) o.close() wnew = psopen(fname, "r").read() - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) - - -if __name__ == "__main__": - unittest.main() + assert wnew.pct_nonzero == w.pct_nonzero diff --git a/libpysal/io/iohandlers/tests/test_geobugs_txt.py b/libpysal/io/iohandlers/tests/test_geobugs_txt.py index 5e98fb61c..78859007e 100644 --- a/libpysal/io/iohandlers/tests/test_geobugs_txt.py +++ b/libpysal/io/iohandlers/tests/test_geobugs_txt.py @@ -1,13 +1,15 @@ -import unittest -from ..geobugs_txt import GeoBUGSTextIO +import os +import tempfile + +import pytest + from .... import examples as pysal_examples from ...fileio import FileIO as psopen -import tempfile -import os +from ..geobugs_txt import GeoBUGSTextIO -class test_GeoBUGSTextIO(unittest.TestCase): - def setUp(self): +class Testtest_GeoBUGSTextIO: + def setup_method(self): self.test_file_scot = test_file_scot = pysal_examples.get_path("geobugs_scot") self.test_file_col = test_file_col = pysal_examples.get_path( "spdep_listw2WB_columbus" @@ -19,23 +21,23 @@ def test_close(self): for obj in [self.obj_scot, self.obj_col]: f = obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): w_scot = self.obj_scot.read() - self.assertEqual(56, w_scot.n) - self.assertEqual(4.1785714285714288, w_scot.mean_neighbors) - self.assertEqual([1.0, 1.0, 1.0], list(w_scot[1].values())) + assert w_scot.n == 56 + assert w_scot.mean_neighbors == 4.1785714285714288 + assert [1.0, 1.0, 1.0] == list(w_scot[1].values()) w_col = self.obj_col.read() - self.assertEqual(49, w_col.n) - self.assertEqual(4.6938775510204085, w_col.mean_neighbors) - self.assertEqual([0.5, 0.5], list(w_col[1].values())) + assert w_col.n == 49 + assert w_col.mean_neighbors == 4.6938775510204085 + assert [0.5, 0.5] == list(w_col[1].values()) def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj_scot.read) - self.assertRaises(StopIteration, self.obj_col.read) + pytest.raises(StopIteration, self.obj_scot.read) + pytest.raises(StopIteration, self.obj_col.read) self.obj_scot.seek(0) self.obj_col.seek(0) self.test_read() @@ -50,9 +52,5 @@ def test_write(self): o.write(w) o.close() wnew = psopen(fname, "r", "geobugs_text").read() - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_geoda_txt.py b/libpysal/io/iohandlers/tests/test_geoda_txt.py index 6b7013ff8..456ef88aa 100644 --- a/libpysal/io/iohandlers/tests/test_geoda_txt.py +++ b/libpysal/io/iohandlers/tests/test_geoda_txt.py @@ -1,26 +1,24 @@ """GeoDa Text File Reader Unit Tests""" -import unittest -from ..geoda_txt import GeoDaTxtReader as GTR + +import pytest + from .... import examples as pysal_examples +from ..geoda_txt import GeoDaTxtReader as GTR -class test_GeoDaTxtReader(unittest.TestCase): - def setUp(self): +class Testtest_GeoDaTxtReader: + def setup_method(self): test_file = pysal_examples.get_path("stl_hom.txt") self.obj = GTR(test_file, "r") def test___init__(self): - self.assertEqual(self.obj.header, ["FIPSNO", "HR8488", "HR8893", "HC8488"]) + assert self.obj.header == ["FIPSNO", "HR8488", "HR8893", "HC8488"] def test___len__(self): expected = 78 - self.assertEqual(expected, len(self.obj)) + assert expected == len(self.obj) def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) - - -if __name__ == "__main__": - unittest.main() + pytest.raises(ValueError, f.read) diff --git a/libpysal/io/iohandlers/tests/test_gwt.py b/libpysal/io/iohandlers/tests/test_gwt.py index 0bf04d1d5..135bd697f 100644 --- a/libpysal/io/iohandlers/tests/test_gwt.py +++ b/libpysal/io/iohandlers/tests/test_gwt.py @@ -1,33 +1,33 @@ -import unittest -from ..gwt import GwtIO -from ...fileio import FileIO as psopen -from .... import examples as pysal_examples -import tempfile import os +import tempfile + import pytest -import warnings +from .... import examples as pysal_examples +from ...fileio import FileIO as psopen +from ..gwt import GwtIO -class test_GwtIO(unittest.TestCase): - def setUp(self): + +class Testtest_GwtIO: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("juvenile.gwt") self.obj = GwtIO(test_file, "r") def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): w = self.obj.read() - self.assertEqual(168, w.n) - self.assertEqual(16.678571428571427, w.mean_neighbors) + assert w.n == 168 + assert w.mean_neighbors == 16.678571428571427 w.transform = "B" - self.assertEqual([1.0], list(w[1].values())) + assert [1.0] == list(w[1].values()) def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj.read) + pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() @@ -49,9 +49,5 @@ def test_write(self): o.write(w) o.close() wnew = psopen(fname, "r").read() - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_mat.py b/libpysal/io/iohandlers/tests/test_mat.py index cb6e856c6..87745a21b 100644 --- a/libpysal/io/iohandlers/tests/test_mat.py +++ b/libpysal/io/iohandlers/tests/test_mat.py @@ -1,31 +1,33 @@ -import unittest -from ..mat import MatIO -from .... import examples as pysal_examples -from ...fileio import FileIO as psopen -import tempfile import os +import tempfile import warnings +import pytest + +from .... import examples as pysal_examples +from ...fileio import FileIO as psopen +from ..mat import MatIO -class test_MatIO(unittest.TestCase): - def setUp(self): + +class Testtest_MatIO: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("spat-sym-us.mat") self.obj = MatIO(test_file, "r") def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): w = self.obj.read() - self.assertEqual(46, w.n) - self.assertEqual(4.0869565217391308, w.mean_neighbors) - self.assertEqual([1.0, 1.0, 1.0, 1.0], list(w[1].values())) + assert w.n == 46 + assert w.mean_neighbors == 4.0869565217391308 + assert [1.0, 1.0, 1.0, 1.0] == list(w[1].values()) def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj.read) + pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() @@ -42,9 +44,5 @@ def test_write(self): assert issubclass(warn[0].category, FutureWarning) o.close() wnew = psopen(fname, "r").read() - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_mtx.py b/libpysal/io/iohandlers/tests/test_mtx.py index e191fe657..9140268ff 100644 --- a/libpysal/io/iohandlers/tests/test_mtx.py +++ b/libpysal/io/iohandlers/tests/test_mtx.py @@ -1,40 +1,38 @@ -import unittest -from ..mtx import MtxIO -from ...fileio import FileIO as psopen -from .... import examples as pysal_examples -import tempfile import os -import warnings -import scipy.sparse as SP +import tempfile + +import pytest +from .... import examples as pysal_examples +from ...fileio import FileIO as psopen +from ..mtx import MtxIO -class test_MtxIO(unittest.TestCase): - def setUp(self): + +class TesttestMtxIO: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("wmat.mtx") self.obj = MtxIO(test_file, "r") def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): w = self.obj.read() - self.assertEqual(49, w.n) - self.assertEqual(4.7346938775510203, w.mean_neighbors) - self.assertEqual( - [0.33329999999999999, 0.33329999999999999, 0.33329999999999999], - list(w[1].values()), - ) + assert w.n == 49 + assert w.mean_neighbors == 4.7346938775510203 + assert [0.33329999999999999, 0.33329999999999999, 0.33329999999999999] == \ + list(w[1].values()) s0 = w.s0 self.obj.seek(0) wsp = self.obj.read(sparse=True) - self.assertEqual(49, wsp.n) - self.assertEqual(s0, wsp.s0) + assert wsp.n == 49 + assert s0 == wsp.s0 def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj.read) + pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() @@ -50,11 +48,7 @@ def test_write(self): o.close() wnew = psopen(fname, "r").read(sparse=i) if i: - self.assertEqual(wnew.s0, w.s0) + assert wnew.s0 == w.s0 else: - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_pyDbfIO.py b/libpysal/io/iohandlers/tests/test_pyDbfIO.py index ff4adc8e0..6e60dbf0c 100644 --- a/libpysal/io/iohandlers/tests/test_pyDbfIO.py +++ b/libpysal/io/iohandlers/tests/test_pyDbfIO.py @@ -1,66 +1,66 @@ -import unittest +import os +import tempfile + from .... import examples as pysal_examples from ..pyDbfIO import DBF -import tempfile -import os -class test_DBF(unittest.TestCase): - def setUp(self): +class Testtest_DBF: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("10740.dbf") self.dbObj = DBF(test_file, "r") def test_len(self): - self.assertEqual(len(self.dbObj), 195) + assert len(self.dbObj) == 195 def test_tell(self): - self.assertEqual(self.dbObj.tell(), 0) + assert self.dbObj.tell() == 0 self.dbObj.read(1) - self.assertEqual(self.dbObj.tell(), 1) + assert self.dbObj.tell() == 1 self.dbObj.read(50) - self.assertEqual(self.dbObj.tell(), 51) + assert self.dbObj.tell() == 51 self.dbObj.read() - self.assertEqual(self.dbObj.tell(), 195) + assert self.dbObj.tell() == 195 def test_cast(self): - self.assertEqual(self.dbObj._spec, []) + assert self.dbObj._spec == [] self.dbObj.cast("FIPSSTCO", float) - self.assertEqual(self.dbObj._spec[1], float) + assert self.dbObj._spec[1] == float def test_seek(self): self.dbObj.seek(0) - self.assertEqual(self.dbObj.tell(), 0) + assert self.dbObj.tell() == 0 self.dbObj.seek(55) - self.assertEqual(self.dbObj.tell(), 55) + assert self.dbObj.tell() == 55 self.dbObj.read(1) - self.assertEqual(self.dbObj.tell(), 56) + assert self.dbObj.tell() == 56 def test_read(self): self.dbObj.seek(0) objs = self.dbObj.read() - self.assertEqual(len(objs), 195) + assert len(objs) == 195 self.dbObj.seek(0) objsB = list(self.dbObj) - self.assertEqual(len(objsB), 195) + assert len(objsB) == 195 for rowA, rowB in zip(objs, objsB): - self.assertEqual(rowA, rowB) + assert rowA == rowB def test_random_access(self): self.dbObj.seek(0) db0 = self.dbObj.read(1)[0] - self.assertEqual(db0, [1, "35001", "000107", "35001000107", "1.07"]) + assert db0 == [1, "35001", "000107", "35001000107", "1.07"] self.dbObj.seek(57) db57 = self.dbObj.read(1)[0] - self.assertEqual(db57, [58, "35001", "001900", "35001001900", "19"]) + assert db57 == [58, "35001", "001900", "35001001900", "19"] self.dbObj.seek(32) db32 = self.dbObj.read(1)[0] - self.assertEqual(db32, [33, "35001", "000500", "35001000500", "5"]) + assert db32 == [33, "35001", "000500", "35001000500", "5"] self.dbObj.seek(0) - self.assertEqual(next(self.dbObj), db0) + assert next(self.dbObj) == db0 self.dbObj.seek(57) - self.assertEqual(next(self.dbObj), db57) + assert next(self.dbObj) == db57 self.dbObj.seek(32) - self.assertEqual(next(self.dbObj), db32) + assert next(self.dbObj) == db32 def test_write(self): f = tempfile.NamedTemporaryFile(suffix=".dbf") @@ -82,13 +82,13 @@ def test_write(self): # PySAL writes proper DBF files with a terminator at the end, not everyone does. n = self.dbObj.record_size * self.dbObj.n_records # bytes to read. - self.assertEqual(orig.read(n), copy.read(n)) + assert orig.read(n) == copy.read(n) # self.assertEquals(orig.read(1), copy.read(1)) # last byte may fail orig.close() copy.close() os.remove(self.dbfcopy) - def test_writeNones(self): + def test_write_nones(self): import datetime import time @@ -109,10 +109,6 @@ def test_writeNones(self): db.write(rec) db.close() db2 = DBF(fname, "r") - self.assertEqual(records, db2.read()) + assert records == db2.read() db2.close() os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_pyShpIO.py b/libpysal/io/iohandlers/tests/test_pyShpIO.py index e3d4123e7..f0990e2e4 100644 --- a/libpysal/io/iohandlers/tests/test_pyShpIO.py +++ b/libpysal/io/iohandlers/tests/test_pyShpIO.py @@ -1,12 +1,12 @@ -import unittest +import os +import tempfile + from .... import examples as pysal_examples from ..pyShpIO import PurePyShpWrapper -import tempfile -import os -class test_PurePyShpWrapper(unittest.TestCase): - def setUp(self): +class Testtest_PurePyShpWrapper: + def setup_method(self): test_file = pysal_examples.get_path("10740.shp") self.test_file = test_file self.shpObj = PurePyShpWrapper(test_file, "r") @@ -17,36 +17,36 @@ def setUp(self): self.shxcopy = shpcopy.replace(".shp", ".shx") def test_len(self): - self.assertEqual(len(self.shpObj), 195) + assert len(self.shpObj) == 195 def test_tell(self): - self.assertEqual(self.shpObj.tell(), 0) + assert self.shpObj.tell() == 0 self.shpObj.read(1) - self.assertEqual(self.shpObj.tell(), 1) + assert self.shpObj.tell() == 1 self.shpObj.read(50) - self.assertEqual(self.shpObj.tell(), 51) + assert self.shpObj.tell() == 51 self.shpObj.read() - self.assertEqual(self.shpObj.tell(), 195) + assert self.shpObj.tell() == 195 def test_seek(self): self.shpObj.seek(0) - self.assertEqual(self.shpObj.tell(), 0) + assert self.shpObj.tell() == 0 self.shpObj.seek(55) - self.assertEqual(self.shpObj.tell(), 55) + assert self.shpObj.tell() == 55 self.shpObj.read(1) - self.assertEqual(self.shpObj.tell(), 56) + assert self.shpObj.tell() == 56 def test_read(self): self.shpObj.seek(0) objs = self.shpObj.read() - self.assertEqual(len(objs), 195) + assert len(objs) == 195 self.shpObj.seek(0) objsB = list(self.shpObj) - self.assertEqual(len(objsB), 195) + assert len(objsB) == 195 for shpA, shpB in zip(objs, objsB): - self.assertEqual(shpA.vertices, shpB.vertices) + assert shpA.vertices == shpB.vertices def test_random_access(self): self.shpObj.seek(57) @@ -55,9 +55,9 @@ def test_random_access(self): shp32 = self.shpObj.read(1)[0] self.shpObj.seek(57) - self.assertEqual(self.shpObj.read(1)[0].vertices, shp57.vertices) + assert self.shpObj.read(1)[0].vertices == shp57.vertices self.shpObj.seek(32) - self.assertEqual(self.shpObj.read(1)[0].vertices, shp32.vertices) + assert self.shpObj.read(1)[0].vertices == shp32.vertices def test_write(self): out = PurePyShpWrapper(self.shpcopy, "w") @@ -68,19 +68,15 @@ def test_write(self): orig = open(self.test_file, "rb") copy = open(self.shpcopy, "rb") - self.assertEqual(orig.read(), copy.read()) + assert orig.read() == copy.read() orig.close() copy.close() oshx = open(self.test_file.replace(".shp", ".shx"), "rb") cshx = open(self.shxcopy, "rb") - self.assertEqual(oshx.read(), cshx.read()) + assert oshx.read() == cshx.read() oshx.close() cshx.close() os.remove(self.shpcopy) os.remove(self.shxcopy) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_stata_txt.py b/libpysal/io/iohandlers/tests/test_stata_txt.py index aad4ebd26..0969b7a7e 100644 --- a/libpysal/io/iohandlers/tests/test_stata_txt.py +++ b/libpysal/io/iohandlers/tests/test_stata_txt.py @@ -1,13 +1,15 @@ -import unittest +import os +import tempfile + +import pytest + from .... import examples as pysal_examples -from ..stata_txt import StataTextIO from ...fileio import FileIO as psopen -import tempfile -import os +from ..stata_txt import StataTextIO -class test_StataTextIO(unittest.TestCase): - def setUp(self): +class Testtest_StataTextIO: + def setup_method(self): self.test_file_sparse = test_file_sparse = pysal_examples.get_path( "stata_sparse.txt" ) @@ -19,23 +21,23 @@ def test_close(self): for obj in [self.obj_sparse, self.obj_full]: f = obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): w_sparse = self.obj_sparse.read() - self.assertEqual(56, w_sparse.n) - self.assertEqual(4.0, w_sparse.mean_neighbors) - self.assertEqual([1.0, 1.0, 1.0, 1.0, 1.0], list(w_sparse[1].values())) + assert w_sparse.n == 56 + assert w_sparse.mean_neighbors == 4.0 + assert [1.0, 1.0, 1.0, 1.0, 1.0] == list(w_sparse[1].values()) w_full = self.obj_full.read() - self.assertEqual(56, w_full.n) - self.assertEqual(4.0, w_full.mean_neighbors) - self.assertEqual([0.125, 0.125, 0.125, 0.125, 0.125], list(w_full[1].values())) + assert w_full.n == 56 + assert w_full.mean_neighbors == 4.0 + assert [0.125, 0.125, 0.125, 0.125, 0.125] == list(w_full[1].values()) def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj_sparse.read) - self.assertRaises(StopIteration, self.obj_full.read) + pytest.raises(StopIteration, self.obj_sparse.read) + pytest.raises(StopIteration, self.obj_full.read) self.obj_sparse.seek(0) self.obj_full.seek(0) self.test_read() @@ -53,9 +55,5 @@ def test_write(self): o.write(w, matrix_form=True) o.close() wnew = psopen(fname, "r", "stata_text").read() - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_wk1.py b/libpysal/io/iohandlers/tests/test_wk1.py index eb8df408a..c181c2fd2 100644 --- a/libpysal/io/iohandlers/tests/test_wk1.py +++ b/libpysal/io/iohandlers/tests/test_wk1.py @@ -1,30 +1,32 @@ -import unittest -from ..wk1 import Wk1IO +import os +import tempfile + +import pytest + from .... import examples as pysal_examples from ...fileio import FileIO as psopen -import tempfile -import os +from ..wk1 import Wk1IO -class test_Wk1IO(unittest.TestCase): - def setUp(self): +class Testtest_Wk1IO: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("spat-sym-us.wk1") self.obj = Wk1IO(test_file, "r") def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) def test_read(self): w = self.obj.read() - self.assertEqual(46, w.n) - self.assertEqual(4.0869565217391308, w.mean_neighbors) - self.assertEqual([1.0, 1.0, 1.0, 1.0], list(w[1].values())) + assert w.n == 46 + assert w.mean_neighbors == 4.0869565217391308 + assert [1.0, 1.0, 1.0, 1.0] == list(w[1].values()) def test_seek(self): self.test_read() - self.assertRaises(StopIteration, self.obj.read) + pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() @@ -37,9 +39,6 @@ def test_write(self): o.write(w) o.close() wnew = psopen(fname, "r").read() - self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) + assert wnew.pct_nonzero == w.pct_nonzero os.remove(fname) - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/iohandlers/tests/test_wkt.py b/libpysal/io/iohandlers/tests/test_wkt.py index 797d1cdb5..9f0f78a0d 100644 --- a/libpysal/io/iohandlers/tests/test_wkt.py +++ b/libpysal/io/iohandlers/tests/test_wkt.py @@ -1,30 +1,27 @@ -import unittest -from ..wkt import WKTReader +import pytest + from .... import examples as pysal_examples +from ..wkt import WKTReader -class test_WKTReader(unittest.TestCase): - def setUp(self): +class Testtest_WKTReader: + def setup_method(self): self.test_file = test_file = pysal_examples.get_path("stl_hom.wkt") self.obj = WKTReader(test_file, "r") def test_close(self): f = self.obj f.close() - self.assertRaises(ValueError, f.read) + pytest.raises(ValueError, f.read) # w_kt_reader = WKTReader(*args, **kwargs) # self.assertEqual(expected, w_kt_reader.close()) def test_open(self): f = self.obj expected = ["wkt"] - self.assertEqual(expected, f.FORMATS) + assert expected == f.FORMATS def test__read(self): polys = self.obj.read() - self.assertEqual(78, len(polys)) - self.assertEqual((-91.195784694307383, 39.990883050220845), polys[1].centroid) - - -if __name__ == "__main__": - unittest.main() + assert len(polys) == 78 + assert polys[1].centroid == (-91.195784694307383, 39.990883050220845) diff --git a/libpysal/io/tests/test_FileIO.py b/libpysal/io/tests/test_FileIO.py index d3082e702..94cc033de 100644 --- a/libpysal/io/tests/test_FileIO.py +++ b/libpysal/io/tests/test_FileIO.py @@ -1,5 +1,5 @@ -from ..fileio import FileIO from ...examples import get_path +from ..fileio import FileIO def test_by_col_exists(): diff --git a/libpysal/io/tests/test_Tables.py b/libpysal/io/tests/test_Tables.py index 5dcfdb950..7601cec54 100644 --- a/libpysal/io/tests/test_Tables.py +++ b/libpysal/io/tests/test_Tables.py @@ -1,16 +1,15 @@ import numpy as np -from ..fileio import FileIO as psopen -from ...common import pandas # import pysal_examples from ... import examples as pysal_examples -import unittest as ut +from ...common import pandas +from ..fileio import FileIO as psopen PANDAS_EXTINCT = pandas is None -class Test_Table(ut.TestCase): - def setUp(self): +class TestTable: + def setup_method(self): self.filehandler = psopen(pysal_examples.get_path("columbus.dbf")) self.df = self.filehandler.to_df() self.filehandler.seek(0) @@ -19,7 +18,6 @@ def setUp(self): self.csv_df = self.csvhandler.to_df() self.csvhandler.seek(0) - @ut.skipIf(PANDAS_EXTINCT, "Missing pandas.") def test_to_df(self): for column in self.csv_df.columns: if column.lower() == "name": diff --git a/libpysal/io/util/tests/test_shapefile.py b/libpysal/io/util/tests/test_shapefile.py index 4bcf00934..334b69d8d 100644 --- a/libpysal/io/util/tests/test_shapefile.py +++ b/libpysal/io/util/tests/test_shapefile.py @@ -1,53 +1,50 @@ -import unittest -import sys +import pytest import io +import os # import pysal_examples from .... import examples as pysal_examples - from ..shapefile import ( - noneMax, - noneMin, - shp_file, - shx_file, + MultiPatch, + MultiPoint, + MultiPointM, + MultiPointZ, NullShape, Point, - PolyLine, - MultiPoint, + PointM, PointZ, - PolyLineZ, + PolygonM, PolygonZ, - MultiPointZ, - PointM, + PolyLine, PolyLineM, - PolygonM, - MultiPointM, - MultiPatch, + PolyLineZ, + noneMax, + noneMin, + shp_file, + shx_file, ) -import os def bufferIO(buf): - """Temp stringIO function to force compat. - """ + """Temp stringIO function to force compat.""" return io.BytesIO(buf) -class TestNoneMax(unittest.TestCase): +class TestNoneMax: def test_none_max(self): - self.assertEqual(5, noneMax(5, None)) - self.assertEqual(1, noneMax(None, 1)) - self.assertEqual(None, noneMax(None, None)) + assert 5 == noneMax(5, None) + assert 1 == noneMax(None, 1) + assert None is noneMax(None, None) -class TestNoneMin(unittest.TestCase): +class TestNoneMin: def test_none_min(self): - self.assertEqual(5, noneMin(5, None)) - self.assertEqual(1, noneMin(None, 1)) - self.assertEqual(None, noneMin(None, None)) + assert 5 == noneMin(5, None) + assert 1 == noneMin(None, 1) + assert None is noneMin(None, None) -class test_shp_file(unittest.TestCase): +class test_shp_file: def test___init__(self): shp = shp_file(pysal_examples.get_path("10740.shp")) assert shp.header == { @@ -104,14 +101,14 @@ def test_add_shape(self): shp.close() for a, b in zip(points, shp_file("test_point")): - self.assertEqual(a, b) + assert a == b os.remove("test_point.shp") os.remove("test_point.shx") def test_close(self): shp = shp_file(pysal_examples.get_path("10740.shp")) shp.close() - self.assertEqual(shp.fileObj.closed, True) + assert shp.fileObj.closed == True def test_get_shape(self): shp = shp_file(pysal_examples.get_path("Line.shp")) @@ -131,7 +128,7 @@ def test_get_shape(self): "Shape Type": 3, "Parts Index": [0], } - self.assertEqual(expected, shp.get_shape(0)) + assert expected == shp.get_shape(0) def test_next(self): shp = shp_file(pysal_examples.get_path("Point.shp")) @@ -141,24 +138,24 @@ def test_next(self): "X": -0.00068176617532103578, "Shape Type": 1, } - self.assertEqual(expected, next(shp)) + assert expected == next(shp) expected = { "Y": -0.25630328607387354, "X": 0.11697145363360706, "Shape Type": 1, } - self.assertEqual(expected, next(shp)) + assert expected == next(shp) def test_type(self): shp = shp_file(pysal_examples.get_path("Point.shp")) - self.assertEqual("POINT", shp.type()) + assert "POINT" == shp.type() shp = shp_file(pysal_examples.get_path("Polygon.shp")) - self.assertEqual("POLYGON", shp.type()) + assert "POLYGON" == shp.type() shp = shp_file(pysal_examples.get_path("Line.shp")) - self.assertEqual("ARC", shp.type()) + assert "ARC" == shp.type() -class test_shx_file(unittest.TestCase): +class test_shx_file: def test___init__(self): shx = shx_file(pysal_examples.get_path("Point.shx")) assert isinstance(shx, shx_file) @@ -192,34 +189,34 @@ def test_add_record(self): def test_close(self): shx = shx_file(pysal_examples.get_path("Point.shx")) shx.close(None) - self.assertEqual(shx.fileObj.closed, True) + assert shx.fileObj.closed == True -class TestNullShape(unittest.TestCase): +class TestNullShape: def test_pack(self): null_shape = NullShape() - self.assertEqual(b"\x00" * 4, null_shape.pack()) + assert b"\x00" * 4 == null_shape.pack() def test_unpack(self): null_shape = NullShape() - self.assertEqual(None, null_shape.unpack()) + assert None is null_shape.unpack() -class TestPoint(unittest.TestCase): +class TestPoint: def test_pack(self): record = {"X": 5, "Y": 5, "Shape Type": 1} expected = b"\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x40\x00\x00\x00\x00\x00\x00\x14\x40" - self.assertEqual(expected, Point.pack(record)) + assert expected == Point.pack(record) def test_unpack(self): dat = bufferIO( b"\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x40\x00\x00\x00\x00\x00\x00\x14\x40" ) expected = {"X": 5, "Y": 5, "Shape Type": 1} - self.assertEqual(expected, Point.unpack(dat)) + assert expected == Point.unpack(dat) -class TestPolyLine(unittest.TestCase): +class TestPolyLine: def test_pack(self): record = { "BBOX Ymax": -0.25832280562918325, @@ -245,7 +242,7 @@ def test_pack(self): \xa0\xe5\x8f\xa4\x7e\x3f\x3d\xc1\x65\xce\xc7\ \x92\xd0\xbf\x00\xc5\xa0\xe5\x8f\xa4\x7e\x3f\ \x3d\xc1\x65\xce\xc7\x92\xd0\xbf""" - self.assertEqual(expected, PolyLine.pack(record)) + assert expected == PolyLine.pack(record) def test_unpack(self): dat = bufferIO( @@ -274,34 +271,34 @@ def test_unpack(self): "Shape Type": 3, "Parts Index": [0], } - self.assertEqual(expected, PolyLine.unpack(dat)) + assert expected == PolyLine.unpack(dat) -class TestMultiPoint(unittest.TestCase): +class TestMultiPoint: def test___init__(self): - self.assertRaises(NotImplementedError, MultiPoint) + pytest.raises(NotImplementedError, MultiPoint) -class TestPointZ(unittest.TestCase): +class TestPointZ: def test_pack(self): record = {"X": 5, "Y": 5, "Z": 5, "M": 5, "Shape Type": 11} expected = b"\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x14@" - self.assertEqual(expected, PointZ.pack(record)) + assert expected == PointZ.pack(record) def test_unpack(self): dat = bufferIO( b"\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x14@" ) expected = {"X": 5, "Y": 5, "Z": 5, "M": 5, "Shape Type": 11} - self.assertEqual(expected, PointZ.unpack(dat)) + assert expected == PointZ.unpack(dat) -class TestPolyLineZ(unittest.TestCase): +class TestPolyLineZ: def test___init__(self): - self.assertRaises(NotImplementedError, PolyLineZ) + pytest.raises(NotImplementedError, PolyLineZ) -class TestPolyLineZ(unittest.TestCase): +class TestPolyLineZ: def test_pack(self): record = { "BBOX Ymax": -0.25832280562918325, @@ -325,7 +322,7 @@ def test_pack(self): "Marray": [2, 3, 4], } expected = b"""\r\x00\x00\x00\xc0FR:\xdd\x8a\x82\xbf=\xc1e\xce\xc7\x92\xd0\xbf\x00\xc5\xa0\xe5\x8f\xa4~?k@\x7f`\\\x88\xd0\xbf\x01\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\xc0FR:\xdd\x8a\x82\xbfk@\x7f`\\\x88\xd0\xbf\x00\xc5\xa0\xe5\x8f\xa4~?=\xc1e\xce\xc7\x92\xd0\xbf\x00\xc5\xa0\xe5\x8f\xa4~?=\xc1e\xce\xc7\x92\xd0\xbf\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00$@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00$@\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x10@""" - self.assertEqual(expected, PolyLineZ.pack(record)) + assert expected == PolyLineZ.pack(record) def test_unpack(self): dat = bufferIO( @@ -352,10 +349,10 @@ def test_unpack(self): "Mmax": 4, "Marray": [2, 3, 4], } - self.assertEqual(expected, PolyLineZ.unpack(dat)) + assert expected == PolyLineZ.unpack(dat) -class TestPolygonZ(unittest.TestCase): +class TestPolygonZ: def test_pack(self): record = { "BBOX Xmin": 0.0, @@ -375,46 +372,46 @@ def test_pack(self): "Marray": [2, 4, 2, 2], } dat = bufferIO(PolygonZ.pack(record)) - self.assertEqual(record, PolygonZ.unpack(dat)) + assert record == PolygonZ.unpack(dat) -class TestMultiPointZ(unittest.TestCase): +class TestMultiPointZ: def test___init__(self): - self.assertRaises(NotImplementedError, MultiPointZ) + pytest.raises(NotImplementedError, MultiPointZ) # multi_point_z = MultiPointZ() -class TestPointM(unittest.TestCase): +class TestPointM: def test___init__(self): - self.assertRaises(NotImplementedError, PointM) + pytest.raises(NotImplementedError, PointM) # point_m = PointM() -class TestPolyLineM(unittest.TestCase): +class TestPolyLineM: def test___init__(self): - self.assertRaises(NotImplementedError, PolyLineM) + pytest.raises(NotImplementedError, PolyLineM) # poly_line_m = PolyLineM() -class TestPolygonM(unittest.TestCase): +class TestPolygonM: def test___init__(self): - self.assertRaises(NotImplementedError, PolygonM) + pytest.raises(NotImplementedError, PolygonM) # polygon_m = PolygonM() -class TestMultiPointM(unittest.TestCase): +class TestMultiPointM: def test___init__(self): - self.assertRaises(NotImplementedError, MultiPointM) + pytest.raises(NotImplementedError, MultiPointM) # multi_point_m = MultiPointM() -class TestMultiPatch(unittest.TestCase): +class TestMultiPatch: def test___init__(self): - self.assertRaises(NotImplementedError, MultiPatch) + pytest.raises(NotImplementedError, MultiPatch) # multi_patch = MultiPatch() -class _TestPoints(unittest.TestCase): +class _TestPoints: def test1(self): """Test creating and reading Point Shape Files.""" shp = shp_file("test_point", "w", "POINT") @@ -431,12 +428,12 @@ def test1(self): shp = list(shp_file("test_point")) for a, b in zip(points, shp): - self.assertEqual(a, b) + assert a == b os.remove("test_point.shp") os.remove("test_point.shx") -class _TestPolyLines(unittest.TestCase): +class _TestPolyLines: def test1(self): """Test creating and reading PolyLine Shape Files.""" lines = [[(0, 0), (4, 4)], [(1, 0), (5, 4)], [(2, 0), (6, 4)]] @@ -461,12 +458,12 @@ def test1(self): shp.close() shp = list(shp_file("test_line")) for a, b in zip(shapes, shp): - self.assertEqual(a, b) + assert a == b os.remove("test_line.shp") os.remove("test_line.shx") -class _TestPolygons(unittest.TestCase): +class _TestPolygons: def test1(self): """Test creating and reading PolyLine Shape Files.""" lines = [ @@ -494,10 +491,6 @@ def test1(self): shp.close() shp = list(shp_file("test_poly")) for a, b in zip(shapes, shp): - self.assertEqual(a, b) + assert a == b os.remove("test_poly.shp") os.remove("test_poly.shx") - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/util/tests/test_weight_converter.py b/libpysal/io/util/tests/test_weight_converter.py index c48fa556e..2b436e66d 100644 --- a/libpysal/io/util/tests/test_weight_converter.py +++ b/libpysal/io/util/tests/test_weight_converter.py @@ -1,4 +1,4 @@ -import unittest +import pytest from ..weight_converter import WeightConverter from ..weight_converter import weight_convert from ...fileio import FileIO as psopen @@ -10,9 +10,9 @@ from .... import examples as pysal_examples -@unittest.skip("This function is deprecated.") -class test_WeightConverter(unittest.TestCase): - def setUp(self): +@pytest.mark.skip("This function is deprecated.") +class Testtest_WeightConverter: + def setup_method(self): test_files = [ "arcgis_ohio.dbf", "arcgis_txt.txt", @@ -59,15 +59,15 @@ def setUp(self): ("wk1", None), ] - def test__setW(self): + def test__set_w(self): for f in self.test_files: with warnings.catch_warnings(record=True) as warn: # note: we are just suppressing the warnings here; individual warnings # are tested in their specific readers warnings.simplefilter("always") wc = WeightConverter(f, dataFormat=self.dataformats[f]) - self.assertEqual(wc.w_set(), True) - self.assertEqual(wc.w.n, self.ns[f]) + assert wc.w_set() == True + assert wc.w.n == self.ns[f] def test_write(self): for f in self.test_files: @@ -112,9 +112,9 @@ def test_write(self): ext in ["dbf", "swm", "dat", "wk1", "gwt"] or dataformat == "arcgis_text" ): - self.assertEqual(wnew.n, wc.w.n - len(wc.w.islands)) + assert wnew.n == wc.w.n - len(wc.w.islands) else: - self.assertEqual(wnew.n, wc.w.n) + assert wnew.n == wc.w.n os.remove(temp_fname) def test_weight_convert(self): @@ -170,11 +170,7 @@ def test_weight_convert(self): ext in ["dbf", "swm", "dat", "wk1", "gwt"] or dataformat == "arcgis_text" ): - self.assertEqual(wnew.n, wold.n - len(wold.islands)) + assert wnew.n == wold.n - len(wold.islands) else: - self.assertEqual(wnew.n, wold.n) + assert wnew.n == wold.n os.remove(outFile) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/io/util/tests/test_wkt.py b/libpysal/io/util/tests/test_wkt.py index c934355cd..8e38246cd 100644 --- a/libpysal/io/util/tests/test_wkt.py +++ b/libpysal/io/util/tests/test_wkt.py @@ -1,10 +1,10 @@ -import unittest +import pytest from ..wkt import WKTParser from ....cg.shapes import Point, Chain, Polygon -class test_WKTParser(unittest.TestCase): - def setUp(self): +class Testtest_WKTParser: + def setup_method(self): # Create some Well-Known Text objects self.wktPOINT = "POINT(6 10)" self.wktLINESTRING = "LINESTRING(3 4,10 50,20 25)" @@ -20,39 +20,32 @@ def setUp(self): self.empty = ["POINT EMPTY", "MULTIPOLYGON EMPTY"] self.parser = WKTParser() - def test_Point(self): + def test_point(self): pt = self.parser(self.wktPOINT) - self.assertTrue(issubclass(type(pt), Point)) - self.assertEqual(pt[:], (6.0, 10.0)) + assert issubclass(type(pt), Point) + assert pt[:] == (6.0, 10.0) - def test_LineString(self): + def test_line_string(self): line = self.parser(self.wktLINESTRING) - self.assertTrue(issubclass(type(line), Chain)) + assert issubclass(type(line), Chain) parts = [[pt[:] for pt in part] for part in line.parts] - self.assertEqual(parts, [[(3.0, 4.0), (10.0, 50.0), (20.0, 25.0)]]) - self.assertEqual(line.len, 73.455384532199886) + assert parts == [[(3.0, 4.0), (10.0, 50.0), (20.0, 25.0)]] + assert line.len == 73.455384532199886 - def test_Polygon(self): + def test_polygon(self): poly = self.parser(self.wktPOLYGON) - self.assertTrue(issubclass(type(poly), Polygon)) + assert issubclass(type(poly), Polygon) parts = [[pt[:] for pt in part] for part in poly.parts] - self.assertEqual( - parts, - [ - [(1.0, 1.0), (1.0, 5.0), (5.0, 5.0), (5.0, 1.0), (1.0, 1.0)], - [(2.0, 2.0), (2.0, 3.0), (3.0, 3.0), (3.0, 2.0), (2.0, 2.0)], - ], - ) - self.assertEqual(poly.centroid, (2.9705882352941178, 2.9705882352941178)) - self.assertEqual(poly.area, 17.0) + assert parts == [ + [(1.0, 1.0), (1.0, 5.0), (5.0, 5.0), (5.0, 1.0), (1.0, 1.0)], + [(2.0, 2.0), (2.0, 3.0), (3.0, 3.0), (3.0, 2.0), (2.0, 2.0)], + ] + assert poly.centroid == (2.9705882352941178, 2.9705882352941178) + assert poly.area == 17.0 - def test_fromWKT(self): + def test_from_wkt(self): for wkt in self.unsupported: - self.assertRaises(NotImplementedError, self.parser.fromWKT, wkt) + pytest.raises(NotImplementedError, self.parser.fromWKT, wkt) for wkt in self.empty: - self.assertEqual(self.parser.fromWKT(wkt), None) - self.assertEqual(self.parser.__call__, self.parser.fromWKT) - - -if __name__ == "__main__": - unittest.main() + assert self.parser.fromWKT(wkt) == None + assert self.parser.__call__ == self.parser.fromWKT diff --git a/libpysal/weights/tests/test_Wsets.py b/libpysal/weights/tests/test_Wsets.py index c4e73141f..72cef064d 100644 --- a/libpysal/weights/tests/test_Wsets.py +++ b/libpysal/weights/tests/test_Wsets.py @@ -1,11 +1,11 @@ """Unit test for set_operations module.""" -import unittest -from ..util import lat2W, block_weights -from .. import set_operations import numpy as np +from .. import set_operations +from ..util import block_weights, lat2W + -class Testset_operations(unittest.TestCase): +class TestSetOperations: """Unit test for set_operations module.""" def test_w_union(self): @@ -13,49 +13,49 @@ def test_w_union(self): w1 = lat2W(4, 4) w2 = lat2W(6, 4) w3 = set_operations.w_union(w1, w2) - self.assertEqual(w1[0], w3[0]) - self.assertEqual(set(w1.neighbors[15]), set([11, 14])) - self.assertEqual(set(w2.neighbors[15]), set([11, 14, 19])) - self.assertEqual(set(w3.neighbors[15]), set([19, 11, 14])) + assert w1[0] == w3[0] + assert set(w1.neighbors[15]) == set([11, 14]) + assert set(w2.neighbors[15]) == set([11, 14, 19]) + assert set(w3.neighbors[15]) == set([19, 11, 14]) def test_w_intersection(self): """Unit test""" w1 = lat2W(4, 4) w2 = lat2W(6, 4) w3 = set_operations.w_union(w1, w2) - self.assertEqual(w1[0], w3[0]) - self.assertEqual(set(w1.neighbors[15]), set([11, 14])) - self.assertEqual(set(w2.neighbors[15]), set([11, 14, 19])) - self.assertEqual(set(w3.neighbors[15]), set([19, 11, 14])) + assert w1[0] == w3[0] + assert set(w1.neighbors[15]) == set([11, 14]) + assert set(w2.neighbors[15]) == set([11, 14, 19]) + assert set(w3.neighbors[15]) == set([19, 11, 14]) def test_w_difference(self): """Unit test""" w1 = lat2W(4, 4, rook=False) w2 = lat2W(4, 4, rook=True) w3 = set_operations.w_difference(w1, w2, constrained=False) - self.assertNotEqual(w1[0], w3[0]) - self.assertEqual(set(w1.neighbors[15]), set([10, 11, 14])) - self.assertEqual(set(w2.neighbors[15]), set([11, 14])) - self.assertEqual(set(w3.neighbors[15]), set([10])) + assert w1[0] != w3[0] + assert set(w1.neighbors[15]) == set([10, 11, 14]) + assert set(w2.neighbors[15]) == set([11, 14]) + assert set(w3.neighbors[15]) == set([10]) def test_w_symmetric_difference(self): """Unit test""" w1 = lat2W(4, 4, rook=False) w2 = lat2W(6, 4, rook=True) w3 = set_operations.w_symmetric_difference(w1, w2, constrained=False) - self.assertNotEqual(w1[0], w3[0]) - self.assertEqual(set(w1.neighbors[15]), set([10, 11, 14])) - self.assertEqual(set(w2.neighbors[15]), set([11, 14, 19])) - self.assertEqual(set(w3.neighbors[15]), set([10, 19])) + assert w1[0] != w3[0] + assert set(w1.neighbors[15]) == set([10, 11, 14]) + assert set(w2.neighbors[15]) == set([11, 14, 19]) + assert set(w3.neighbors[15]) == set([10, 19]) def test_w_subset(self): """Unit test""" w1 = lat2W(6, 4) ids = list(range(16)) w2 = set_operations.w_subset(w1, ids) - self.assertEqual(w1[0], w2[0]) - self.assertEqual(set(w1.neighbors[15]), set([11, 14, 19])) - self.assertEqual(set(w2.neighbors[15]), set([11, 14])) + assert w1[0] == w2[0] + assert set(w1.neighbors[15]) == set([11, 14, 19]) + assert set(w2.neighbors[15]) == set([11, 14]) def test_w_clip(self): """Unit test for w_clip""" @@ -80,10 +80,3 @@ def test_w_clip(self): wc = set_operations.w_clip(w1, w2, outSP=False) np.testing.assert_array_equal(wcs.sparse.toarray(), wc.full()[0]) - - -suite = unittest.TestLoader().loadTestsFromTestCase(Testset_operations) - -if __name__ == "__main__": - runner = unittest.TextTestRunner() - runner.run(suite) diff --git a/libpysal/weights/tests/test__contW_lists.py b/libpysal/weights/tests/test__contW_lists.py index 4ac9f1727..903defb96 100644 --- a/libpysal/weights/tests/test__contW_lists.py +++ b/libpysal/weights/tests/test__contW_lists.py @@ -1,39 +1,33 @@ import os -import unittest -from .._contW_lists import ContiguityWeightsLists, ROOK, QUEEN -from ..weights import W -from ...io.fileio import FileIO as ps_open - - -try: - import geopandas as gpd -except ImportError: - gpd = None +import geopandas as gpd from ... import examples as pysal_examples +from ...io.fileio import FileIO as ps_open +from .._contW_lists import QUEEN, ROOK, ContiguityWeightsLists +from ..weights import W -class TestContiguityWeights(unittest.TestCase): - def setUp(self): - """ Setup the binning contiguity weights""" +class TestContiguityWeights: + def setup_method(self): + """Setup the binning contiguity weights""" shpObj = ps_open(pysal_examples.get_path("virginia.shp"), "r") self.binningW = ContiguityWeightsLists(shpObj, QUEEN) shpObj.close() def test_w_type(self): - self.assertTrue(isinstance(self.binningW, ContiguityWeightsLists)) + assert isinstance(self.binningW, ContiguityWeightsLists) - def test_QUEEN(self): - self.assertEqual(QUEEN, 1) + def test_queen(self): + assert QUEEN == 1 - def test_ROOK(self): - self.assertEqual(ROOK, 2) + def test_rook(self): + assert ROOK == 2 - def test_ContiguityWeightsLists(self): - self.assertTrue(hasattr(self.binningW, "w")) - self.assertTrue(issubclass(dict, type(self.binningW.w))) - self.assertEqual(len(self.binningW.w), 136) + def test_contiguity_weights_lists(self): + assert hasattr(self.binningW, "w") + assert issubclass(dict, type(self.binningW.w)) + assert len(self.binningW.w) == 136 def test_nested_polygons(self): # load queen gal file created using Open Geoda. @@ -48,7 +42,7 @@ def test_nested_polygons(self): pysalb_neighbors = pysalWb.neighbors[int(key)] geoda_neighbors.sort() pysalb_neighbors.sort() - self.assertEqual(geoda_neighbors, pysalb_neighbors) + assert geoda_neighbors == pysalb_neighbors def test_true_rook(self): # load queen gal file created using Open Geoda. @@ -62,7 +56,7 @@ def test_true_rook(self): pysalb_neighbors = pysalWb.neighbors[int(key)] geoda_neighbors.sort() pysalb_neighbors.sort() - self.assertEqual(geoda_neighbors, pysalb_neighbors) + assert geoda_neighbors == pysalb_neighbors def test_true_rook2(self): # load queen gal file created using Open Geoda. @@ -78,7 +72,7 @@ def test_true_rook2(self): pysalb_neighbors = pysalWb.neighbors[int(key)] geoda_neighbors.sort() pysalb_neighbors.sort() - self.assertEqual(geoda_neighbors, pysalb_neighbors) + assert geoda_neighbors == pysalb_neighbors def test_true_rook3(self): # load queen gal file created using Open Geoda. @@ -91,24 +85,23 @@ def test_true_rook3(self): pysalb_neighbors = pysalWb.neighbors[int(key)] geoda_neighbors.sort() pysalb_neighbors.sort() - self.assertEqual(geoda_neighbors, pysalb_neighbors) + assert geoda_neighbors == pysalb_neighbors - @unittest.skipIf(gpd is None, "geopandas is missing in the testing environment") def test_shapely(self): pysalneighbs = ContiguityWeightsLists( ps_open(pysal_examples.get_path("virginia.shp")), ROOK ) gdf = gpd.read_file(pysal_examples.get_path("virginia.shp")) shplyneighbs = ContiguityWeightsLists(gdf.geometry.tolist(), ROOK) - self.assertEqual(pysalneighbs.w, shplyneighbs.w) + assert pysalneighbs.w == shplyneighbs.w pysalneighbs = ContiguityWeightsLists( ps_open(pysal_examples.get_path("virginia.shp")), QUEEN ) shplyneighbs = ContiguityWeightsLists(gdf.geometry.tolist(), QUEEN) - self.assertEqual(pysalneighbs.w, shplyneighbs.w) + assert pysalneighbs.w == shplyneighbs.w def build_W(self, shapefile, type, idVariable=None): - """ Building 2 W's the hard way. We need to do this so we can test both rtree and binning """ + """Building 2 W's the hard way. We need to do this so we can test both rtree and binning""" dbname = os.path.splitext(shapefile)[0] + ".dbf" db = ps_open(dbname) shpObj = ps_open(shapefile) @@ -117,7 +110,7 @@ def build_W(self, shapefile, type, idVariable=None): weights = {} if idVariable: ids = db.by_col[idVariable] - self.assertEqual(len(ids), len(set(ids))) + assert len(ids) == len(set(ids)) for key in neighbor_data: id = ids[key] if id not in neighbors: @@ -130,11 +123,3 @@ def build_W(self, shapefile, type, idVariable=None): neighbors[key] = list(neighbors[key]) binningW = W(neighbors) return binningW - - -# suite = unittest.TestLoader().loadTestsFromTestCase(_TestContiguityWeights) - -if __name__ == "__main__": - # runner = unittest.TextTestRunner() - # runner.run(suite) - unittest.main() diff --git a/libpysal/weights/tests/test_adjlist.py b/libpysal/weights/tests/test_adjlist.py index 65dbf2e92..fff6e747b 100644 --- a/libpysal/weights/tests/test_adjlist.py +++ b/libpysal/weights/tests/test_adjlist.py @@ -1,25 +1,15 @@ -import unittest as ut +import geopandas import numpy as np +import pytest + +from ... import examples, io, weights +from ...common import ATOL, RTOL from .. import adjtools as adj -from ... import weights -from ... import io -from ... import examples from ..util import lat2W -from ...common import RTOL, ATOL - - -try: - import pandas - import geopandas - - PANDAS_MISSING = False -except ImportError: - PANDAS_MISSING = True -@ut.skipIf(PANDAS_MISSING, "Pandas is gone") -class Test_Adjlist(ut.TestCase): - def setUp(self): +class Test_Adjlist: + def setup_method(self): self.knownW = io.open(examples.get_path("columbus.gal")).read() def test_round_trip_drop_islands_true(self): @@ -44,7 +34,7 @@ def test_filter(self): grid = lat2W(2, 2) alist = grid.to_adjlist(remove_symmetric=True, drop_islands=True) assert len(alist) == 4 - with self.assertRaises(AssertionError): + with pytest.raises(AssertionError): # build this manually because of bug libpysal#322 alist_neighbors = alist.groupby("focal").neighbor.apply(list).to_dict() all_ids = set(alist_neighbors.keys()).union( @@ -60,7 +50,7 @@ def test_filter(self): grid = lat2W(2, 2, id_type="string") alist = grid.to_adjlist(remove_symmetric=True, drop_islands=True) assert len(alist) == 4 - with self.assertRaises(AssertionError): + with pytest.raises(AssertionError): # build this manually because of bug libpysal#322 alist_neighbors = alist.groupby("focal").neighbor.apply(list).to_dict() all_ids = set(alist_neighbors.keys()).union( @@ -192,4 +182,4 @@ def test_lat2w(self): w = lat2W(5, 5) manual_neighbors = w.to_adjlist().groupby("focal").neighbor.agg(list).to_dict() for focal, neighbors in w.neighbors.items(): - self.assertEqual(set(manual_neighbors[focal]), set(neighbors)) + assert set(manual_neighbors[focal]) == set(neighbors) diff --git a/libpysal/weights/tests/test_contiguity.py b/libpysal/weights/tests/test_contiguity.py index ea6b3877f..a390f1cb2 100644 --- a/libpysal/weights/tests/test_contiguity.py +++ b/libpysal/weights/tests/test_contiguity.py @@ -1,33 +1,14 @@ -from .. import contiguity as c -from ..weights import W -from .. import util -from .. import raster -from ...common import pandas -from ...io.fileio import FileIO as ps_open -from ...io import geotable as pdio - -from ... import examples as pysal_examples -import unittest as ut import numpy as np -import pytest - -PANDAS_EXTINCT = pandas is None -try: - import geopandas - - GEOPANDAS_EXTINCT = False -except ImportError: - GEOPANDAS_EXTINCT = True -try: - import shapely - - HAS_SHAPELY = True -except ImportError: - HAS_SHAPELY = False +from ... import examples as pysal_examples +from ...io import geotable as pdio +from ...io.fileio import FileIO as ps_open +from .. import contiguity as c +from .. import raster, util +from ..weights import W -class Contiguity_Mixin(object): +class ContiguityMixin: polygon_path = pysal_examples.get_path("columbus.shp") point_path = pysal_examples.get_path("baltim.shp") da = raster.testDataArray((1, 4, 4), missing_vals=False) @@ -45,22 +26,19 @@ class Contiguity_Mixin(object): known_wi_da = None known_w_da = dict() - def setUp(self): + def setup_method(self): self.__dict__.update( { k: v - for k, v in list(Contiguity_Mixin.__dict__.items()) + for k, v in list(ContiguityMixin.__dict__.items()) if not k.startswith("_") } ) - def runTest(self): - pass - def test_init(self): # basic w = self.cls(self.polygons) - self.assertEqual(w[self.known_wi], self.known_w) + assert w[self.known_wi] == self.known_w # sparse # w = self.cls(self.polygons, sparse=True) @@ -72,58 +50,55 @@ def test_init(self): # named ids = util.get_ids(self.polygon_path, self.idVariable) w = self.cls(self.polygons, ids=ids) - self.assertEqual(w[self.known_name], self.known_namedw) + assert w[self.known_name] == self.known_namedw def test_from_iterable(self): w = self.cls.from_iterable(self.f) self.f.seek(0) - self.assertEqual(w[self.known_wi], self.known_w) + assert w[self.known_wi] == self.known_w def test_from_shapefile(self): # basic w = self.cls.from_shapefile(self.polygon_path) - self.assertEqual(w[self.known_wi], self.known_w) + assert w[self.known_wi] == self.known_w # sparse ws = self.cls.from_shapefile(self.polygon_path, sparse=True) srowvec = ws.sparse[self.known_wi].todense().tolist()[0] this_w = {i: k for i, k in enumerate(srowvec) if k > 0} - self.assertEqual(this_w, self.known_w) + assert this_w == self.known_w # named w = self.cls.from_shapefile(self.polygon_path, idVariable=self.idVariable) - self.assertEqual(w[self.known_name], self.known_namedw) + assert w[self.known_name] == self.known_namedw def test_from_array(self): # test named, sparse from point array pass - @ut.skipIf(PANDAS_EXTINCT, "Missing pandas") def test_from_dataframe(self): # basic df = pdio.read_files(self.polygon_path) w = self.cls.from_dataframe(df) - self.assertEqual(w[self.known_wi], self.known_w) + assert w[self.known_wi] == self.known_w # named geometry df.rename(columns={"geometry": "the_geom"}, inplace=True) w = self.cls.from_dataframe(df, geom_col="the_geom") - self.assertEqual(w[self.known_wi], self.known_w) + assert w[self.known_wi] == self.known_w - @ut.skipIf(GEOPANDAS_EXTINCT, "Missing geopandas") def test_from_geodataframe(self): df = pdio.read_files(self.polygon_path) # named active geometry df.rename(columns={"geometry": "the_geom"}, inplace=True) df = df.set_geometry("the_geom") w = self.cls.from_dataframe(df) - self.assertEqual(w[self.known_wi], self.known_w) + assert w[self.known_wi] == self.known_w # named geometry + named obs w = self.cls.from_dataframe(df, geom_col="the_geom", ids=self.idVariable) - self.assertEqual(w[self.known_name], self.known_namedw) + assert w[self.known_name] == self.known_namedw - @ut.skipIf(GEOPANDAS_EXTINCT, "Missing geopandas") def test_from_geodataframe_order(self): import geopandas @@ -131,20 +106,20 @@ def test_from_geodataframe_order(self): expected = south.FIPS.iloc[:5].tolist() for ids_ in ("FIPS", south.FIPS): w = self.cls.from_dataframe(south, ids=ids_) - self.assertEqual(w.id_order[:5], expected) + assert w.id_order[:5] == expected def test_from_xarray(self): w = self.cls.from_xarray(self.da, sparse=False, n_jobs=-1) - self.assertEqual(w[self.known_wi_da], self.known_w_da) + assert w[self.known_wi_da] == self.known_w_da ws = self.cls.from_xarray(self.da) srowvec = ws.sparse[self.known_wspi_da].todense().tolist()[0] this_w = {i: k for i, k in enumerate(srowvec) if k > 0} - self.assertEqual(this_w, self.known_wsp_da) + assert this_w == self.known_wsp_da -class Test_Queen(ut.TestCase, Contiguity_Mixin): - def setUp(self): - Contiguity_Mixin.setUp(self) +class TestQueen(ContiguityMixin): + def setup_method(self): + ContiguityMixin.setup_method(self) self.known_wi = 4 self.known_w = { @@ -175,7 +150,6 @@ def setUp(self): (1, 30.0, 60.0): 1, } - @ut.skipIf(GEOPANDAS_EXTINCT, "Missing Geopandas") def test_linestrings(self): import geopandas @@ -197,9 +171,9 @@ def test_linestrings(self): np.testing.assert_array_equal(eberly_w, computed) -class Test_Rook(ut.TestCase, Contiguity_Mixin): - def setUp(self): - Contiguity_Mixin.setUp(self) +class TestRook(ContiguityMixin): + def setup_method(self): + ContiguityMixin.setup_method(self) self.known_w = {2: 1.0, 3: 1.0, 5: 1.0, 7: 1.0, 8: 1.0, 10: 1.0, 14: 1.0} self.known_wi = 4 @@ -217,21 +191,16 @@ def setUp(self): } -class Test_Voronoi(ut.TestCase): - @pytest.mark.skipif(not HAS_SHAPELY, reason="shapely needed") - def test_voronoiW(self): +class TestVoronoi: + def test_voronoi_w(self): np.random.seed(12345) points = np.random.random((5, 2)) * 10 + 10 w = c.Voronoi(points) - self.assertEqual(w.n, 5) - self.assertEqual( - w.neighbors, {0: [2, 3, 4], 1: [2], 2: [0, 1, 4], 3: [0, 4], 4: [0, 2, 3]} - ) - - -q = ut.TestLoader().loadTestsFromTestCase(Test_Queen) -r = ut.TestLoader().loadTestsFromTestCase(Test_Rook) -suite = ut.TestSuite([q, r]) -if __name__ == "__main__": - runner = ut.TextTestRunner() - runner.run(suite) + assert w.n == 5 + assert w.neighbors == { + 0: [2, 3, 4], + 1: [2], + 2: [0, 1, 4], + 3: [0, 4], + 4: [0, 2, 3], + } diff --git a/libpysal/weights/tests/test_distance.py b/libpysal/weights/tests/test_distance.py index 5f2043baa..5b088f24f 100644 --- a/libpysal/weights/tests/test_distance.py +++ b/libpysal/weights/tests/test_distance.py @@ -1,28 +1,21 @@ -from ...common import RTOL, ATOL, pandas -from ...cg.kdtree import KDTree, RADIUS_EARTH_KM -from ..util import get_points_array -from ... import cg -from ... import weights -from .. import raster -from .. import distance as d, contiguity as c -from ...io import geotable as pdio -from ...io.fileio import FileIO as psopen import numpy as np -from ... import examples as pysal_examples -import unittest as ut -PANDAS_EXTINCT = pandas is None -try: - import geopandas +from ... import cg, weights +from ... import examples as pysal_examples +from ...cg.kdtree import RADIUS_EARTH_KM, KDTree +from ...common import ATOL, RTOL, pandas +from ...io import geotable as pdio +from ...io.fileio import FileIO as psopen +from .. import contiguity as c +from .. import distance as d +from .. import raster +from ..util import get_points_array - GEOPANDAS_EXTINCT = False -except ImportError: - GEOPANDAS_EXTINCT = True # All instances should test these four methods, and define their own functional # tests based on common codepaths/estimated weights use cases. -class Distance_Mixin(object): +class DistanceMixin: polygon_path = pysal_examples.get_path("columbus.shp") arc_path = pysal_examples.get_path("stl_hom.shp") points = [(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)] @@ -44,11 +37,11 @@ class Distance_Mixin(object): known_w = dict() # actual w entry known_name = known_wi - def setUp(self): + def setup_method(self): self.__dict__.update( { k: v - for k, v in list(Distance_Mixin.__dict__.items()) + for k, v in list(DistanceMixin.__dict__.items()) if not k.startswith("_") } ) @@ -78,9 +71,9 @@ def test_from_dataframe(self): ) -class Test_KNN(ut.TestCase, Distance_Mixin): - def setUp(self): - Distance_Mixin.setUp(self) +class TestKNN(DistanceMixin): + def setup_method(self): + DistanceMixin.setup_method(self) self.known_wi0 = 7 self.known_w0 = [3, 6, 12, 11] @@ -98,40 +91,38 @@ def setUp(self): def test_init(self): w = d.KNN(self.euclidean_kdt, k=2) - self.assertEqual(w.neighbors[0], [1, 3]) + assert w.neighbors[0] == [1, 3] - @ut.skipIf(PANDAS_EXTINCT, "Missing pandas") def test_from_dataframe(self): df = pdio.read_files(self.polygon_path) w = d.KNN.from_dataframe(df, k=4) - self.assertEqual(w.neighbors[self.known_wi0], self.known_w0) - self.assertEqual(w.neighbors[self.known_wi1], self.known_w1) + assert w.neighbors[self.known_wi0] == self.known_w0 + assert w.neighbors[self.known_wi1] == self.known_w1 # named geometry df.rename(columns={"geometry": "the_geom"}, inplace=True) w = d.KNN.from_dataframe(df, k=4, geom_col="the_geom") - self.assertEqual(w.neighbors[self.known_wi0], self.known_w0) - self.assertEqual(w.neighbors[self.known_wi1], self.known_w1) + assert w.neighbors[self.known_wi0] == self.known_w0 + assert w.neighbors[self.known_wi1] == self.known_w1 - @ut.skipIf(GEOPANDAS_EXTINCT, "Missing geopandas") def test_from_geodataframe(self): df = pdio.read_files(self.polygon_path) # named active geometry df.rename(columns={"geometry": "the_geom"}, inplace=True) df = df.set_geometry("the_geom") w = d.KNN.from_dataframe(df, k=4) - self.assertEqual(w.neighbors[self.known_wi0], self.known_w0) - self.assertEqual(w.neighbors[self.known_wi1], self.known_w1) + assert w.neighbors[self.known_wi0] == self.known_w0 + assert w.neighbors[self.known_wi1] == self.known_w1 def test_from_array(self): w = d.KNN.from_array(self.poly_centroids, k=4) - self.assertEqual(w.neighbors[self.known_wi0], self.known_w0) - self.assertEqual(w.neighbors[self.known_wi1], self.known_w1) + assert w.neighbors[self.known_wi0] == self.known_w0 + assert w.neighbors[self.known_wi1] == self.known_w1 def test_from_shapefile(self): w = d.KNN.from_shapefile(self.polygon_path, k=4) - self.assertEqual(w.neighbors[self.known_wi0], self.known_w0) - self.assertEqual(w.neighbors[self.known_wi1], self.known_w1) + assert w.neighbors[self.known_wi0] == self.known_w0 + assert w.neighbors[self.known_wi1] == self.known_w1 ########################## # Function/User tests # @@ -141,7 +132,7 @@ def test_reweight(self): w = d.KNN(self.points, k=2) new_point = [(21, 21)] wnew = w.reweight(k=4, p=1, new_data=new_point, inplace=False) - self.assertEqual(wnew[0], {1: 1.0, 3: 1.0, 4: 1.0, 6: 1.0}) + assert wnew[0] == {1: 1.0, 3: 1.0, 4: 1.0, 6: 1.0} def test_arcdata(self): w = d.KNN.from_shapefile( @@ -150,12 +141,12 @@ def test_arcdata(self): distance_metric="Arc", radius=cg.sphere.RADIUS_EARTH_KM, ) - self.assertEqual(w.data.shape[1], 3) + assert w.data.shape[1] == 3 -class Test_DistanceBand(ut.TestCase, Distance_Mixin): - def setUp(self): - Distance_Mixin.setUp(self) +class TestDistanceBand(DistanceMixin): + def setup_method(self): + DistanceMixin.setup_method(self) self.grid_path = pysal_examples.get_path("lattice10x10.shp") self.grid_rook_w = c.Rook.from_shapefile(self.grid_path) self.grid_f = psopen(self.grid_path) @@ -171,19 +162,18 @@ def setUp(self): def test_init(self): w = d.DistanceBand(self.grid_kdt, 1) for k, v in w: - self.assertEqual(v, self.grid_rook_w[k]) + assert v == self.grid_rook_w[k] def test_from_shapefile(self): w = d.DistanceBand.from_shapefile(self.grid_path, 1) for k, v in w: - self.assertEqual(v, self.grid_rook_w[k]) + assert v == self.grid_rook_w[k] def test_from_array(self): w = d.DistanceBand.from_array(self.grid_points, 1) for k, v in w: - self.assertEqual(v, self.grid_rook_w[k]) + assert v == self.grid_rook_w[k] - @ut.skipIf(PANDAS_EXTINCT, "Missing pandas") def test_from_dataframe(self): import pandas as pd @@ -192,9 +182,8 @@ def test_from_dataframe(self): df = pd.DataFrame({"obs": random_data, "geometry": geom_series}) w = d.DistanceBand.from_dataframe(df, 1) for k, v in w: - self.assertEqual(v, self.grid_rook_w[k]) + assert v == self.grid_rook_w[k] - @ut.skipIf(GEOPANDAS_EXTINCT, "Missing geopandas") def test_from_geodataframe(self): import geopandas as gpd import pandas as pd @@ -204,19 +193,19 @@ def test_from_geodataframe(self): df = pd.DataFrame({"obs": random_data, "geometry": geom_series}) w = d.DistanceBand.from_dataframe(df, 1) for k, v in w: - self.assertEqual(v, self.grid_rook_w[k]) + assert v == self.grid_rook_w[k] # named geometry df = gpd.GeoDataFrame(df) df.rename(columns={"geometry": "the_geom"}, inplace=True) w = d.DistanceBand.from_dataframe(df, 1, geom_col="the_geom") for k, v in w: - self.assertEqual(v, self.grid_rook_w[k]) + assert v == self.grid_rook_w[k] # named active geometry df = df.set_geometry("the_geom") w = d.DistanceBand.from_dataframe(df, 1) for k, v in w: - self.assertEqual(v, self.grid_rook_w[k]) + assert v == self.grid_rook_w[k] ########################## # Function/User tests # @@ -229,7 +218,7 @@ def test_integers(self): self.grid_f.seek(0) grid_dbw = d.DistanceBand(grid_integers, 1) for k, v in grid_dbw: - self.assertEqual(v, self.grid_rook_w[k]) + assert v == self.grid_rook_w[k] def test_arcdist(self): arc = cg.sphere.arcdist @@ -246,7 +235,7 @@ def test_arcdist(self): maxdist = full.max() w = d.DistanceBand(kdt, maxdist, binary=False, alpha=1.0) np.testing.assert_allclose(w.sparse.todense(), full) - self.assertEqual(w.data.shape[1], 3) + assert w.data.shape[1] == 3 def test_dense(self): w_rook = c.Rook.from_shapefile(pysal_examples.get_path("lattice10x10.shp")) @@ -257,7 +246,6 @@ def test_dense(self): for k in w_db.id_order: np.testing.assert_equal(w_db[k], w_rook[k]) - @ut.skipIf(PANDAS_EXTINCT, "Missing pandas") def test_named(self): import pandas as pd @@ -268,10 +256,9 @@ def test_named(self): w = d.DistanceBand.from_dataframe(df, 1, ids=df.names) -class Test_Kernel(ut.TestCase, Distance_Mixin): - def setUp(self): - - Distance_Mixin.setUp(self) +class TestKernel(DistanceMixin): + def setup_method(self): + DistanceMixin.setup_method(self) self.known_wi0 = 0 self.known_w0 = {0: 1, 1: 0.500000049999995, 3: 0.4409830615267465} @@ -342,14 +329,12 @@ def test_from_array(self): for k, v in list(w[self.known_wi0].items()): np.testing.assert_allclose(v, self.known_w0[k], rtol=RTOL) - @ut.skipIf(PANDAS_EXTINCT, "Missing pandas") def test_from_dataframe(self): df = pdio.read_files(self.polygon_path) w = d.Kernel.from_dataframe(df) for k, v in list(w[self.known_wi5 - 1].items()): np.testing.assert_allclose(v, self.known_w5[k + 1], rtol=RTOL) - @ut.skipIf(GEOPANDAS_EXTINCT, "Missing geopandas") def test_from_geodataframe(self): df = pdio.read_files(self.polygon_path) # named geometry @@ -401,13 +386,4 @@ def test_arcdistance(self): distance_metric="Arc", radius=cg.sphere.RADIUS_EARTH_KM, ) - self.assertEqual(w.data.shape[1], 3) - - -knn = ut.TestLoader().loadTestsFromTestCase(Test_KNN) -kern = ut.TestLoader().loadTestsFromTestCase(Test_Kernel) -db = ut.TestLoader().loadTestsFromTestCase(Test_DistanceBand) -suite = ut.TestSuite([knn, kern, db]) -if __name__ == "__main__": - runner = ut.TextTestRunner() - runner.run(suite) + assert w.data.shape[1] == 3 diff --git a/libpysal/weights/tests/test_gabriel.py b/libpysal/weights/tests/test_gabriel.py index 6b331edf6..9dcbc5de9 100644 --- a/libpysal/weights/tests/test_gabriel.py +++ b/libpysal/weights/tests/test_gabriel.py @@ -1,9 +1,8 @@ -from .. import gabriel -from ... import examples +import geopandas import numpy -import pytest -geopandas = pytest.importorskip("geopandas") +from ... import examples +from .. import gabriel path = examples.get_path("columbus.shp") df = geopandas.read_file(path) @@ -32,6 +31,7 @@ def test_gabriel(): dneighbors = c2[focal] assert set(neighbors) <= set(dneighbors) + def test_rng(): e = gabriel.Relative_Neighborhood(coords) f = gabriel.Relative_Neighborhood.from_dataframe(df.centroid) @@ -40,7 +40,7 @@ def test_rng(): assert e.neighbors == f.neighbors assert e[1] != dty[1] - assert list(e[1].keys()) == [0,3,6,30,38] + assert list(e[1].keys()) == [0, 3, 6, 30, 38] for focal, neighbors in e.neighbors.items(): dneighbors = dty[focal] assert set(neighbors) <= set(dneighbors) diff --git a/libpysal/weights/tests/test_nx.py b/libpysal/weights/tests/test_nx.py index 13d605275..d8f01eb81 100644 --- a/libpysal/weights/tests/test_nx.py +++ b/libpysal/weights/tests/test_nx.py @@ -1,32 +1,26 @@ -import unittest as ut import numpy as np -import scipy as sp -from packaging.version import Version +import pytest + from ..util import lat2W from ..weights import W -try: - import networkx as nx -except ImportError: - nx = None +networkx = pytest.importorskip("networkx") -SP_18 = Version(sp.__version__) >= Version('1.8') -@ut.skipIf((nx is None) or (not SP_18), "Missing networkx or old scipy") -class Test_NetworkXConverter(ut.TestCase): - def setUp(self): - self.known_nx = nx.random_regular_graph(4, 10, seed=8879) - self.known_amat = nx.to_numpy_array(self.known_nx) +class TestNetworkXConverter: + def setup_method(self): + self.known_nx = networkx.random_regular_graph(4, 10, seed=8879) + self.known_amat = networkx.to_numpy_array(self.known_nx) self.known_W = lat2W(5, 5) def test_round_trip(self): W_ = W.from_networkx(self.known_nx) np.testing.assert_allclose(W_.sparse.toarray(), self.known_amat) nx2 = W_.to_networkx() - np.testing.assert_allclose(nx.to_numpy_array(nx2), self.known_amat) + np.testing.assert_allclose(networkx.to_numpy_array(nx2), self.known_amat) nxsquare = self.known_W.to_networkx() np.testing.assert_allclose( - self.known_W.sparse.toarray(), nx.to_numpy_array(nxsquare) + self.known_W.sparse.toarray(), networkx.to_numpy_array(nxsquare) ) W_square = W.from_networkx(nxsquare) np.testing.assert_allclose( diff --git a/libpysal/weights/tests/test_raster.py b/libpysal/weights/tests/test_raster.py index f694b1deb..51685e075 100644 --- a/libpysal/weights/tests/test_raster.py +++ b/libpysal/weights/tests/test_raster.py @@ -1,101 +1,93 @@ """Unit test for raster.py""" -from .. import raster -import unittest import numpy as np import pandas as pd +import pytest from xarray import DataArray +from .. import raster + -class Testraster(unittest.TestCase): - def setUp(self): +class Testraster: + def setup_method(self): self.da1 = raster.testDataArray() self.da2 = raster.testDataArray((1, 4, 4), missing_vals=False) - self.da3 = self.da2.rename( - {"band": "layer", "x": "longitude", "y": "latitude"}) + self.da3 = self.da2.rename({"band": "layer", "x": "longitude", "y": "latitude"}) self.data1 = pd.Series(np.ones(5)) self.da4 = raster.testDataArray((1, 1), missing_vals=False) self.da4.data = np.array([["test"]]) - def test_da2W(self): + def test_da2_w(self): w1 = raster.da2W(self.da1, "queen", k=2, n_jobs=-1) - self.assertEqual(w1[(1, -30.0, -180.0)], - {(1, -90.0, 60.0): 1, (1, -90.0, -60.0): 1}) - self.assertEqual(w1[(1, -30.0, 180.0)], - {(1, -90.0, -60.0): 1, (1, -90.0, 60.0): 1}) - self.assertEqual(w1.n, 5) - self.assertEqual(w1.index.names, self.da1.to_series().index.names) - self.assertEqual(w1.index.tolist()[0], (1, 90.0, 180.0)) - self.assertEqual(w1.index.tolist()[1], (1, -30.0, -180.0)) - self.assertEqual(w1.index.tolist()[2], (1, -30.0, 180.0)) - self.assertEqual(w1.index.tolist()[3], (1, -90.0, -60.0)) + assert w1[(1, -30.0, -180.0)] == {(1, -90.0, 60.0): 1, (1, -90.0, -60.0): 1} + assert w1[(1, -30.0, 180.0)] == {(1, -90.0, -60.0): 1, (1, -90.0, 60.0): 1} + assert w1.n == 5 + assert w1.index.names == self.da1.to_series().index.names + assert w1.index.tolist()[0] == (1, 90.0, 180.0) + assert w1.index.tolist()[1] == (1, -30.0, -180.0) + assert w1.index.tolist()[2] == (1, -30.0, 180.0) + assert w1.index.tolist()[3] == (1, -90.0, -60.0) w2 = raster.da2W(self.da2, "rook") - self.assertEqual( - sorted(w2.neighbors[(1, -90.0, 180.0)]), [(1, -90.0, 60.0), (1, -30.0, 180.0)]) - self.assertEqual(sorted(w2.neighbors[( - 1, -90.0, 60.0)]), [(1, -90.0, -60.0), (1, -90.0, 180.0), (1, -30.0, 60.0)]) - self.assertEqual(w2.n, 16) - self.assertEqual(w2.index.names, self.da2.to_series().index.names) - self.assertEqual(w2.index.tolist(), - self.da2.to_series().index.tolist()) + assert sorted(w2.neighbors[(1, -90.0, 180.0)]) == [ + (1, -90.0, 60.0), + (1, -30.0, 180.0), + ] + assert sorted(w2.neighbors[(1, -90.0, 60.0)]) == [ + (1, -90.0, -60.0), + (1, -90.0, 180.0), + (1, -30.0, 60.0), + ] + assert w2.n == 16 + assert w2.index.names == self.da2.to_series().index.names + assert w2.index.tolist() == self.da2.to_series().index.tolist() coords_labels = { "z_label": "layer", "y_label": "latitude", "x_label": "longitude", } w3 = raster.da2W(self.da3, z_value=1, coords_labels=coords_labels) - self.assertEqual(sorted(w3.neighbors[( - 1, -90.0, 180.0)]), [(1, -90.0, 60.0), (1, -30.0, 60.0), (1, -30.0, 180.0)]) - self.assertEqual(w3.n, 16) - self.assertEqual(w3.index.names, self.da3.to_series().index.names) - self.assertEqual(w3.index.tolist(), - self.da3.to_series().index.tolist()) + assert sorted(w3.neighbors[(1, -90.0, 180.0)]) == [ + (1, -90.0, 60.0), + (1, -30.0, 60.0), + (1, -30.0, 180.0), + ] + assert w3.n == 16 + assert w3.index.names == self.da3.to_series().index.names + assert w3.index.tolist() == self.da3.to_series().index.tolist() - def test_da2WSP(self): + def test_da2_wsp(self): w1 = raster.da2WSP(self.da1, "rook", n_jobs=-1) rows, cols = w1.sparse.shape n = rows * cols pct_nonzero = w1.sparse.nnz / float(n) - self.assertEqual(pct_nonzero, 0.08) + assert pct_nonzero == 0.08 data = w1.sparse.todense().tolist() - self.assertEqual(data[3], [0, 0, 0, 0, 1]) - self.assertEqual(data[4], [0, 0, 0, 1, 0]) - self.assertEqual(w1.index.names, self.da1.to_series().index.names) - self.assertEqual(w1.index.tolist()[0], (1, 90.0, 180.0)) - self.assertEqual(w1.index.tolist()[1], (1, -30.0, -180.0)) - self.assertEqual(w1.index.tolist()[2], (1, -30.0, 180.0)) - self.assertEqual(w1.index.tolist()[3], (1, -90.0, -60.0)) + assert data[3] == [0, 0, 0, 0, 1] + assert data[4] == [0, 0, 0, 1, 0] + assert w1.index.names == self.da1.to_series().index.names + assert w1.index.tolist()[0] == (1, 90.0, 180.0) + assert w1.index.tolist()[1] == (1, -30.0, -180.0) + assert w1.index.tolist()[2] == (1, -30.0, 180.0) + assert w1.index.tolist()[3] == (1, -90.0, -60.0) w2 = raster.da2WSP(self.da2, "queen", k=2, include_nodata=True) w3 = raster.da2WSP(self.da2, "queen", k=2, n_jobs=-1) - self.assertEqual(w2.sparse.nnz, w3.sparse.nnz) - self.assertEqual(w2.sparse.todense().tolist(), - w3.sparse.todense().tolist()) - self.assertEqual(w2.n, 16) - self.assertEqual(w2.index.names, self.da2.to_series().index.names) - self.assertEqual(w2.index.tolist(), - self.da2.to_series().index.tolist()) + assert w2.sparse.nnz == w3.sparse.nnz + assert w2.sparse.todense().tolist() == w3.sparse.todense().tolist() + assert w2.n == 16 + assert w2.index.names == self.da2.to_series().index.names + assert w2.index.tolist() == self.da2.to_series().index.tolist() def test_w2da(self): w2 = raster.da2W(self.da2, "rook", n_jobs=-1) - da2 = raster.w2da(self.da2.data.flatten(), w2, - self.da2.attrs, self.da2.coords) + da2 = raster.w2da(self.da2.data.flatten(), w2, self.da2.attrs, self.da2.coords) da_compare = DataArray.equals(da2, self.da2) - self.assertEqual(da_compare, True) + assert da_compare == True def test_wsp2da(self): wsp1 = raster.da2WSP(self.da1, "queen") da1 = raster.wsp2da(self.data1, wsp1) - self.assertEqual(da1["y"].values.tolist(), - self.da1["y"].values.tolist()) - self.assertEqual(da1["x"].values.tolist(), - self.da1["x"].values.tolist()) - self.assertEqual(da1.shape, (1, 4, 4)) + assert da1["y"].values.tolist() == self.da1["y"].values.tolist() + assert da1["x"].values.tolist() == self.da1["x"].values.tolist() + assert da1.shape == (1, 4, 4) def test_da_checker(self): - self.assertRaises(ValueError, raster.da2W, self.da4) - - -suite = unittest.TestLoader().loadTestsFromTestCase(Testraster) - -if __name__ == "__main__": - runner = unittest.TextTestRunner() - runner.run(suite) + pytest.raises(ValueError, raster.da2W, self.da4) diff --git a/libpysal/weights/tests/test_spatial_lag.py b/libpysal/weights/tests/test_spatial_lag.py index 39e9a3342..36a3945e4 100644 --- a/libpysal/weights/tests/test_spatial_lag.py +++ b/libpysal/weights/tests/test_spatial_lag.py @@ -1,13 +1,12 @@ -import os -import unittest -from ..weights import W -from ..util import lat2W -from ..spatial_lag import lag_spatial, lag_categorical import numpy as np +from ..spatial_lag import lag_categorical, lag_spatial +from ..util import lat2W +from ..weights import W + -class Test_spatial_lag(unittest.TestCase): - def setUp(self): +class Test_spatial_lag: + def setup_method(self): self.neighbors = {"c": ["b"], "b": ["c", "a"], "a": ["b"]} self.weights = {"c": [1.0], "b": [1.0, 1.0], "a": [1.0]} self.id_order = ["a", "b", "c"] @@ -57,10 +56,3 @@ def test_lag_categorical(self): ] ) np.testing.assert_array_equal(ym_lag, np.asarray(known)) - - -suite = unittest.TestLoader().loadTestsFromTestCase(Test_spatial_lag) - -if __name__ == "__main__": - runner = unittest.TextTestRunner() - runner.run(suite) diff --git a/libpysal/weights/tests/test_spintW.py b/libpysal/weights/tests/test_spintW.py index 15b6b6660..5a4828000 100644 --- a/libpysal/weights/tests/test_spintW.py +++ b/libpysal/weights/tests/test_spintW.py @@ -1,11 +1,11 @@ -import unittest import numpy as np -from ..spintW import ODW, netW, mat2L, vecW + +from ..spintW import ODW, mat2L, netW, vecW from ..util import lat2W -class TestODWeights(unittest.TestCase): - def setUp(self): +class TestODWeights: + def setup_method(self): self.O = lat2W(2, 2) self.D = lat2W(2, 2) self.ODW = np.array( @@ -301,13 +301,13 @@ def setUp(self): ] ) - def test_ODW_full(self): + def test_odw_full(self): W = ODW(self.O, self.D) np.testing.assert_allclose(self.ODW, W.full()[0]) -class TestNetW(unittest.TestCase): - def setUp(self): +class TestNetW: + def setup_method(self): self.link_list = [ ("a", "b"), ("a", "c"), @@ -410,19 +410,19 @@ def setUp(self): self.edge_list = [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] - def test_netOD(self): + def test_net_od(self): netW_OD = netW(self.link_list, share="OD") np.testing.assert_allclose(netW_OD.full()[0], self.OD) - def test_netO(self): + def test_net_o(self): netW_O = netW(self.link_list, share="O") np.testing.assert_allclose(netW_O.full()[0], self.O) - def test_netD(self): + def test_net_d(self): netW_D = netW(self.link_list, share="D") np.testing.assert_allclose(netW_D.full()[0], self.D) - def test_netC(self): + def test_net_c(self): netW_C = netW(self.link_list, share="C") np.testing.assert_allclose(netW_C.full()[0], self.C) @@ -430,14 +430,14 @@ def test_net_all(self): netW_all = netW(self.link_list, share="A") np.testing.assert_allclose(netW_all.full()[0], self._all) - def test_mat2L(self): + def test_mat2_l(self): mat = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) edge_list = mat2L(mat) - self.assertEqual(edge_list, self.edge_list) + assert edge_list == self.edge_list -class TestVecW(unittest.TestCase): - def setUp(self): +class TestVecW: + def setup_method(self): self.origin_x = np.array([2, 6, 9, 2]) self.origin_y = np.array([4, 8, 2, 5]) self.dest_x = np.array([9, 1, 6, 3]) @@ -451,7 +451,7 @@ def setUp(self): ] ) - def test_vecW(self): + def test_vec_w(self): W = vecW( self.origin_x, self.origin_y, diff --git a/libpysal/weights/tests/test_user.py b/libpysal/weights/tests/test_user.py index 4a840030c..6e04be9eb 100644 --- a/libpysal/weights/tests/test_user.py +++ b/libpysal/weights/tests/test_user.py @@ -1,29 +1,23 @@ import os -import unittest -import numpy as np -from ..contiguity import Rook, Voronoi -from .. import user + +import pytest + from ... import examples +from .. import user +from ..contiguity import Rook, Voronoi -class Testuser(unittest.TestCase): +class Testuser: def test_min_threshold_dist_from_shapefile(self): f = examples.get_path("columbus.shp") min_d = user.min_threshold_dist_from_shapefile(f) - self.assertAlmostEqual(min_d, 0.61886415807685413) + assert min_d == pytest.approx(0.61886415807685413) def test_build_lattice_shapefile(self): of = "lattice.shp" user.build_lattice_shapefile(20, 20, of) w = Rook.from_shapefile(of) - self.assertEqual(w.n, 400) + assert w.n == 400 os.remove("lattice.dbf") os.remove("lattice.shp") os.remove("lattice.shx") - - -suite = unittest.TestLoader().loadTestsFromTestCase(Testuser) - -if __name__ == "__main__": - runner = unittest.TextTestRunner() - runner.run(suite) diff --git a/libpysal/weights/tests/test_util.py b/libpysal/weights/tests/test_util.py index 0c0e4dee5..74e4135dd 100644 --- a/libpysal/weights/tests/test_util.py +++ b/libpysal/weights/tests/test_util.py @@ -1,53 +1,46 @@ """Unit test for util.py""" -from ..util import lat2W, nonplanar_neighbors, fuzzy_contiguity -from .. import util -from ..weights import W, WSP -from ..distance import DistanceBand, KNN -from ..contiguity import Queen, Rook -from ...io.fileio import FileIO as psopen -from ... import examples +import geopandas as gpd import numpy as np -import scipy -import unittest - +import pytest -try: - import geopandas as gpd - - HAS_GEOPANDAS = True -except: - HAS_GEOPANDAS = False +from ... import examples +from ...io.fileio import FileIO as psopen +from .. import util +from ..contiguity import Queen, Rook +from ..distance import KNN, DistanceBand +from ..util import fuzzy_contiguity, lat2W, nonplanar_neighbors +from ..weights import WSP, W -class Testutil(unittest.TestCase): - def setUp(self): +class Testutil: + def setup_method(self): self.w = Rook.from_shapefile(examples.get_path("10740.shp")) self.rio = examples.load_example("Rio Grande do Sul") - def test_lat2W(self): + def test_lat2_w(self): w9 = lat2W(3, 3) - self.assertEqual(w9.pct_nonzero, 29.62962962962963) - self.assertEqual(w9[0], {1: 1.0, 3: 1.0}) - self.assertEqual(w9[3], {0: 1.0, 4: 1.0, 6: 1.0}) + assert w9.pct_nonzero == 29.62962962962963 + assert w9[0] == {1: 1.0, 3: 1.0} + assert w9[3] == {0: 1.0, 4: 1.0, 6: 1.0} - def test_lat2SW(self): + def test_lat2_sw(self): w9 = util.lat2SW(3, 3) rows, cols = w9.shape n = rows * cols - self.assertEqual(w9.nnz, 24) + assert w9.nnz == 24 pct_nonzero = w9.nnz / float(n) - self.assertEqual(pct_nonzero, 0.29629629629629628) + assert pct_nonzero == 0.29629629629629628 data = w9.todense().tolist() - self.assertEqual(data[0], [0, 1, 0, 1, 0, 0, 0, 0, 0]) - self.assertEqual(data[1], [1, 0, 1, 0, 1, 0, 0, 0, 0]) - self.assertEqual(data[2], [0, 1, 0, 0, 0, 1, 0, 0, 0]) - self.assertEqual(data[3], [1, 0, 0, 0, 1, 0, 1, 0, 0]) - self.assertEqual(data[4], [0, 1, 0, 1, 0, 1, 0, 1, 0]) - self.assertEqual(data[5], [0, 0, 1, 0, 1, 0, 0, 0, 1]) - self.assertEqual(data[6], [0, 0, 0, 1, 0, 0, 0, 1, 0]) - self.assertEqual(data[7], [0, 0, 0, 0, 1, 0, 1, 0, 1]) - self.assertEqual(data[8], [0, 0, 0, 0, 0, 1, 0, 1, 0]) + assert data[0] == [0, 1, 0, 1, 0, 0, 0, 0, 0] + assert data[1] == [1, 0, 1, 0, 1, 0, 0, 0, 0] + assert data[2] == [0, 1, 0, 0, 0, 1, 0, 0, 0] + assert data[3] == [1, 0, 0, 0, 1, 0, 1, 0, 0] + assert data[4] == [0, 1, 0, 1, 0, 1, 0, 1, 0] + assert data[5] == [0, 0, 1, 0, 1, 0, 0, 0, 1] + assert data[6] == [0, 0, 0, 1, 0, 0, 0, 1, 0] + assert data[7] == [0, 0, 0, 0, 1, 0, 1, 0, 1] + assert data[8] == [0, 0, 0, 0, 0, 1, 0, 1, 0] def test_block_weights(self): regimes = np.ones(25) @@ -84,9 +77,9 @@ def test_block_weights(self): ) w = util.block_weights(regimes) ww0 = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] - self.assertEqual(w.weights[0], ww0) + assert w.weights[0] == ww0 wn0 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 20] - self.assertEqual(w.neighbors[0], wn0) + assert w.neighbors[0] == wn0 regimes = ["n", "n", "s", "s", "e", "e", "w", "w", "e"] w = util.block_weights(regimes) wn = { @@ -100,14 +93,14 @@ def test_block_weights(self): 7: [6], 8: [4, 5], } - self.assertEqual(w.neighbors, wn) + assert w.neighbors == wn ids = ["id-%i" % i for i in range(len(regimes))] w = util.block_weights(regimes, ids=np.array(ids)) w0 = {"id-1": 1.0} - self.assertEqual(w["id-0"], w0) + assert w["id-0"] == w0 w = util.block_weights(regimes, ids=ids) w0 = {"id-1": 1.0} - self.assertEqual(w["id-0"], w0) + assert w["id-0"] == w0 def test_comb(self): x = list(range(4)) @@ -115,32 +108,32 @@ def test_comb(self): for i in util.comb(x, 2): l.append(i) lo = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]] - self.assertEqual(l, lo) + assert l == lo def test_order(self): w3 = util.order(self.w, kmax=3) w3105 = [1, -1, 1, 2, 1] - self.assertEqual(w3105, w3[1][0:5]) + assert w3105 == w3[1][0:5] def test_higher_order(self): w10 = lat2W(10, 10) w10_2 = util.higher_order(w10, 2) w10_20 = {2: 1.0, 11: 1.0, 20: 1.0} - self.assertEqual(w10_20, w10_2[0]) + assert w10_20 == w10_2[0] w5 = lat2W() w50 = {1: 1.0, 5: 1.0} - self.assertEqual(w50, w5[0]) + assert w50 == w5[0] w51 = {0: 1.0, 2: 1.0, 6: 1.0} - self.assertEqual(w51, w5[1]) + assert w51 == w5[1] w5_2 = util.higher_order(w5, 2) w5_20 = {2: 1.0, 10: 1.0, 6: 1.0} - self.assertEqual(w5_20, w5_2[0]) + assert w5_20 == w5_2[0] def test_higher_order_sp(self): w10 = lat2W(10, 10) w10_3 = util.higher_order_sp(w10, 3) w10_30 = {30: 1.0, 21: 1.0, 12: 1.0, 3: 1.0} - self.assertEqual(w10_30, w10_3[0]) + assert w10_30 == w10_3[0] w10_3 = util.higher_order_sp(w10, 3, lower_order=True) w10_30 = { 20: 1.0, @@ -153,7 +146,7 @@ def test_higher_order_sp(self): 12: 1.0, 3: 1.0, } - self.assertEqual(w10_30, w10_3[0]) + assert w10_30 == w10_3[0] def test_higher_order_classes(self): wdb = DistanceBand.from_shapefile(examples.get_path("baltim.shp"), 34) @@ -170,7 +163,7 @@ def test_higher_order_classes(self): util.higher_order(ww, 2) ww.transform = "r" wsparse_notbinary = wrook.sparse - with self.assertRaises(ValueError): + with pytest.raises(ValueError): util.higher_order(wsparse, 2) util.higher_order(ww, 3) @@ -178,9 +171,9 @@ def test_shimbel(self): w5 = lat2W() w5_shimbel = util.shimbel(w5) w5_shimbel024 = 8 - self.assertEqual(w5_shimbel024, w5_shimbel[0][24]) + assert w5_shimbel024 == w5_shimbel[0][24] w5_shimbel004 = [-1, 1, 2, 3] - self.assertEqual(w5_shimbel004, w5_shimbel[0][0:4]) + assert w5_shimbel004 == w5_shimbel[0][0:4] def test_full(self): neighbors = { @@ -194,9 +187,9 @@ def test_full(self): wfo = np.array([[0.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 0.0]]) np.testing.assert_array_almost_equal(wfo, wf, decimal=8) idso = ["first", "second", "third"] - self.assertEqual(idso, ids) + assert idso == ids - def test_full2W(self): + def test_full2_w(self): a = np.zeros((4, 4)) for i in range(len(a)): for j in range(len(a[i])): @@ -209,61 +202,61 @@ def test_full2W(self): np.testing.assert_array_equal(w.full()[0], a) w.full()[0] == a - def test_WSP2W(self): + def test_wsp2_w(self): sp = util.lat2SW(2, 5) wsp = WSP(sp) w = util.WSP2W(wsp) - self.assertEqual(w.n, 10) - self.assertEqual(w[0], {1: 1, 5: 1}) + assert w.n == 10 + assert w[0] == {1: 1, 5: 1} for weights in w.weights.values(): assert isinstance(weights, list) w = psopen(examples.get_path("sids2.gal"), "r").read() wsp = WSP(w.sparse, w.id_order) w = util.WSP2W(wsp) - self.assertEqual(w.n, 100) - self.assertEqual( - w["37135"], - {"37001": 1.0, "37033": 1.0, "37037": 1.0, "37063": 1.0, "37145": 1.0}, - ) + assert w.n == 100 + assert w["37135"] == { + "37001": 1.0, + "37033": 1.0, + "37037": 1.0, + "37063": 1.0, + "37145": 1.0, + } def test_fill_diagonal(self): w1 = util.fill_diagonal(self.w) r1 = {0: 1.0, 1: 1.0, 4: 1.0, 101: 1.0, 85: 1.0, 5: 1.0} - self.assertEqual(w1[0], r1) + assert w1[0] == r1 w1 = util.fill_diagonal(self.w, 20) r1 = {0: 20, 1: 1.0, 4: 1.0, 101: 1.0, 85: 1.0, 5: 1.0} - self.assertEqual(w1[0], r1) + assert w1[0] == r1 diag = np.arange(100, 100 + self.w.n) w1 = util.fill_diagonal(self.w, diag) r1 = {0: 100, 1: 1.0, 4: 1.0, 101: 1.0, 85: 1.0, 5: 1.0} - self.assertEqual(w1[0], r1) + assert w1[0] == r1 def test_remap_ids(self): w = lat2W(3, 2) wid_order = [0, 1, 2, 3, 4, 5] - self.assertEqual(wid_order, w.id_order) + assert wid_order == w.id_order wneighbors0 = [2, 1] - self.assertEqual(wneighbors0, w.neighbors[0]) + assert wneighbors0 == w.neighbors[0] old_to_new = {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f"} w_new = util.remap_ids(w, old_to_new) w_newid_order = ["a", "b", "c", "d", "e", "f"] - self.assertEqual(w_newid_order, w_new.id_order) + assert w_newid_order == w_new.id_order w_newdneighborsa = ["c", "b"] - self.assertEqual(w_newdneighborsa, w_new.neighbors["a"]) + assert w_newdneighborsa == w_new.neighbors["a"] def test_get_ids_shp(self): polyids = util.get_ids(examples.get_path("columbus.shp"), "POLYID") polyids5 = [1, 2, 3, 4, 5] - self.assertEqual(polyids5, polyids[:5]) + assert polyids5 == polyids[:5] - @unittest.skipIf( - not HAS_GEOPANDAS, "Missing geopandas, cannot test get_ids with gdf" - ) def test_get_ids_gdf(self): gdf = gpd.read_file(examples.get_path("columbus.shp")) polyids = util.get_ids(gdf, "POLYID") polyids5 = [1, 2, 3, 4, 5] - self.assertEqual(polyids5, polyids[:5]) + assert polyids5 == polyids[:5] def test_get_points_array_from_shapefile(self): xy = util.get_points_array_from_shapefile(examples.get_path("juvenile.shp")) @@ -285,86 +278,68 @@ def test_min_threshold_distance(self): y.shape = (25, 1) data = np.hstack([x, y]) mint = 1.0 - self.assertEqual(mint, util.min_threshold_distance(data)) + assert mint == util.min_threshold_distance(data) def test_attach_islands(self): w = Rook.from_shapefile(examples.get_path("10740.shp")) w_knn1 = KNN.from_shapefile(examples.get_path("10740.shp"), k=1) w_attach = util.attach_islands(w, w_knn1) - self.assertEqual(w_attach.islands, []) - self.assertEqual(w_attach[w.islands[0]], {166: 1.0}) + assert w_attach.islands == [] + assert w_attach[w.islands[0]] == {166: 1.0} - @unittest.skipIf( - not HAS_GEOPANDAS, "Missing geopandas, cannot test nonplanar neighbors" - ) def test_nonplanar_neighbors(self): df = gpd.read_file(examples.get_path("map_RS_BR.shp")) w = Queen.from_dataframe(df) - self.assertEqual( - w.islands, - [ - 0, - 4, - 23, - 27, - 80, - 94, - 101, - 107, - 109, - 119, - 122, - 139, - 169, - 175, - 223, - 239, - 247, - 253, - 254, - 255, - 256, - 261, - 276, - 291, - 294, - 303, - 321, - 357, - 374, - ], - ) + assert w.islands == [ + 0, + 4, + 23, + 27, + 80, + 94, + 101, + 107, + 109, + 119, + 122, + 139, + 169, + 175, + 223, + 239, + 247, + 253, + 254, + 255, + 256, + 261, + 276, + 291, + 294, + 303, + 321, + 357, + 374, + ] wnp = nonplanar_neighbors(w, df) - self.assertEqual(wnp.islands, []) - self.assertEqual(w.neighbors[0], []) - self.assertEqual(wnp.neighbors[0], [23, 59, 152, 239]) - self.assertEqual(wnp.neighbors[23], [0, 45, 59, 107, 152, 185, 246]) + assert wnp.islands == [] + assert w.neighbors[0] == [] + assert wnp.neighbors[0] == [23, 59, 152, 239] + assert wnp.neighbors[23] == [0, 45, 59, 107, 152, 185, 246] - @unittest.skipIf( - not HAS_GEOPANDAS, "Missing geopandas, cannot test fuzzy_contiguity" - ) def test_fuzzy_contiguity(self): rs = examples.get_path("map_RS_BR.shp") rs_df = gpd.read_file(rs) wf = fuzzy_contiguity(rs_df) - self.assertEqual(wf.islands, []) - self.assertEqual(set(wf.neighbors[0]), set([239, 59, 152, 23])) + assert wf.islands == [] + assert set(wf.neighbors[0]) == set([239, 59, 152, 23]) buff = fuzzy_contiguity(rs_df, buffering=True, buffer=0.2) - self.assertEqual( - set(buff.neighbors[0]), set([175, 119, 239, 59, 152, 246, 23, 107]) - ) + assert set(buff.neighbors[0]) == set([175, 119, 239, 59, 152, 246, 23, 107]) rs_index = rs_df.set_index("NM_MUNICIP") index_w = fuzzy_contiguity(rs_index) - self.assertEqual( - set(index_w.neighbors["TAVARES"]), set(["SÃO JOSÉ DO NORTE", "MOSTARDAS"]) + assert set(index_w.neighbors["TAVARES"]) == set( + ["SÃO JOSÉ DO NORTE", "MOSTARDAS"] ) wf_pred = fuzzy_contiguity(rs_df, predicate="touches") - self.assertEqual(set(wf_pred.neighbors[0]), set([])) - self.assertEqual(set(wf_pred.neighbors[1]), set([142, 82, 197, 285, 386, 350])) - - -suite = unittest.TestLoader().loadTestsFromTestCase(Testutil) - -if __name__ == "__main__": - runner = unittest.TextTestRunner() - runner.run(suite) + assert set(wf_pred.neighbors[0]) == set([]) + assert set(wf_pred.neighbors[1]) == set([142, 82, 197, 285, 386, 350]) diff --git a/libpysal/weights/tests/test_weights.py b/libpysal/weights/tests/test_weights.py index 8bd9456d6..8bb4e038c 100644 --- a/libpysal/weights/tests/test_weights.py +++ b/libpysal/weights/tests/test_weights.py @@ -2,37 +2,22 @@ import tempfile import warnings -import unittest +import geopandas +import numpy as np import pytest -from ..weights import W, WSP, _LabelEncoder +import scipy.sparse + +from ... import examples +from ...io.fileio import FileIO as psopen from .. import util -from ..util import WSP2W, lat2W from ..contiguity import Rook -from ...io.fileio import FileIO as psopen -from ... import examples from ..distance import KNN -import numpy as np -import scipy.sparse - -NPTA3E = np.testing.assert_array_almost_equal - -try: - import geopandas - - GEOPANDAS_EXTINCT = False -except ImportError: - GEOPANDAS_EXTINCT = True - -try: - import matplotlib - - MPL_EXTINCT = False -except ImportError: - MPL_EXTINCT = True +from ..util import WSP2W, lat2W +from ..weights import WSP, W, _LabelEncoder -class TestW(unittest.TestCase): - def setUp(self): +class TestW: + def setup_method(self): self.w = Rook.from_shapefile( examples.get_path("10740.shp"), silence_warnings=True ) @@ -63,64 +48,61 @@ def setUp(self): self.w3x3 = util.lat2W(3, 3) self.w_islands = W({0: [1], 1: [0, 2], 2: [1], 3: []}) - def test_W(self): + def test_w(self): w = W(self.neighbors, self.weights, silence_warnings=True) - self.assertEqual(w.pct_nonzero, 29.62962962962963) + assert w.pct_nonzero == 29.62962962962963 def test___getitem__(self): - self.assertEqual(self.w[0], {1: 1.0, 4: 1.0, 101: 1.0, 85: 1.0, 5: 1.0}) + assert self.w[0] == {1: 1.0, 4: 1.0, 101: 1.0, 85: 1.0, 5: 1.0} def test___init__(self): w = W(self.neighbors, self.weights, silence_warnings=True) - self.assertEqual(w.pct_nonzero, 29.62962962962963) + assert w.pct_nonzero == 29.62962962962963 def test___iter__(self): w = lat2W(3, 3) res = {} for i, wi in enumerate(w): res[i] = wi - self.assertEqual(res[0], (0, {1: 1.0, 3: 1.0})) - self.assertEqual(res[8], (8, {5: 1.0, 7: 1.0})) + assert res[0] == (0, {1: 1.0, 3: 1.0}) + assert res[8] == (8, {5: 1.0, 7: 1.0}) def test_asymmetries(self): w = lat2W(3, 3) w.transform = "r" result = w.asymmetry() - self.assertEqual( - result, - [ - (0, 1), - (0, 3), - (1, 0), - (1, 2), - (1, 4), - (2, 1), - (2, 5), - (3, 0), - (3, 4), - (3, 6), - (4, 1), - (4, 3), - (4, 5), - (4, 7), - (5, 2), - (5, 4), - (5, 8), - (6, 3), - (6, 7), - (7, 4), - (7, 6), - (7, 8), - (8, 5), - (8, 7), - ], - ) + assert result == [ + (0, 1), + (0, 3), + (1, 0), + (1, 2), + (1, 4), + (2, 1), + (2, 5), + (3, 0), + (3, 4), + (3, 6), + (4, 1), + (4, 3), + (4, 5), + (4, 7), + (5, 2), + (5, 4), + (5, 8), + (6, 3), + (6, 7), + (7, 4), + (7, 6), + (7, 8), + (8, 5), + (8, 7), + ] def test_asymmetry(self): w = lat2W(3, 3) - self.assertEqual(w.asymmetry(), []) + assert w.asymmetry() == [] w.transform = "r" - self.assertFalse(w.asymmetry() == []) + assert not w.asymmetry() == [] def test_asymmetry_string_index(self): neighbors = { @@ -174,22 +156,20 @@ def test_asymmetry_mixed_index(self): def test_cardinalities(self): w = lat2W(3, 3) - self.assertEqual( - w.cardinalities, {0: 2, 1: 3, 2: 2, 3: 3, 4: 4, 5: 3, 6: 2, 7: 3, 8: 2} - ) + assert w.cardinalities == {0: 2, 1: 3, 2: 2, 3: 3, 4: 4, 5: 3, 6: 2, 7: 3, 8: 2} - def test_diagW2(self): - NPTA3E( + def test_diag_w2(self): + np.testing.assert_array_almost_equal( self.w3x3.diagW2, np.array([2.0, 3.0, 2.0, 3.0, 4.0, 3.0, 2.0, 3.0, 2.0]) ) - def test_diagWtW(self): - NPTA3E( + def test_diag_wt_w(self): + np.testing.assert_array_almost_equal( self.w3x3.diagW2, np.array([2.0, 3.0, 2.0, 3.0, 4.0, 3.0, 2.0, 3.0, 2.0]) ) - def test_diagWtW_WW(self): - NPTA3E( + def test_diag_wt_w_ww(self): + np.testing.assert_array_almost_equal( self.w3x3.diagWtW_WW, np.array([4.0, 6.0, 4.0, 6.0, 8.0, 6.0, 4.0, 6.0, 4.0]), ) @@ -211,13 +191,13 @@ def test_full(self): ids = list(range(9)) wf1, ids1 = self.w3x3.full() - NPTA3E(wf1, wf) - self.assertEqual(ids1, ids) + np.testing.assert_array_almost_equal(wf1, wf) + assert ids1 == ids def test_get_transform(self): - self.assertEqual(self.w3x3.transform, "O") + assert self.w3x3.transform == "O" self.w3x3.transform = "r" - self.assertEqual(self.w3x3.transform, "R") + assert self.w3x3.transform == "R" self.w3x3.transform = "b" def test_higher_order(self): @@ -252,7 +232,7 @@ def test_higher_order(self): k: {ne: weights[k][i] for i, ne in enumerate(v)} for k, v in list(w2.neighbors.items()) } - self.assertEqual(test_wneighbs, wneighbs) + assert test_wneighbs == wneighbs def test_histogram(self): hist = [ @@ -273,43 +253,43 @@ def test_histogram(self): (14, 0), (15, 1), ] - self.assertEqual(self.w.histogram, hist) + assert self.w.histogram == hist def test_id2i(self): id2i = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8} - self.assertEqual(self.w3x3.id2i, id2i) + assert self.w3x3.id2i == id2i def test_id_order_set(self): w = W(neighbors={"a": ["b"], "b": ["a", "c"], "c": ["b"]}) - self.assertFalse(w.id_order_set) + assert not w.id_order_set def test_islands(self): w = W( neighbors={"a": ["b"], "b": ["a", "c"], "c": ["b"], "d": []}, silence_warnings=True, ) - self.assertEqual(w.islands, ["d"]) - self.assertEqual(self.w3x3.islands, []) + assert w.islands == ["d"] + assert self.w3x3.islands == [] def test_max_neighbors(self): w = W( neighbors={"a": ["b"], "b": ["a", "c"], "c": ["b"], "d": []}, silence_warnings=True, ) - self.assertEqual(w.max_neighbors, 2) - self.assertEqual(self.w3x3.max_neighbors, 4) + assert w.max_neighbors == 2 + assert self.w3x3.max_neighbors == 4 def test_mean_neighbors(self): w = util.lat2W() - self.assertEqual(w.mean_neighbors, 3.2) + assert w.mean_neighbors == 3.2 def test_min_neighbors(self): w = util.lat2W() - self.assertEqual(w.min_neighbors, 2) + assert w.min_neighbors == 2 def test_n(self): w = util.lat2W() - self.assertEqual(w.n, 25) + assert w.n == 25 def test_neighbor_offsets(self): d = { @@ -324,10 +304,10 @@ def test_neighbor_offsets(self): 8: [5, 7], } - self.assertEqual(self.w3x3.neighbor_offsets, d) + assert self.w3x3.neighbor_offsets == d def test_nonzero(self): - self.assertEqual(self.w3x3.nonzero, 24) + assert self.w3x3.nonzero == 24 def test_order(self): w = util.lat2W(3, 3) @@ -342,35 +322,35 @@ def test_order(self): 7: [3, 2, 3, 2, 1, 2, 1, -1, 1], 8: [0, 3, 2, 3, 2, 1, 2, 1, -1], } - self.assertEqual(util.order(w), o) + assert util.order(w) == o def test_pct_nonzero(self): - self.assertEqual(self.w3x3.pct_nonzero, 29.62962962962963) + assert self.w3x3.pct_nonzero == 29.62962962962963 def test_s0(self): - self.assertEqual(self.w3x3.s0, 24.0) + assert self.w3x3.s0 == 24.0 def test_s1(self): - self.assertEqual(self.w3x3.s1, 48.0) + assert self.w3x3.s1 == 48.0 def test_s2(self): - self.assertEqual(self.w3x3.s2, 272.0) + assert self.w3x3.s2 == 272.0 def test_s2array(self): s2a = np.array( [[16.0], [36.0], [16.0], [36.0], [64.0], [36.0], [16.0], [36.0], [16.0]] ) - NPTA3E(self.w3x3.s2array, s2a) + np.testing.assert_array_almost_equal(self.w3x3.s2array, s2a) def test_sd(self): - self.assertEqual(self.w3x3.sd, 0.66666666666666663) + assert self.w3x3.sd == 0.66666666666666663 def test_set_transform(self): w = util.lat2W(2, 2) - self.assertEqual(w.transform, "O") - self.assertEqual(w.weights[0], [1.0, 1.0]) + assert w.transform == "O" + assert w.weights[0] == [1.0, 1.0] w.transform = "r" - self.assertEqual(w.weights[0], [0.5, 0.5]) + assert w.weights[0] == [0.5, 0.5] def test_shimbel(self): d = { @@ -384,19 +364,19 @@ def test_shimbel(self): 7: [3, 2, 3, 2, 1, 2, 1, -1, 1], 8: [4, 3, 2, 3, 2, 1, 2, 1, -1], } - self.assertEqual(util.shimbel(self.w3x3), d) + assert util.shimbel(self.w3x3) == d def test_sparse(self): - self.assertEqual(self.w3x3.sparse.nnz, 24) + assert self.w3x3.sparse.nnz == 24 - def test_trcW2(self): - self.assertEqual(self.w3x3.trcW2, 24.0) + def test_trc_w2(self): + assert self.w3x3.trcW2 == 24.0 - def test_trcWtW(self): - self.assertEqual(self.w3x3.trcWtW, 24.0) + def test_trc_wt_w(self): + assert self.w3x3.trcWtW == 24.0 - def test_trcWtW_WW(self): - self.assertEqual(self.w3x3.trcWtW_WW, 48.0) + def test_trc_wt_w_ww(self): + assert self.w3x3.trcWtW_WW == 48.0 def test_symmetrize(self): symm = self.w.symmetrize() @@ -423,8 +403,8 @@ def test_roundtrip_write(self): new = W.from_file(path) np.testing.assert_array_equal(self.w.sparse.toarray(), new.sparse.toarray()) - @unittest.skipIf(GEOPANDAS_EXTINCT or MPL_EXTINCT, "Missing dependencies") def test_plot(self): + pytest.importorskip("matplotlib") df = geopandas.read_file(examples.get_path("10740.shp")) with warnings.catch_warnings(record=True) as record: self.w.plot(df) @@ -436,15 +416,15 @@ def test_to_sparse(self): np.testing.assert_array_equal(sparse.row, [0, 1, 1, 2, 3]) np.testing.assert_array_equal(sparse.col, [1, 0, 2, 1, 3]) sparse = self.w_islands.to_sparse("bsr") - self.assertIsInstance(sparse, scipy.sparse.bsr_array) + assert isinstance(sparse, scipy.sparse.bsr_array) sparse = self.w_islands.to_sparse("csr") - self.assertIsInstance(sparse, scipy.sparse.csr_array) + assert isinstance(sparse, scipy.sparse.csr_array) sparse = self.w_islands.to_sparse("coo") - self.assertIsInstance(sparse, scipy.sparse.coo_array) + assert isinstance(sparse, scipy.sparse.coo_array) sparse = self.w_islands.to_sparse("csc") - self.assertIsInstance(sparse, scipy.sparse.csc_array) + assert isinstance(sparse, scipy.sparse.csc_array) sparse = self.w_islands.to_sparse() - self.assertIsInstance(sparse, scipy.sparse.coo_array) + assert isinstance(sparse, scipy.sparse.coo_array) def test_sparse_fmt(self): with pytest.raises(ValueError) as exc_info: @@ -453,14 +433,14 @@ def test_sparse_fmt(self): def test_from_sparse(self): sparse = self.w_islands.to_sparse() w = W.from_sparse(sparse) - self.assertEqual(w.n, 4) - self.assertEqual(len(w.islands), 0) - self.assertEqual(w.neighbors[3], [3]) + assert w.n == 4 + assert len(w.islands) == 0 + assert w.neighbors[3] == [3] -class Test_WSP_Back_To_W(unittest.TestCase): +class Test_WSP_Back_To_W: # Test to make sure we get back to the same W functionality - def setUp(self): + def setup_method(self): self.w = Rook.from_shapefile( examples.get_path("10740.shp"), silence_warnings=True ) @@ -494,83 +474,78 @@ def setUp(self): w3x3 = WSP(self.w3x3.sparse, self.w3x3.id_order) self.w3x3 = WSP2W(w3x3) - def test_W(self): + def test_w(self): w = W(self.neighbors, self.weights, silence_warnings=True) - self.assertEqual(w.pct_nonzero, 29.62962962962963) + assert w.pct_nonzero == 29.62962962962963 def test___getitem__(self): - self.assertEqual(self.w[0], {1: 1.0, 4: 1.0, 101: 1.0, 85: 1.0, 5: 1.0}) + assert self.w[0] == {1: 1.0, 4: 1.0, 101: 1.0, 85: 1.0, 5: 1.0} def test___init__(self): w = W(self.neighbors, self.weights, silence_warnings=True) - self.assertEqual(w.pct_nonzero, 29.62962962962963) + assert w.pct_nonzero == 29.62962962962963 def test___iter__(self): w = util.lat2W(3, 3) res = {} for i, wi in enumerate(w): res[i] = wi - self.assertEqual(res[0], (0, {1: 1.0, 3: 1.0})) - self.assertEqual(res[8], (8, {5: 1.0, 7: 1.0})) + assert res[0] == (0, {1: 1.0, 3: 1.0}) + assert res[8] == (8, {5: 1.0, 7: 1.0}) def test_asymmetries(self): w = util.lat2W(3, 3) w.transform = "r" result = w.asymmetry() - self.assertEqual( - result, - [ - (0, 1), - (0, 3), - (1, 0), - (1, 2), - (1, 4), - (2, 1), - (2, 5), - (3, 0), - (3, 4), - (3, 6), - (4, 1), - (4, 3), - (4, 5), - (4, 7), - (5, 2), - (5, 4), - (5, 8), - (6, 3), - (6, 7), - (7, 4), - (7, 6), - (7, 8), - (8, 5), - (8, 7), - ], - ) + assert result == [ + (0, 1), + (0, 3), + (1, 0), + (1, 2), + (1, 4), + (2, 1), + (2, 5), + (3, 0), + (3, 4), + (3, 6), + (4, 1), + (4, 3), + (4, 5), + (4, 7), + (5, 2), + (5, 4), + (5, 8), + (6, 3), + (6, 7), + (7, 4), + (7, 6), + (7, 8), + (8, 5), + (8, 7), + ] def test_asymmetry(self): w = util.lat2W(3, 3) - self.assertEqual(w.asymmetry(), []) + assert w.asymmetry() == [] w.transform = "r" - self.assertFalse(w.asymmetry() == []) + assert not w.asymmetry() == [] def test_cardinalities(self): w = util.lat2W(3, 3) - self.assertEqual( - w.cardinalities, {0: 2, 1: 3, 2: 2, 3: 3, 4: 4, 5: 3, 6: 2, 7: 3, 8: 2} - ) + assert w.cardinalities == {0: 2, 1: 3, 2: 2, 3: 3, 4: 4, 5: 3, 6: 2, 7: 3, 8: 2} - def test_diagW2(self): - NPTA3E( + def test_diag_w2(self): + np.testing.assert_array_almost_equal( self.w3x3.diagW2, np.array([2.0, 3.0, 2.0, 3.0, 4.0, 3.0, 2.0, 3.0, 2.0]) ) - def test_diagWtW(self): - NPTA3E( + def test_diag_wt_w(self): + np.testing.assert_array_almost_equal( self.w3x3.diagW2, np.array([2.0, 3.0, 2.0, 3.0, 4.0, 3.0, 2.0, 3.0, 2.0]) ) - def test_diagWtW_WW(self): - NPTA3E( + def test_diag_wt_w_ww(self): + np.testing.assert_array_almost_equal( self.w3x3.diagWtW_WW, np.array([4.0, 6.0, 4.0, 6.0, 8.0, 6.0, 4.0, 6.0, 4.0]), ) @@ -592,13 +567,13 @@ def test_full(self): ids = list(range(9)) wf1, ids1 = self.w3x3.full() - NPTA3E(wf1, wf) - self.assertEqual(ids1, ids) + np.testing.assert_array_almost_equal(wf1, wf) + assert ids1 == ids def test_get_transform(self): - self.assertEqual(self.w3x3.transform, "O") + assert self.w3x3.transform == "O" self.w3x3.transform = "r" - self.assertEqual(self.w3x3.transform, "R") + assert self.w3x3.transform == "R" self.w3x3.transform = "b" def test_higher_order(self): @@ -633,7 +608,7 @@ def test_higher_order(self): k: {ne: w2.weights[k][i] for i, ne in enumerate(v)} for k, v in list(w2.neighbors.items()) } - self.assertEqual(test_wneighbs, wneighbs) + assert test_wneighbs == wneighbs def test_histogram(self): hist = [ @@ -654,46 +629,46 @@ def test_histogram(self): (14, 0), (15, 1), ] - self.assertEqual(self.w.histogram, hist) + assert self.w.histogram == hist def test_id2i(self): id2i = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8} - self.assertEqual(self.w3x3.id2i, id2i) + assert self.w3x3.id2i == id2i def test_id_order_set(self): w = W(neighbors={"a": ["b"], "b": ["a", "c"], "c": ["b"]}) - self.assertFalse(w.id_order_set) + assert not w.id_order_set def test_islands(self): w = W( neighbors={"a": ["b"], "b": ["a", "c"], "c": ["b"], "d": []}, silence_warnings=True, ) - self.assertEqual(w.islands, ["d"]) - self.assertEqual(self.w3x3.islands, []) + assert w.islands == ["d"] + assert self.w3x3.islands == [] def test_max_neighbors(self): w = W( neighbors={"a": ["b"], "b": ["a", "c"], "c": ["b"], "d": []}, silence_warnings=True, ) - self.assertEqual(w.max_neighbors, 2) - self.assertEqual(self.w3x3.max_neighbors, 4) + assert w.max_neighbors == 2 + assert self.w3x3.max_neighbors == 4 def test_mean_neighbors(self): w = util.lat2W() - self.assertEqual(w.mean_neighbors, 3.2) + assert w.mean_neighbors == 3.2 def test_min_neighbors(self): w = util.lat2W() - self.assertEqual(w.min_neighbors, 2) + assert w.min_neighbors == 2 def test_n(self): w = util.lat2W() - self.assertEqual(w.n, 25) + assert w.n == 25 def test_nonzero(self): - self.assertEqual(self.w3x3.nonzero, 24) + assert self.w3x3.nonzero == 24 def test_order(self): w = util.lat2W(3, 3) @@ -708,35 +683,35 @@ def test_order(self): 7: [3, 2, 3, 2, 1, 2, 1, -1, 1], 8: [0, 3, 2, 3, 2, 1, 2, 1, -1], } - self.assertEqual(util.order(w), o) + assert util.order(w) == o def test_pct_nonzero(self): - self.assertEqual(self.w3x3.pct_nonzero, 29.62962962962963) + assert self.w3x3.pct_nonzero == 29.62962962962963 def test_s0(self): - self.assertEqual(self.w3x3.s0, 24.0) + assert self.w3x3.s0 == 24.0 def test_s1(self): - self.assertEqual(self.w3x3.s1, 48.0) + assert self.w3x3.s1 == 48.0 def test_s2(self): - self.assertEqual(self.w3x3.s2, 272.0) + assert self.w3x3.s2 == 272.0 def test_s2array(self): s2a = np.array( [[16.0], [36.0], [16.0], [36.0], [64.0], [36.0], [16.0], [36.0], [16.0]] ) - NPTA3E(self.w3x3.s2array, s2a) + np.testing.assert_array_almost_equal(self.w3x3.s2array, s2a) def test_sd(self): - self.assertEqual(self.w3x3.sd, 0.66666666666666663) + assert self.w3x3.sd == 0.66666666666666663 def test_set_transform(self): w = util.lat2W(2, 2) - self.assertEqual(w.transform, "O") - self.assertEqual(w.weights[0], [1.0, 1.0]) + assert w.transform == "O" + assert w.weights[0] == [1.0, 1.0] w.transform = "r" - self.assertEqual(w.weights[0], [0.5, 0.5]) + assert w.weights[0] == [0.5, 0.5] def test_shimbel(self): d = { @@ -750,53 +725,53 @@ def test_shimbel(self): 7: [3, 2, 3, 2, 1, 2, 1, -1, 1], 8: [4, 3, 2, 3, 2, 1, 2, 1, -1], } - self.assertEqual(util.shimbel(self.w3x3), d) + assert util.shimbel(self.w3x3) == d def test_sparse(self): - self.assertEqual(self.w3x3.sparse.nnz, 24) + assert self.w3x3.sparse.nnz == 24 - def test_trcW2(self): - self.assertEqual(self.w3x3.trcW2, 24.0) + def test_trc_w2(self): + assert self.w3x3.trcW2 == 24.0 - def test_trcWtW(self): - self.assertEqual(self.w3x3.trcWtW, 24.0) + def test_trc_wt_w(self): + assert self.w3x3.trcWtW == 24.0 - def test_trcWtW_WW(self): - self.assertEqual(self.w3x3.trcWtW_WW, 48.0) + def test_trc_wt_w_ww(self): + assert self.w3x3.trcWtW_WW == 48.0 -class TestWSP(unittest.TestCase): - def setUp(self): +class TestWSP: + def setup_method(self): self.w = psopen(examples.get_path("sids2.gal")).read() self.wsp = WSP(self.w.sparse, self.w.id_order) w3x3 = util.lat2W(3, 3) self.w3x3 = WSP(w3x3.sparse) - def test_WSP(self): - self.assertEqual(self.w.id_order, self.wsp.id_order) - self.assertEqual(self.w.n, self.wsp.n) + def test_wsp(self): + assert self.w.id_order == self.wsp.id_order + assert self.w.n == self.wsp.n np.testing.assert_array_equal( self.w.sparse.todense(), self.wsp.sparse.todense() ) - def test_diagWtW_WW(self): - NPTA3E( + def test_diag_wt_w_ww(self): + np.testing.assert_array_almost_equal( self.w3x3.diagWtW_WW, np.array([4.0, 6.0, 4.0, 6.0, 8.0, 6.0, 4.0, 6.0, 4.0]), ) - def test_trcWtW_WW(self): - self.assertEqual(self.w3x3.trcWtW_WW, 48.0) + def test_trc_wt_w_ww(self): + assert self.w3x3.trcWtW_WW == 48.0 def test_s0(self): - self.assertEqual(self.w3x3.s0, 24.0) + assert self.w3x3.s0 == 24.0 - def test_from_WSP(self): + def test_from_wsp(self): w = W.from_WSP(self.wsp) - self.assertEqual(w.n, 100) - self.assertEqual(w.pct_nonzero, 4.62) + assert w.n == 100 + assert w.pct_nonzero == 4.62 - def test_LabelEncoder(self): + def test_label_encoder(self): le = _LabelEncoder() le.fit(["NY", "CA", "NY", "CA", "TX", "TX"]) np.testing.assert_equal(le.classes_, np.array(["CA", "NY", "TX"])) @@ -804,7 +779,3 @@ def test_LabelEncoder(self): le.transform(["NY", "CA", "NY", "CA", "TX", "TX"]), np.array([1, 0, 1, 0, 2, 2]), ) - - -if __name__ == "__main__": - unittest.main() diff --git a/libpysal/weights/tests/test_weights_IO.py b/libpysal/weights/tests/test_weights_IO.py index cafa534ce..4d130359a 100644 --- a/libpysal/weights/tests/test_weights_IO.py +++ b/libpysal/weights/tests/test_weights_IO.py @@ -1,16 +1,17 @@ -import unittest +import os +import tempfile + import libpysal -import tempfile, os -class TestWIO(unittest.TestCase): - def setUp(self): +class TestWIO: + def setup_method(self): self.swmFile1 = libpysal.examples.get_path("ohio.swm") self.swmFile2 = libpysal.examples.get_path("us48_CONTIGUITY_EDGES_ONLY.swm") self.swmFile3 = libpysal.examples.get_path("us48_INVERSE_DISTANCE.swm") self.files = [self.swmFile1, self.swmFile2, self.swmFile3] - def test_SWMIO(self): + def test_swmio(self): for file in self.files: f1 = libpysal.io.open(file) w1 = f1.read() @@ -27,8 +28,4 @@ def test_SWMIO(self): f2.close() w2 = libpysal.io.open(fname, "r").read() assert w1.pct_nonzero == w2.pct_nonzero - os.remove(fname) - - -if __name__ == "__main__": - unittest.main() + os.remove(fname) \ No newline at end of file