1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
|
"""``pytest`` fixtures."""
import functools
import operator
import os
import shutil
import sys
import uuid
import zipfile
import affine
import boto3
import numpy as np
import pytest
from click.testing import CliRunner
import rasterio
import rasterio.env
from rasterio.coords import BoundingBox
from rasterio.crs import CRS
from rasterio.enums import ColorInterp
from rasterio.env import GDALVersion
from affine import Affine
DEFAULT_SHAPE = (10, 10)
reduce = functools.reduce
try:
have_credentials = boto3.Session().get_credentials()
except Exception:
have_credentials = False
credentials = pytest.mark.skipif(
not(have_credentials),
reason="S3 raster access requires credentials")
test_files = [os.path.join(os.path.dirname(__file__), p) for p in [
'data/RGB.byte.tif', 'data/float.tif', 'data/float32.tif',
'data/float_nan.tif', 'data/shade.tif', 'data/RGBA.byte.tif']]
def pytest_cmdline_main(config):
# Bail if the test raster data is not present. Test data is not
# distributed with sdists since 0.12.
if reduce(operator.and_, map(os.path.exists, test_files)):
print("Test data present.")
else:
print("Test data not present. See download directions in "
"tests/data/README.rst")
sys.exit(1)
@pytest.fixture(scope='function')
def runner():
return CliRunner()
@pytest.fixture(scope='function')
def data(tmpdir):
"""A temporary directory containing a copy of the files in data."""
for filename in test_files:
shutil.copy(filename, str(tmpdir))
return tmpdir
@pytest.fixture(scope='function')
def red_green(tmpdir):
"""A temporary directory containing copies of red.tif, green.tif."""
for filename in ['tests/data/red.tif', 'tests/data/red.tif.ovr', 'tests/data/green.tif', 'tests/data/green.tif.ovr']:
shutil.copy(filename, str(tmpdir))
return tmpdir
@pytest.fixture
def basic_geometry():
"""A Polygon with 2D coordinates.
Returns
-------
dict : GeoJSON-style geometry object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'type': 'Polygon',
'coordinates': [[(2, 2), (2, 4.25), (4.25, 4.25), (4.25, 2), (2, 2)]]
}
@pytest.fixture
def basic_geometry_3d():
"""A Polygon with 3D coordinates.
Returns
-------
dict : GeoJSON-style geometry object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
"type": "Polygon",
"coordinates": [
[(2, 2, 0), (2, 4.25, 0), (4.25, 4.25, 0), (4.25, 2, 0), (2, 2, 0)]
],
}
@pytest.fixture
def rotation_geometry():
"""A rotated geometry.
Returns
-------
dict : GeoJSON-style geometry object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'type': 'Polygon',
'coordinates': [[(481070, 4481140), (481040, 4481160),
(481035, 4481130), (481060, 4481125),
(481070, 4481140)]]
}
@pytest.fixture
def geojson_point():
"""A 2D Point.
Returns
-------
dict : GeoJSON-style Point geometry object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {"type": "Point", "coordinates": (2, 2)}
@pytest.fixture
def geojson_multipoint():
"""
Returns
-------
dict: GeoJSON-style MultiPoint geometry object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'type': 'MultiPoint',
'coordinates': ((2, 2), (4, 4))
}
@pytest.fixture
def geojson_line():
"""
Returns
-------
dict: GeoJSON-style LineString geometry object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'type': 'LineString',
'coordinates': ((2, 2), (4, 4))
}
@pytest.fixture
def geojson_multiline():
"""
Returns
-------
dict: GeoJSON-style MultiLineString geometry object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'type': 'MultiLineString',
'coordinates': (((2, 2), (4, 4)), ((0, 0), (4, 0)))
}
@pytest.fixture
def geojson_polygon(basic_geometry):
"""
Returns
-------
dict: GeoJSON-style Polygon geometry object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return basic_geometry
@pytest.fixture
def geojson_multipolygon():
"""
Returns
-------
dict: GeoJSON-style MultiPolygon geometry object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'type': 'MultiPolygon',
'coordinates': (
(((2, 2), (2, 4), (4, 4), (4, 2), (2, 2)), ),
(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)), )
)
}
@pytest.fixture
def geojson_geomcollection():
"""
Returns
-------
dict: GeoJSON-style GeometryCollection object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'type': 'GeometryCollection',
'geometries': (
{
'type': 'Polygon',
'coordinates': (((2, 2), (2, 4), (4, 4), (4, 2), (2, 2)), )
},
{
'type': 'Polygon',
'coordinates': (((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)), )
}
)
}
@pytest.fixture
def basic_feature(basic_geometry):
"""
Returns
-------
dict: GeoJSON object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'geometry': basic_geometry,
'properties': {
'val': 15
},
'type': 'Feature'
}
@pytest.fixture
def basic_featurecollection(basic_feature):
"""
Returns
-------
dict: GeoJSON FeatureCollection object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'features': [basic_feature],
'type': 'FeatureCollection'
}
@pytest.fixture
def basic_image():
"""
A basic 10x10 array for testing sieve and shapes functions.
Contains a square feature 3x3 (size 9).
Equivalent to results of rasterizing basic_geometry with all_touched=True.
Returns
-------
np ndarray
"""
image = np.zeros(DEFAULT_SHAPE, dtype=np.uint8)
image[2:5, 2:5] = 1
return image
@pytest.fixture
def basic_image_2x2():
"""
A basic 10x10 array for testing sieve and shapes functions.
Contains a square feature 2x2 (size 4).
Equivalent to results of rasterizing basic_geometry with all_touched=False.
Returns
-------
np ndarray
"""
image = np.zeros(DEFAULT_SHAPE, dtype=np.uint8)
image[2:4, 2:4] = 1
return image
@pytest.fixture
def basic_image_2x2x2():
"""
A basic 10x10 array for testing sieve and shapes functions.
Contains a square feature 2x2 (size 4).
Equivalent to results of rasterizing two times the basic_geometry with
merge_alg='add'.
Returns
-------
np ndarray
"""
image = np.zeros(DEFAULT_SHAPE, dtype=np.uint8)
image[2:4, 2:4] = 2
return image
@pytest.fixture
def pixelated_image(basic_image):
"""
A basic 10x10 array for testing sieve functions. Contains a square feature
3x3 (size 9), with 2 isolated pixels.
Returns
-------
np ndarray
"""
image = basic_image.copy()
image[0, 0] = 1
image[8, 8] = 1
return image
@pytest.fixture
def diagonal_image():
"""
A 10x10 array for testing sieve functions, with only one diagonal filled.
Returns
-------
np ndarray
"""
image = np.zeros(DEFAULT_SHAPE, dtype=np.uint8)
np.fill_diagonal(image, 1)
return image
@pytest.fixture()
def basic_image_file(tmpdir, basic_image):
"""
A basic raster file with a 10x10 array for testing sieve functions.
Contains data from pixelated_image.
Returns
-------
string
Filename of test raster file
"""
image = basic_image
outfilename = str(tmpdir.join('basic_image.tif'))
kwargs = {
"crs": CRS({'init': 'epsg:4326'}),
"transform": Affine.identity(),
"count": 1,
"dtype": rasterio.uint8,
"driver": "GTiff",
"width": image.shape[1],
"height": image.shape[0],
"nodata": None
}
with rasterio.open(outfilename, 'w', **kwargs) as out:
out.write(image, indexes=1)
return outfilename
@pytest.fixture()
def pixelated_image_file(tmpdir, pixelated_image):
"""
A basic raster file with a 10x10 array for testing sieve functions.
Contains data from pixelated_image.
Returns
-------
string
Filename of test raster file
"""
image = pixelated_image
outfilename = str(tmpdir.join('pixelated_image.tif'))
kwargs = {
"crs": CRS({'init': 'epsg:4326'}),
"transform": Affine.identity(),
"count": 1,
"dtype": rasterio.uint8,
"driver": "GTiff",
"width": image.shape[1],
"height": image.shape[0],
"nodata": 255
}
with rasterio.open(outfilename, 'w', **kwargs) as out:
out.write(image, indexes=1)
return outfilename
@pytest.fixture()
def rotated_image_file(tmpdir, pixelated_image):
"""
A basic raster file with a 1000x2000 array for testing sieve functions.
Contains only one value: 128.
Returns
-------
string
Filename of test raster file
"""
image = 128 * np.ones((1000, 2000), dtype=np.uint8)
rotated_transform = Affine(-0.05, 0.07, 481060,
0.07, 0.05, 4481030)
outfilename = str(tmpdir.join('rotated_image.tif'))
kwargs = {
"crs": CRS({'init': 'epsg:32613'}),
"transform": rotated_transform,
"count": 1,
"dtype": rasterio.uint8,
"driver": "GTiff",
"width": image.shape[1],
"height": image.shape[0],
"nodata": 255,
"compress": "lzw"
}
with rasterio.open(outfilename, 'w', **kwargs) as out:
out.write(image, indexes=1)
return outfilename
@pytest.fixture()
def image_file_with_custom_size_and_transform(tmpdir):
"""
A basic raster file with a 10x10 array containing a
caller supplied transform.
Returns
-------
string
Filename of test raster file
"""
def inner(width, height, transform):
image = np.zeros((height, width))
outfilename = str(tmpdir.join('basic_image.tif'))
kwargs = {
"crs": CRS({'init': 'epsg:4326'}),
"transform": transform,
"count": 1,
"dtype": rasterio.uint8,
"driver": "GTiff",
"width": image.shape[1],
"height": image.shape[0],
"nodata": None
}
with rasterio.open(outfilename, 'w', **kwargs) as out:
out.write(image, indexes=1)
return outfilename
return inner
@pytest.fixture(scope='function')
def gdalenv(request):
def fin():
if rasterio.env.local._env:
rasterio.env.delenv()
rasterio.env.local._env = None
request.addfinalizer(fin)
@pytest.fixture(scope='session')
def data_dir():
"""Absolute file path to the directory containing test datasets."""
root = os.path.join(os.path.dirname(__file__), '..')
return os.path.abspath(os.path.join(root, 'tests', 'data'))
@pytest.fixture(scope='session')
def path_rgb_byte_tif(data_dir):
"""The original RGB test fixture with no sidecar files"""
return os.path.join(data_dir, 'RGB.byte.tif')
@pytest.fixture(scope='session')
def path_srtm_hgt(data_dir):
"""Sample SRTM HGT file"""
return os.path.join(data_dir, 'N10W110.hgt.zip')
@pytest.fixture(scope='session')
def path_rgb_lzw_byte_tif(data_dir):
"""The original RGB test fixture with LZW compression."""
return os.path.join(data_dir, 'rgb_lzw.tif')
@pytest.fixture(scope='session')
def path_rgb_byte_rpc_vrt(data_dir):
return os.path.join(data_dir, 'RGB.byte.rpc.vrt')
@pytest.fixture(scope='session')
def path_rgba_byte_tif(data_dir):
"""Derived from RGB.byte.tif, this has an alpha band"""
return os.path.join(data_dir, 'RGBA.byte.tif')
@pytest.fixture(scope='session')
def path_rgb_msk_byte_tif(data_dir):
"""Derived from RGB.byte.tif, this has an external mask"""
return os.path.join(data_dir, 'RGB2.byte.tif')
@pytest.fixture(scope='session')
def path_cogeo_tif(data_dir):
return os.path.join(data_dir, 'cogeo.tif')
@pytest.fixture(scope='session')
def path_white_gemini_iv_vrt(data_dir):
return os.path.join(data_dir, 'white-gemini-iv.vrt')
@pytest.fixture(scope='function')
def _path_multiband_no_colorinterp(tmpdir):
"""Produces a function for generating an image with ``count`` bands
and undefined color interpretation. May trigger a PAM file depending on
the GDAL version.
Returns
-------
function
"""
def _create_path_multiband_no_colorinterp(count):
# For GDAL 2.2.2 the first band can be 'undefined', but on older
# versions it must be 'gray'.
undefined_ci = [ColorInterp.gray]
if count > 1:
undefined_ci += [ColorInterp.undefined] * (count - 1)
dst_path = str(tmpdir.join('4band-byte-no-ci.tif'))
profile = {
'height': 10,
'width': 10,
'count': count,
'dtype': rasterio.ubyte,
'transform': affine.Affine(1, 0.0, 0,
0.0, -1, 1),
'driver': 'GTiff',
'photometric': 'minisblack'
}
undefined_ci = tuple(undefined_ci)
with rasterio.open(dst_path, 'w', **profile) as src:
src.colorinterp = undefined_ci
# Ensure override occurred. Setting color interpretation on an
# existing file is surrounded by traps and forceful GDAL assumptions,
# especially on older versions.
with rasterio.open(dst_path) as src:
if src.colorinterp != undefined_ci:
raise ValueError(
"Didn't properly set color interpretation. GDAL can "
"forcefully make assumptions.")
return dst_path
return _create_path_multiband_no_colorinterp
@pytest.fixture(scope='function')
def path_3band_no_colorinterp(_path_multiband_no_colorinterp):
"""A 3 band image with undefined color interpretation."""
return _path_multiband_no_colorinterp(3)
@pytest.fixture(scope='function')
def path_4band_no_colorinterp(_path_multiband_no_colorinterp):
"""A 4 band image with undefined color interpretation."""
return _path_multiband_no_colorinterp(4)
@pytest.fixture(scope='session')
def path_float_tif(data_dir):
return os.path.join(data_dir, 'float.tif')
@pytest.fixture(scope='session')
def path_alpha_tif(data_dir):
return os.path.join(data_dir, 'alpha.tif')
@pytest.fixture(scope='session')
def path_zip_file(data_dir):
"""Creates ``coutwildrnp.zip`` if it does not exist and returns
the absolute file path."""
path = f"{data_dir}/white-gemini-iv.zip"
if not os.path.exists(path):
with zipfile.ZipFile(path, 'w') as zip:
for filename in ['white-gemini-iv.vrt',
'389225main_sw_1965_1024.jpg']:
zip.write(os.path.join(data_dir, filename), filename)
return path
@pytest.fixture(autouse=True)
def set_mem_name(request, monkeypatch):
def youyoueyedeefour():
return f"{request.node.name}-{uuid.uuid4()}"
monkeypatch.setattr(rasterio._io, "uuid4", youyoueyedeefour)
class MockGeoInterface:
"""Tiny wrapper for GeoJSON to present an object with __geo_interface__ for testing"""
def __init__(self, geojson):
self.__geo_interface__ = geojson
# Define helpers to skip tests based on GDAL version
gdal_version = GDALVersion.runtime()
requires_gdal37 = pytest.mark.skipif(
not gdal_version.at_least('3.7'), reason="Requires GDAL 3.7.x"
)
requires_gdal_lt_37 = pytest.mark.skipif(
gdal_version.at_least('3.7'), reason="Requires GDAL before 3.7"
)
def assert_bounding_box_equal(expected, actual, tolerance=1e-4):
if isinstance(expected, tuple):
expected = BoundingBox(*expected)
if isinstance(actual, tuple):
actual = BoundingBox(*actual)
left = abs(expected.left - actual.left)
bottom = abs(expected.bottom - actual.bottom)
right = abs(expected.right - actual.right)
top = abs(expected.top - actual.top)
assert all(diff < tolerance for diff in [left, bottom, right, top]), f"{expected} differs from {actual}"
|