| 1 |
# -*- coding: utf-8 -*- |
| 2 |
############################################################################### |
| 3 |
# |
| 4 |
# Project: GDAL/OGR Test Suite |
| 5 |
# Purpose: Python Library supporting GDAL/OGR Test Suite |
| 6 |
# Author: Frank Warmerdam <[email protected]> |
| 7 |
# |
| 8 |
############################################################################### |
| 9 |
# Copyright (c) 2003, Frank Warmerdam <[email protected]> |
| 10 |
# Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com> |
| 11 |
# |
| 12 |
# SPDX-License-Identifier: MIT |
| 13 |
# |
| 14 |
############################################################################### |
| 15 |
|
| 16 |
import contextlib |
| 17 |
import io |
| 18 |
import json |
| 19 |
import math |
| 20 |
import os |
| 21 |
import os.path |
| 22 |
import shlex |
| 23 |
import socket |
| 24 |
import stat |
| 25 |
import subprocess |
| 26 |
import sys |
| 27 |
import time |
| 28 |
import urllib.error |
| 29 |
import urllib.parse |
| 30 |
import urllib.request |
| 31 |
from queue import Queue |
| 32 |
from threading import Thread |
| 33 |
|
| 34 |
import pytest |
| 35 |
|
| 36 |
from osgeo import gdal, ogr, osr |
| 37 |
|
| 38 |
jp2kak_drv = None |
| 39 |
jpeg2000_drv = None |
| 40 |
jp2ecw_drv = None |
| 41 |
jp2mrsid_drv = None |
| 42 |
jp2openjpeg_drv = None |
| 43 |
jp2lura_drv = None |
| 44 |
jp2kak_drv_unregistered = False |
| 45 |
jpeg2000_drv_unregistered = False |
| 46 |
jp2ecw_drv_unregistered = False |
| 47 |
jp2mrsid_drv_unregistered = False |
| 48 |
jp2openjpeg_drv_unregistered = False |
| 49 |
jp2lura_drv_unregistered = False |
| 50 |
|
| 51 |
############################################################################### |
| 52 |
|
| 53 |
|
| 54 |
def clean_tmp(): |
| 55 |
all_files = os.listdir("tmp") |
| 56 |
for filename in all_files: |
| 57 |
if filename in ["CVS", "do-not-remove"]: |
| 58 |
continue |
| 59 |
|
| 60 |
try: |
| 61 |
os.remove("tmp/" + filename) |
| 62 |
except OSError: |
| 63 |
pass |
| 64 |
|
| 65 |
|
| 66 |
############################################################################### |
| 67 |
|
| 68 |
|
| 69 |
def testCreateCopyInterruptCallback(pct, message, user_data): |
| 70 |
# pylint: disable=unused-argument |
| 71 |
return pct <= 0.5 |
| 72 |
|
| 73 |
|
| 74 |
############################################################################### |
| 75 |
|
| 76 |
|
| 77 |
class GDALTest(object): |
| 78 |
def __init__( |
| 79 |
self, |
| 80 |
drivername, |
| 81 |
filename, |
| 82 |
band, |
| 83 |
chksum, |
| 84 |
xoff=0, |
| 85 |
yoff=0, |
| 86 |
xsize=0, |
| 87 |
ysize=0, |
| 88 |
options=None, |
| 89 |
filename_absolute=0, |
| 90 |
chksum_after_reopening=None, |
| 91 |
open_options=None, |
| 92 |
): |
| 93 |
self.driver = None |
| 94 |
self.drivername = drivername |
| 95 |
self.filename = filename |
| 96 |
|
| 97 |
if isinstance(self.filename, os.PathLike): |
| 98 |
self.filename = str(self.filename) |
| 99 |
|
| 100 |
self.filename_absolute = filename_absolute |
| 101 |
self.band = band |
| 102 |
self.chksum = chksum |
| 103 |
if chksum_after_reopening is not None: |
| 104 |
if isinstance(chksum_after_reopening, list): |
| 105 |
self.chksum_after_reopening = chksum_after_reopening |
| 106 |
else: |
| 107 |
self.chksum_after_reopening = [chksum_after_reopening] |
| 108 |
elif chksum is None: |
| 109 |
self.chksum_after_reopening = None |
| 110 |
else: |
| 111 |
self.chksum_after_reopening = [chksum] |
| 112 |
self.xoff = xoff |
| 113 |
self.yoff = yoff |
| 114 |
self.xsize = xsize |
| 115 |
self.ysize = ysize |
| 116 |
self.options = [] if options is None else options |
| 117 |
self.open_options = open_options |
| 118 |
|
| 119 |
def testDriver(self): |
| 120 |
if self.driver is None: |
| 121 |
self.driver = gdal.GetDriverByName(self.drivername) |
| 122 |
if self.driver is None: |
| 123 |
pytest.skip(self.drivername + " driver not found!") |
| 124 |
|
| 125 |
def testOpen( |
| 126 |
self, |
| 127 |
check_prj=None, |
| 128 |
check_gt=None, |
| 129 |
gt_epsilon=None, |
| 130 |
check_stat=None, |
| 131 |
check_approx_stat=None, |
| 132 |
stat_epsilon=None, |
| 133 |
skip_checksum=None, |
| 134 |
check_min=None, |
| 135 |
check_max=None, |
| 136 |
check_filelist=True, |
| 137 |
): |
| 138 |
"""check_prj - projection reference, check_gt - geotransformation |
| 139 |
matrix (tuple), gt_epsilon - geotransformation tolerance, |
| 140 |
check_stat - band statistics (tuple), stat_epsilon - statistics |
| 141 |
tolerance.""" |
| 142 |
self.testDriver() |
| 143 |
|
| 144 |
if self.filename_absolute: |
| 145 |
wrk_filename = self.filename |
| 146 |
else: |
| 147 |
wrk_filename = "data/" + self.filename |
| 148 |
|
| 149 |
if self.open_options: |
| 150 |
ds = gdal.OpenEx( |
| 151 |
wrk_filename, gdal.OF_RASTER, open_options=self.open_options |
| 152 |
) |
| 153 |
else: |
| 154 |
ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) |
| 155 |
|
| 156 |
assert ds is not None, "Failed to open dataset: " + wrk_filename |
| 157 |
|
| 158 |
assert ( |
| 159 |
ds.GetDriver().ShortName == gdal.GetDriverByName(self.drivername).ShortName |
| 160 |
), "The driver of the returned dataset is %s instead of %s." % ( |
| 161 |
ds.GetDriver().ShortName, |
| 162 |
self.drivername, |
| 163 |
) |
| 164 |
|
| 165 |
if self.xsize == 0 and self.ysize == 0: |
| 166 |
self.xsize = ds.RasterXSize |
| 167 |
self.ysize = ds.RasterYSize |
| 168 |
|
| 169 |
if ( |
| 170 |
check_filelist |
| 171 |
and ds.GetDriver().GetMetadataItem("DCAP_VIRTUALIO") is not None |
| 172 |
): |
| 173 |
fl = ds.GetFileList() |
| 174 |
if fl is not None and fl and wrk_filename == fl[0]: |
| 175 |
|
| 176 |
# Copy all files in /vsimem/ |
| 177 |
mainfile_dirname = os.path.dirname(fl[0]) |
| 178 |
for filename in fl: |
| 179 |
target_filename = ( |
| 180 |
"/vsimem/tmp_testOpen/" + filename[len(mainfile_dirname) + 1 :] |
| 181 |
) |
| 182 |
if stat.S_ISDIR(gdal.VSIStatL(filename).mode): |
| 183 |
gdal.Mkdir(target_filename, 0) |
| 184 |
else: |
| 185 |
f = gdal.VSIFOpenL(filename, "rb") |
| 186 |
assert f is not None, "File %s does not exist" % filename |
| 187 |
gdal.VSIFSeekL(f, 0, 2) |
| 188 |
size = gdal.VSIFTellL(f) |
| 189 |
gdal.VSIFSeekL(f, 0, 0) |
| 190 |
data = gdal.VSIFReadL(1, size, f) |
| 191 |
gdal.VSIFCloseL(f) |
| 192 |
if data is None: |
| 193 |
data = "" |
| 194 |
gdal.FileFromMemBuffer(target_filename, data) |
| 195 |
|
| 196 |
# Try to open the in-memory file |
| 197 |
main_virtual_filename = "/vsimem/tmp_testOpen/" + os.path.basename( |
| 198 |
fl[0] |
| 199 |
) |
| 200 |
virtual_ds = gdal.Open(main_virtual_filename) |
| 201 |
virtual_ds_is_None = virtual_ds is None |
| 202 |
virtual_ds = None |
| 203 |
|
| 204 |
# Make sure the driver is specific enough by trying to open |
| 205 |
# with all other drivers but it |
| 206 |
drivers = [] |
| 207 |
for i in range(gdal.GetDriverCount()): |
| 208 |
drv_name = gdal.GetDriver(i).ShortName |
| 209 |
if drv_name.lower() != self.drivername.lower() and not ( |
| 210 |
( |
| 211 |
drv_name.lower() == "gif" |
| 212 |
and self.drivername.lower() == "biggif" |
| 213 |
) |
| 214 |
or ( |
| 215 |
drv_name.lower() == "biggif" |
| 216 |
and self.drivername.lower() == "gif" |
| 217 |
) |
| 218 |
): |
| 219 |
drivers += [drv_name] |
| 220 |
other_ds = None |
| 221 |
with gdal.ExceptionMgr(useExceptions=False): |
| 222 |
other_ds = gdal.OpenEx( |
| 223 |
main_virtual_filename, gdal.OF_RASTER, allowed_drivers=drivers |
| 224 |
) |
| 225 |
other_ds_is_None = other_ds is None |
| 226 |
other_ds_driver_name = None |
| 227 |
if not other_ds_is_None: |
| 228 |
other_ds_driver_name = other_ds.GetDriver().ShortName |
| 229 |
other_ds = None |
| 230 |
|
| 231 |
for filename in gdal.ReadDirRecursive("/vsimem/tmp_testOpen"): |
| 232 |
gdal.Unlink("/vsimem/tmp_testOpen/" + filename) |
| 233 |
|
| 234 |
assert ( |
| 235 |
not virtual_ds_is_None |
| 236 |
), "File list is not complete or driver does not support /vsimem/" |
| 237 |
assert ( |
| 238 |
other_ds_is_None |
| 239 |
), "When excluding %s, dataset is still opened by driver %s" % ( |
| 240 |
self.drivername, |
| 241 |
other_ds_driver_name, |
| 242 |
) |
| 243 |
|
| 244 |
# Do we need to check projection? |
| 245 |
if check_prj is not None: |
| 246 |
new_prj = ds.GetProjection() |
| 247 |
|
| 248 |
src_osr = osr.SpatialReference() |
| 249 |
src_osr.SetFromUserInput(check_prj) |
| 250 |
|
| 251 |
new_osr = osr.SpatialReference(wkt=new_prj) |
| 252 |
|
| 253 |
if not src_osr.IsSame(new_osr): |
| 254 |
print("") |
| 255 |
print("old = %s" % src_osr.ExportToPrettyWkt()) |
| 256 |
print("new = %s" % new_osr.ExportToPrettyWkt()) |
| 257 |
pytest.fail("Projections differ") |
| 258 |
|
| 259 |
# Do we need to check geotransform? |
| 260 |
if check_gt: |
| 261 |
# Default to 100th of pixel as our test value. |
| 262 |
if gt_epsilon is None: |
| 263 |
gt_epsilon = (abs(check_gt[1]) + abs(check_gt[2])) / 100.0 |
| 264 |
|
| 265 |
new_gt = ds.GetGeoTransform() |
| 266 |
for i in range(6): |
| 267 |
if new_gt[i] != pytest.approx(check_gt[i], abs=gt_epsilon): |
| 268 |
print("") |
| 269 |
print("old = ", check_gt) |
| 270 |
print("new = ", new_gt) |
| 271 |
pytest.fail("Geotransform differs.") |
| 272 |
|
| 273 |
oBand = ds.GetRasterBand(self.band) |
| 274 |
if skip_checksum is None: |
| 275 |
chksum = oBand.Checksum(self.xoff, self.yoff, self.xsize, self.ysize) |
| 276 |
|
| 277 |
# Do we need to check approximate statistics? |
| 278 |
if check_approx_stat: |
| 279 |
# Default to 1000th of pixel value range as our test value. |
| 280 |
if stat_epsilon is None: |
| 281 |
stat_epsilon = abs(check_approx_stat[1] - check_approx_stat[0]) / 1000.0 |
| 282 |
|
| 283 |
new_stat = oBand.GetStatistics(1, 1) |
| 284 |
for i in range(4): |
| 285 |
|
| 286 |
# NOTE - mloskot: Poor man Nan/Inf value check. It's poor |
| 287 |
# because we need to support old and buggy Python 2.3. |
| 288 |
# Tested on Linux, Mac OS X and Windows, with Python 2.3/2.4/2.5. |
| 289 |
sv = str(new_stat[i]).lower() |
| 290 |
assert not ("n" in sv or "i" in sv or "#" in sv), ( |
| 291 |
"NaN or infinity value encountered '%s'." % sv |
| 292 |
) |
| 293 |
|
| 294 |
if new_stat[i] != pytest.approx(check_approx_stat[i], abs=stat_epsilon): |
| 295 |
print("") |
| 296 |
print("old = ", check_approx_stat) |
| 297 |
print("new = ", new_stat) |
| 298 |
pytest.fail("Approximate statistics differs.") |
| 299 |
|
| 300 |
# Do we need to check statistics? |
| 301 |
if check_stat: |
| 302 |
# Default to 1000th of pixel value range as our test value. |
| 303 |
if stat_epsilon is None: |
| 304 |
stat_epsilon = abs(check_stat[1] - check_stat[0]) / 1000.0 |
| 305 |
|
| 306 |
# FIXME: how to test approximate statistic results? |
| 307 |
new_stat = oBand.GetStatistics(1, 1) |
| 308 |
|
| 309 |
new_stat = oBand.GetStatistics(0, 1) |
| 310 |
for i in range(4): |
| 311 |
|
| 312 |
sv = str(new_stat[i]).lower() |
| 313 |
assert not ("n" in sv or "i" in sv or "#" in sv), ( |
| 314 |
"NaN or infinity value encountered '%s'." % sv |
| 315 |
) |
| 316 |
|
| 317 |
if new_stat[i] != pytest.approx(check_stat[i], abs=stat_epsilon): |
| 318 |
print("") |
| 319 |
print("old = ", check_stat) |
| 320 |
print("new = ", new_stat) |
| 321 |
pytest.fail("Statistics differs.") |
| 322 |
|
| 323 |
if check_min: |
| 324 |
assert oBand.GetMinimum() == check_min, "Unexpected minimum value %s" % str( |
| 325 |
oBand.GetMinimum() |
| 326 |
) |
| 327 |
|
| 328 |
if check_max: |
| 329 |
assert oBand.GetMaximum() == check_max, "Unexpected maximum value %s" % str( |
| 330 |
oBand.GetMaximum() |
| 331 |
) |
| 332 |
|
| 333 |
ds = None |
| 334 |
|
| 335 |
assert not is_file_open(wrk_filename), "file still open after dataset closing" |
| 336 |
|
| 337 |
if skip_checksum is not None: |
| 338 |
return |
| 339 |
if self.chksum is None or chksum == self.chksum: |
| 340 |
return |
| 341 |
pytest.fail( |
| 342 |
'Checksum for band %d in "%s" is %d, but expected %d.' |
| 343 |
% (self.band, self.filename, chksum, self.chksum) |
| 344 |
) |
| 345 |
|
| 346 |
def testCreateCopy( |
| 347 |
self, |
| 348 |
check_minmax=1, |
| 349 |
check_gt=0, |
| 350 |
check_srs=None, |
| 351 |
vsimem=0, |
| 352 |
new_filename=None, |
| 353 |
strict_in=0, |
| 354 |
skip_preclose_test=0, |
| 355 |
delete_copy=1, |
| 356 |
gt_epsilon=None, |
| 357 |
check_checksum_not_null=None, |
| 358 |
interrupt_during_copy=False, |
| 359 |
dest_open_options=None, |
| 360 |
quiet_error_handler=True, |
| 361 |
): |
| 362 |
|
| 363 |
self.testDriver() |
| 364 |
|
| 365 |
if self.filename_absolute: |
| 366 |
wrk_filename = self.filename |
| 367 |
else: |
| 368 |
wrk_filename = "data/" + self.filename |
| 369 |
|
| 370 |
if self.open_options: |
| 371 |
src_ds = gdal.OpenEx( |
| 372 |
wrk_filename, gdal.OF_RASTER, open_options=self.open_options |
| 373 |
) |
| 374 |
else: |
| 375 |
src_ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) |
| 376 |
|
| 377 |
if self.band > 0: |
| 378 |
minmax = src_ds.GetRasterBand(self.band).ComputeRasterMinMax() |
| 379 |
|
| 380 |
src_gt = src_ds.GetGeoTransform() |
| 381 |
|
| 382 |
if new_filename is None: |
| 383 |
if vsimem: |
| 384 |
new_filename = "/vsimem/" + os.path.basename(self.filename) + ".tst" |
| 385 |
else: |
| 386 |
new_filename = "tmp/" + os.path.basename(self.filename) + ".tst" |
| 387 |
|
| 388 |
if quiet_error_handler: |
| 389 |
gdal.PushErrorHandler("CPLQuietErrorHandler") |
| 390 |
if interrupt_during_copy: |
| 391 |
new_ds = self.driver.CreateCopy( |
| 392 |
new_filename, |
| 393 |
src_ds, |
| 394 |
strict=strict_in, |
| 395 |
options=self.options, |
| 396 |
callback=testCreateCopyInterruptCallback, |
| 397 |
) |
| 398 |
else: |
| 399 |
new_ds = self.driver.CreateCopy( |
| 400 |
new_filename, src_ds, strict=strict_in, options=self.options |
| 401 |
) |
| 402 |
if quiet_error_handler: |
| 403 |
gdal.PopErrorHandler() |
| 404 |
|
| 405 |
if interrupt_during_copy: |
| 406 |
if new_ds is None: |
| 407 |
with error_handler(): |
| 408 |
self.driver.Delete(new_filename) |
| 409 |
return |
| 410 |
new_ds = None |
| 411 |
self.driver.Delete(new_filename) |
| 412 |
pytest.fail("CreateCopy() should have failed due to interruption") |
| 413 |
|
| 414 |
assert new_ds is not None, ( |
| 415 |
"Failed to create test file using CreateCopy method." |
| 416 |
+ "\n" |
| 417 |
+ gdal.GetLastErrorMsg() |
| 418 |
) |
| 419 |
|
| 420 |
assert ( |
| 421 |
new_ds.GetDriver().ShortName |
| 422 |
== gdal.GetDriverByName(self.drivername).ShortName |
| 423 |
), "The driver of the returned dataset is %s instead of %s." % ( |
| 424 |
new_ds.GetDriver().ShortName, |
| 425 |
self.drivername, |
| 426 |
) |
| 427 |
|
| 428 |
if self.band > 0 and skip_preclose_test == 0: |
| 429 |
bnd = new_ds.GetRasterBand(self.band) |
| 430 |
if check_checksum_not_null is True: |
| 431 |
assert bnd.Checksum() != 0, "Got null checksum on still-open file." |
| 432 |
elif self.chksum is not None and bnd.Checksum() != self.chksum: |
| 433 |
pytest.fail( |
| 434 |
"Did not get expected checksum on still-open file.\n" |
| 435 |
" Got %d instead of %d." % (bnd.Checksum(), self.chksum) |
| 436 |
) |
| 437 |
if check_minmax: |
| 438 |
got_minmax = bnd.ComputeRasterMinMax() |
| 439 |
assert got_minmax == minmax, ( |
| 440 |
"Did not get expected min/max values on still-open file.\n" |
| 441 |
" Got %g,%g instead of %g,%g." |
| 442 |
% (got_minmax[0], got_minmax[1], minmax[0], minmax[1]) |
| 443 |
) |
| 444 |
|
| 445 |
bnd = None |
| 446 |
new_ds = None |
| 447 |
|
| 448 |
# hopefully it's closed now! |
| 449 |
|
| 450 |
if dest_open_options is not None: |
| 451 |
new_ds = gdal.OpenEx( |
| 452 |
new_filename, gdal.OF_RASTER, open_options=dest_open_options |
| 453 |
) |
| 454 |
else: |
| 455 |
new_ds = gdal.Open(new_filename) |
| 456 |
assert new_ds is not None, "Failed to open dataset: " + new_filename |
| 457 |
|
| 458 |
if self.band > 0: |
| 459 |
bnd = new_ds.GetRasterBand(self.band) |
| 460 |
if check_checksum_not_null is True: |
| 461 |
assert bnd.Checksum() != 0, "Got null checksum on reopened file." |
| 462 |
elif ( |
| 463 |
self.chksum_after_reopening is not None |
| 464 |
and bnd.Checksum() not in self.chksum_after_reopening |
| 465 |
): |
| 466 |
pytest.fail( |
| 467 |
"Did not get expected checksum on reopened file.\n" |
| 468 |
" Got %d instead of %s." |
| 469 |
% (bnd.Checksum(), str(self.chksum_after_reopening)) |
| 470 |
) |
| 471 |
|
| 472 |
if check_minmax: |
| 473 |
got_minmax = bnd.ComputeRasterMinMax() |
| 474 |
assert got_minmax == minmax, ( |
| 475 |
"Did not get expected min/max values on reopened file.\n" |
| 476 |
" Got %g,%g instead of %g,%g." |
| 477 |
% (got_minmax[0], got_minmax[1], minmax[0], minmax[1]) |
| 478 |
) |
| 479 |
|
| 480 |
# Do we need to check the geotransform? |
| 481 |
if check_gt: |
| 482 |
if gt_epsilon is None: |
| 483 |
eps = 0.00000001 |
| 484 |
else: |
| 485 |
eps = gt_epsilon |
| 486 |
new_gt = new_ds.GetGeoTransform() |
| 487 |
if ( |
| 488 |
new_gt[0] != pytest.approx(src_gt[0], abs=eps) |
| 489 |
or new_gt[1] != pytest.approx(src_gt[1], abs=eps) |
| 490 |
or new_gt[2] != pytest.approx(src_gt[2], abs=eps) |
| 491 |
or new_gt[3] != pytest.approx(src_gt[3], abs=eps) |
| 492 |
or new_gt[4] != pytest.approx(src_gt[4], abs=eps) |
| 493 |
or new_gt[5] != pytest.approx(src_gt[5], abs=eps) |
| 494 |
): |
| 495 |
print("") |
| 496 |
print("old = ", src_gt) |
| 497 |
print("new = ", new_gt) |
| 498 |
pytest.fail("Geotransform differs.") |
| 499 |
|
| 500 |
# Do we need to check the SRS? |
| 501 |
if check_srs == True: |
| 502 |
src_srs = src_ds.GetSpatialRef() |
| 503 |
new_srs = new_ds.GetSpatialRef() |
| 504 |
if src_srs is None and new_srs is not None: |
| 505 |
pytest.fail("src_srs is None and new_srs is not None") |
| 506 |
elif src_srs is not None and new_srs is None: |
| 507 |
pytest.fail("src_srs is not None and new_srs is None") |
| 508 |
elif ( |
| 509 |
src_srs is not None |
| 510 |
and new_srs is not None |
| 511 |
and not src_srs.IsSame(new_srs) |
| 512 |
): |
| 513 |
print("") |
| 514 |
print("old = %s" % src_srs.ExportToPrettyWkt()) |
| 515 |
print("new = %s" % new_srs.ExportToPrettyWkt()) |
| 516 |
pytest.fail("Projections differ") |
| 517 |
elif check_srs is not None: |
| 518 |
new_prj = new_ds.GetProjection() |
| 519 |
|
| 520 |
src_osr = osr.SpatialReference(wkt=src_ds.GetProjection()) |
| 521 |
new_osr = osr.SpatialReference(wkt=new_prj) |
| 522 |
|
| 523 |
if not src_osr.IsSame(new_osr): |
| 524 |
print("") |
| 525 |
print("old = %s" % src_osr.ExportToPrettyWkt()) |
| 526 |
print("new = %s" % new_osr.ExportToPrettyWkt()) |
| 527 |
pytest.fail("Projections differ") |
| 528 |
|
| 529 |
bnd = None |
| 530 |
new_ds = None |
| 531 |
src_ds = None |
| 532 |
|
| 533 |
if gdal.GetConfigOption("CPL_DEBUG", "OFF") != "ON" and delete_copy == 1: |
| 534 |
self.driver.Delete(new_filename) |
| 535 |
|
| 536 |
def testCreate( |
| 537 |
self, |
| 538 |
vsimem=0, |
| 539 |
new_filename=None, |
| 540 |
out_bands=1, |
| 541 |
check_minmax=1, |
| 542 |
dest_open_options=None, |
| 543 |
delete_output_file=True, |
| 544 |
): |
| 545 |
self.testDriver() |
| 546 |
|
| 547 |
if self.filename_absolute: |
| 548 |
wrk_filename = self.filename |
| 549 |
else: |
| 550 |
wrk_filename = "data/" + self.filename |
| 551 |
|
| 552 |
if self.open_options: |
| 553 |
src_ds = gdal.OpenEx( |
| 554 |
wrk_filename, gdal.OF_RASTER, open_options=self.open_options |
| 555 |
) |
| 556 |
else: |
| 557 |
src_ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) |
| 558 |
|
| 559 |
xsize = src_ds.RasterXSize |
| 560 |
ysize = src_ds.RasterYSize |
| 561 |
src_img = src_ds.GetRasterBand(self.band).ReadRaster(0, 0, xsize, ysize) |
| 562 |
minmax = src_ds.GetRasterBand(self.band).ComputeRasterMinMax() |
| 563 |
|
| 564 |
if new_filename is None: |
| 565 |
if vsimem: |
| 566 |
new_filename = "/vsimem/" + self.filename + ".tst" |
| 567 |
else: |
| 568 |
new_filename = "tmp/" + os.path.basename(self.filename) + ".tst" |
| 569 |
|
| 570 |
new_ds = self.driver.Create( |
| 571 |
new_filename, |
| 572 |
xsize, |
| 573 |
ysize, |
| 574 |
out_bands, |
| 575 |
src_ds.GetRasterBand(self.band).DataType, |
| 576 |
options=self.options, |
| 577 |
) |
| 578 |
assert new_ds is not None, "Failed to create test file using Create method." |
| 579 |
|
| 580 |
src_ds = None |
| 581 |
|
| 582 |
try: |
| 583 |
for band in range(1, out_bands + 1): |
| 584 |
new_ds.GetRasterBand(band).WriteRaster(0, 0, xsize, ysize, src_img) |
| 585 |
except Exception: |
| 586 |
pytest.fail("Failed to write raster bands to test file.") |
| 587 |
|
| 588 |
for band in range(1, out_bands + 1): |
| 589 |
assert ( |
| 590 |
self.chksum is None |
| 591 |
or new_ds.GetRasterBand(band).Checksum() == self.chksum |
| 592 |
), ( |
| 593 |
"Did not get expected checksum on still-open file.\n" |
| 594 |
" Got %d instead of %d." |
| 595 |
% (new_ds.GetRasterBand(band).Checksum(), self.chksum) |
| 596 |
) |
| 597 |
|
| 598 |
computed_minmax = new_ds.GetRasterBand(band).ComputeRasterMinMax() |
| 599 |
if computed_minmax != minmax and check_minmax: |
| 600 |
print("expect: ", minmax) |
| 601 |
print("got: ", computed_minmax) |
| 602 |
pytest.fail("Did not get expected min/max values on still-open file.") |
| 603 |
|
| 604 |
new_ds = None |
| 605 |
|
| 606 |
if dest_open_options is not None: |
| 607 |
new_ds = gdal.OpenEx( |
| 608 |
new_filename, gdal.OF_RASTER, open_options=dest_open_options |
| 609 |
) |
| 610 |
else: |
| 611 |
new_ds = gdal.Open(new_filename) |
| 612 |
assert new_ds is not None, "Failed to open dataset: " + new_filename |
| 613 |
|
| 614 |
for band in range(1, out_bands + 1): |
| 615 |
assert ( |
| 616 |
self.chksum is None |
| 617 |
or new_ds.GetRasterBand(band).Checksum() == self.chksum |
| 618 |
), ( |
| 619 |
"Did not get expected checksum on reopened file." |
| 620 |
" Got %d instead of %d." |
| 621 |
% (new_ds.GetRasterBand(band).Checksum(), self.chksum) |
| 622 |
) |
| 623 |
|
| 624 |
assert ( |
| 625 |
new_ds.GetRasterBand(band).ComputeRasterMinMax() == minmax |
| 626 |
or not check_minmax |
| 627 |
), "Did not get expected min/max values on reopened file." |
| 628 |
|
| 629 |
assert new_ds.FlushCache() == gdal.CE_None |
| 630 |
new_ds = None |
| 631 |
|
| 632 |
if delete_output_file and gdal.GetConfigOption("CPL_DEBUG", "OFF") != "ON": |
| 633 |
self.driver.Delete(new_filename) |
| 634 |
|
| 635 |
def testSetGeoTransform(self): |
| 636 |
self.testDriver() |
| 637 |
|
| 638 |
wrk_filename = "data/" + self.filename |
| 639 |
if self.open_options: |
| 640 |
src_ds = gdal.OpenEx( |
| 641 |
wrk_filename, gdal.OF_RASTER, open_options=self.open_options |
| 642 |
) |
| 643 |
else: |
| 644 |
src_ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) |
| 645 |
|
| 646 |
xsize = src_ds.RasterXSize |
| 647 |
ysize = src_ds.RasterYSize |
| 648 |
|
| 649 |
new_filename = "tmp/" + os.path.basename(self.filename) + ".tst" |
| 650 |
new_ds = self.driver.Create( |
| 651 |
new_filename, |
| 652 |
xsize, |
| 653 |
ysize, |
| 654 |
1, |
| 655 |
src_ds.GetRasterBand(self.band).DataType, |
| 656 |
options=self.options, |
| 657 |
) |
| 658 |
assert new_ds is not None, "Failed to create test file using Create method." |
| 659 |
|
| 660 |
gt = (123.0, 1.18, 0.0, 456.0, 0.0, -1.18) |
| 661 |
assert ( |
| 662 |
new_ds.SetGeoTransform(gt) is gdal.CE_None |
| 663 |
), "Failed to set geographic transformation." |
| 664 |
|
| 665 |
src_ds = None |
| 666 |
new_ds = None |
| 667 |
|
| 668 |
new_ds = gdal.Open(new_filename) |
| 669 |
assert new_ds is not None, "Failed to open dataset: " + new_filename |
| 670 |
|
| 671 |
eps = 0.00000001 |
| 672 |
new_gt = new_ds.GetGeoTransform() |
| 673 |
if ( |
| 674 |
new_gt[0] != pytest.approx(gt[0], abs=eps) |
| 675 |
or new_gt[1] != pytest.approx(gt[1], abs=eps) |
| 676 |
or new_gt[2] != pytest.approx(gt[2], abs=eps) |
| 677 |
or new_gt[3] != pytest.approx(gt[3], abs=eps) |
| 678 |
or new_gt[4] != pytest.approx(gt[4], abs=eps) |
| 679 |
or new_gt[5] != pytest.approx(gt[5], abs=eps) |
| 680 |
): |
| 681 |
print("") |
| 682 |
print("old = ", gt) |
| 683 |
print("new = ", new_gt) |
| 684 |
pytest.fail("Did not get expected geotransform.") |
| 685 |
|
| 686 |
new_ds = None |
| 687 |
|
| 688 |
if gdal.GetConfigOption("CPL_DEBUG", "OFF") != "ON": |
| 689 |
self.driver.Delete(new_filename) |
| 690 |
|
| 691 |
def testSetProjection(self, prj=None, expected_prj=None): |
| 692 |
self.testDriver() |
| 693 |
|
| 694 |
wrk_filename = "data/" + self.filename |
| 695 |
if self.open_options: |
| 696 |
src_ds = gdal.OpenEx( |
| 697 |
wrk_filename, gdal.OF_RASTER, open_options=self.open_options |
| 698 |
) |
| 699 |
else: |
| 700 |
src_ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) |
| 701 |
|
| 702 |
xsize = src_ds.RasterXSize |
| 703 |
ysize = src_ds.RasterYSize |
| 704 |
|
| 705 |
new_filename = "tmp/" + os.path.basename(self.filename) + ".tst" |
| 706 |
new_ds = self.driver.Create( |
| 707 |
new_filename, |
| 708 |
xsize, |
| 709 |
ysize, |
| 710 |
1, |
| 711 |
src_ds.GetRasterBand(self.band).DataType, |
| 712 |
options=self.options, |
| 713 |
) |
| 714 |
assert new_ds is not None, "Failed to create test file using Create method." |
| 715 |
|
| 716 |
gt = (123.0, 1.18, 0.0, 456.0, 0.0, -1.18) |
| 717 |
if prj is None: |
| 718 |
# This is a challenging SRS since it has non-meter linear units. |
| 719 |
prj = 'PROJCS["NAD83 / Ohio South",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",40.03333333333333],PARAMETER["standard_parallel_2",38.73333333333333],PARAMETER["latitude_of_origin",38],PARAMETER["central_meridian",-82.5],PARAMETER["false_easting",1968500],PARAMETER["false_northing",0],UNIT["US survey foot",0.3048006096012192]]' |
| 720 |
|
| 721 |
src_osr = osr.SpatialReference() |
| 722 |
src_osr.ImportFromWkt(prj) |
| 723 |
|
| 724 |
new_ds.SetGeoTransform(gt) |
| 725 |
assert ( |
| 726 |
new_ds.SetProjection(prj) is gdal.CE_None |
| 727 |
), "Failed to set geographic projection string." |
| 728 |
|
| 729 |
src_ds = None |
| 730 |
new_ds = None |
| 731 |
|
| 732 |
new_ds = gdal.Open(new_filename) |
| 733 |
assert new_ds is not None, "Failed to open dataset: " + new_filename |
| 734 |
|
| 735 |
expected_osr = osr.SpatialReference() |
| 736 |
if expected_prj is None: |
| 737 |
expected_osr = src_osr |
| 738 |
else: |
| 739 |
expected_osr.ImportFromWkt(expected_prj) |
| 740 |
|
| 741 |
new_osr = osr.SpatialReference() |
| 742 |
new_osr.ImportFromWkt(new_ds.GetProjection()) |
| 743 |
if not new_osr.IsSame(expected_osr): |
| 744 |
print("Got: ") |
| 745 |
print(new_osr.ExportToPrettyWkt()) |
| 746 |
print("Expected:") |
| 747 |
print(expected_osr.ExportToPrettyWkt()) |
| 748 |
pytest.fail("Did not get expected projection reference.") |
| 749 |
|
| 750 |
new_ds = None |
| 751 |
|
| 752 |
if gdal.GetConfigOption("CPL_DEBUG", "OFF") != "ON": |
| 753 |
self.driver.Delete(new_filename) |
| 754 |
|
| 755 |
def testSetMetadata(self): |
| 756 |
self.testDriver() |
| 757 |
|
| 758 |
wrk_filename = "data/" + self.filename |
| 759 |
if self.open_options: |
| 760 |
src_ds = gdal.OpenEx( |
| 761 |
wrk_filename, gdal.OF_RASTER, open_options=self.open_options |
| 762 |
) |
| 763 |
else: |
| 764 |
src_ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) |
| 765 |
|
| 766 |
xsize = src_ds.RasterXSize |
| 767 |
ysize = src_ds.RasterYSize |
| 768 |
|
| 769 |
new_filename = "tmp/" + os.path.basename(self.filename) + ".tst" |
| 770 |
new_ds = self.driver.Create( |
| 771 |
new_filename, |
| 772 |
xsize, |
| 773 |
ysize, |
| 774 |
1, |
| 775 |
src_ds.GetRasterBand(self.band).DataType, |
| 776 |
options=self.options, |
| 777 |
) |
| 778 |
assert new_ds is not None, "Failed to create test file using Create method." |
| 779 |
|
| 780 |
new_ds.SetMetadata({"TEST_KEY": "TestValue"}) |
| 781 |
# FIXME |
| 782 |
# if new_ds.SetMetadata( dict ) is not gdal.CE_None: |
| 783 |
# print new_ds.SetMetadata( dict ) |
| 784 |
# post_reason( 'Failed to set metadata item.' ) |
| 785 |
# return 'fail' |
| 786 |
|
| 787 |
src_ds = None |
| 788 |
new_ds = None |
| 789 |
|
| 790 |
new_ds = gdal.Open(new_filename) |
| 791 |
assert new_ds is not None, "Failed to open dataset: " + new_filename |
| 792 |
|
| 793 |
md_dict = new_ds.GetMetadata() |
| 794 |
|
| 795 |
assert "TEST_KEY" in md_dict, "Metadata item TEST_KEY does not exist." |
| 796 |
|
| 797 |
assert md_dict["TEST_KEY"] == "TestValue", "Did not get expected metadata item." |
| 798 |
|
| 799 |
new_ds = None |
| 800 |
|
| 801 |
if gdal.GetConfigOption("CPL_DEBUG", "OFF") != "ON": |
| 802 |
self.driver.Delete(new_filename) |
| 803 |
|
| 804 |
def testSetNoDataValue(self, delete=False): |
| 805 |
self.testDriver() |
| 806 |
|
| 807 |
wrk_filename = "data/" + self.filename |
| 808 |
if self.open_options: |
| 809 |
src_ds = gdal.OpenEx( |
| 810 |
wrk_filename, gdal.OF_RASTER, open_options=self.open_options |
| 811 |
) |
| 812 |
else: |
| 813 |
src_ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) |
| 814 |
|
| 815 |
xsize = src_ds.RasterXSize |
| 816 |
ysize = src_ds.RasterYSize |
| 817 |
|
| 818 |
new_filename = "tmp/" + os.path.basename(self.filename) + ".tst" |
| 819 |
dt = src_ds.GetRasterBand(self.band).DataType |
| 820 |
new_ds = self.driver.Create( |
| 821 |
new_filename, |
| 822 |
xsize, |
| 823 |
ysize, |
| 824 |
1, |
| 825 |
dt, |
| 826 |
options=self.options, |
| 827 |
) |
| 828 |
assert new_ds is not None, "Failed to create test file using Create method." |
| 829 |
|
| 830 |
if dt == gdal.GDT_Int8: |
| 831 |
nodata = -11 |
| 832 |
elif self.options is None or "PIXELTYPE=SIGNEDBYTE" not in self.options: |
| 833 |
nodata = 130 |
| 834 |
else: |
| 835 |
nodata = 11 |
| 836 |
assert ( |
| 837 |
new_ds.GetRasterBand(1).SetNoDataValue(nodata) is gdal.CE_None |
| 838 |
), "Failed to set NoData value." |
| 839 |
|
| 840 |
src_ds = None |
| 841 |
new_ds = None |
| 842 |
|
| 843 |
if delete: |
| 844 |
mode = gdal.GA_Update |
| 845 |
else: |
| 846 |
mode = gdal.GA_ReadOnly |
| 847 |
new_ds = gdal.Open(new_filename, mode) |
| 848 |
assert new_ds is not None, "Failed to open dataset: " + new_filename |
| 849 |
|
| 850 |
assert ( |
| 851 |
nodata == new_ds.GetRasterBand(1).GetNoDataValue() |
| 852 |
), "Did not get expected NoData value." |
| 853 |
|
| 854 |
if delete: |
| 855 |
assert ( |
| 856 |
new_ds.GetRasterBand(1).DeleteNoDataValue() == 0 |
| 857 |
), "Did not manage to delete nodata value" |
| 858 |
|
| 859 |
new_ds = None |
| 860 |
|
| 861 |
if delete: |
| 862 |
new_ds = gdal.Open(new_filename) |
| 863 |
assert ( |
| 864 |
new_ds.GetRasterBand(1).GetNoDataValue() is None |
| 865 |
), "Got nodata value whereas none was expected" |
| 866 |
new_ds = None |
| 867 |
|
| 868 |
if gdal.GetConfigOption("CPL_DEBUG", "OFF") != "ON": |
| 869 |
self.driver.Delete(new_filename) |
| 870 |
|
| 871 |
def testSetNoDataValueAndDelete(self): |
| 872 |
self.testSetNoDataValue(delete=True) |
| 873 |
|
| 874 |
def testSetDescription(self): |
| 875 |
self.testDriver() |
| 876 |
|
| 877 |
wrk_filename = "data/" + self.filename |
| 878 |
if self.open_options: |
| 879 |
src_ds = gdal.OpenEx( |
| 880 |
wrk_filename, gdal.OF_RASTER, open_options=self.open_options |
| 881 |
) |
| 882 |
else: |
| 883 |
src_ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) |
| 884 |
|
| 885 |
xsize = src_ds.RasterXSize |
| 886 |
ysize = src_ds.RasterYSize |
| 887 |
|
| 888 |
new_filename = "tmp/" + os.path.basename(self.filename) + ".tst" |
| 889 |
new_ds = self.driver.Create( |
| 890 |
new_filename, |
| 891 |
xsize, |
| 892 |
ysize, |
| 893 |
1, |
| 894 |
src_ds.GetRasterBand(self.band).DataType, |
| 895 |
options=self.options, |
| 896 |
) |
| 897 |
assert new_ds is not None, "Failed to create test file using Create method." |
| 898 |
|
| 899 |
description = "Description test string" |
| 900 |
new_ds.GetRasterBand(1).SetDescription(description) |
| 901 |
|
| 902 |
src_ds = None |
| 903 |
new_ds = None |
| 904 |
|
| 905 |
new_ds = gdal.Open(new_filename) |
| 906 |
assert new_ds is not None, "Failed to open dataset: " + new_filename |
| 907 |
|
| 908 |
assert ( |
| 909 |
description == new_ds.GetRasterBand(1).GetDescription() |
| 910 |
), "Did not get expected description string." |
| 911 |
|
| 912 |
new_ds = None |
| 913 |
|
| 914 |
if gdal.GetConfigOption("CPL_DEBUG", "OFF") != "ON": |
| 915 |
self.driver.Delete(new_filename) |
| 916 |
|
| 917 |
def testSetUnitType(self): |
| 918 |
self.testDriver() |
| 919 |
|
| 920 |
wrk_filename = "data/" + self.filename |
| 921 |
if self.open_options: |
| 922 |
src_ds = gdal.OpenEx( |
| 923 |
wrk_filename, gdal.OF_RASTER, open_options=self.open_options |
| 924 |
) |
| 925 |
else: |
| 926 |
src_ds = gdal.Open(wrk_filename, gdal.GA_ReadOnly) |
| 927 |
|
| 928 |
xsize = src_ds.RasterXSize |
| 929 |
ysize = src_ds.RasterYSize |
| 930 |
|
| 931 |
new_filename = "tmp/" + os.path.basename(self.filename) + ".tst" |
| 932 |
new_ds = self.driver.Create( |
| 933 |
new_filename, |
| 934 |
xsize, |
| 935 |
ysize, |
| 936 |
1, |
| 937 |
src_ds.GetRasterBand(self.band).DataType, |
| 938 |
options=self.options, |
| 939 |
) |
| 940 |
assert new_ds is not None, "Failed to create test file using Create method." |
| 941 |
|
| 942 |
unit = "mg/m3" |
| 943 |
assert ( |
| 944 |
new_ds.GetRasterBand(1).SetUnitType(unit) is gdal.CE_None |
| 945 |
), "Failed to set unit type." |
| 946 |
|
| 947 |
src_ds = None |
| 948 |
new_ds = None |
| 949 |
|
| 950 |
new_ds = gdal.Open(new_filename) |
| 951 |
assert new_ds is not None, "Failed to open dataset: " + new_filename |
| 952 |
|
| 953 |
new_unit = new_ds.GetRasterBand(1).GetUnitType() |
| 954 |
if new_unit != unit: |
| 955 |
print("") |
| 956 |
print("old = ", unit) |
| 957 |
print("new = ", new_unit) |
| 958 |
pytest.fail("Did not get expected unit type.") |
| 959 |
|
| 960 |
new_ds = None |
| 961 |
|
| 962 |
if gdal.GetConfigOption("CPL_DEBUG", "OFF") != "ON": |
| 963 |
self.driver.Delete(new_filename) |
| 964 |
|
| 965 |
|
| 966 |
def approx_equal(a, b): |
| 967 |
a = float(a) |
| 968 |
b = float(b) |
| 969 |
if a == 0 and b != 0: |
| 970 |
return 0 |
| 971 |
|
| 972 |
if b / a != pytest.approx(1.0, abs=0.00000000001): |
| 973 |
return 0 |
| 974 |
return 1 |
| 975 |
|
| 976 |
|
| 977 |
def user_srs_to_wkt(user_text): |
| 978 |
srs = osr.SpatialReference() |
| 979 |
srs.SetFromUserInput(user_text) |
| 980 |
return srs.ExportToWkt() |
| 981 |
|
| 982 |
|
| 983 |
def equal_srs_from_wkt(expected_wkt, got_wkt, verbose=True): |
| 984 |
expected_srs = osr.SpatialReference() |
| 985 |
expected_srs.SetAxisMappingStrategy(osr.OAMS_AUTHORITY_COMPLIANT) |
| 986 |
expected_srs.ImportFromWkt(expected_wkt) |
| 987 |
|
| 988 |
got_srs = osr.SpatialReference() |
| 989 |
got_srs.SetAxisMappingStrategy(osr.OAMS_AUTHORITY_COMPLIANT) |
| 990 |
got_srs.ImportFromWkt(got_wkt) |
| 991 |
|
| 992 |
if got_srs.IsSame(expected_srs): |
| 993 |
return True |
| 994 |
if verbose: |
| 995 |
print("Expected:\n%s" % expected_wkt) |
| 996 |
print("Got: \n%s" % got_wkt) |
| 997 |
print("SRS differs from expected.") |
| 998 |
return False |
| 999 |
|
| 1000 |
|
| 1001 |
############################################################################### |
| 1002 |
# Compare two sets of RPC metadata, and establish if they are essentially |
| 1003 |
# equivalent or not. |
| 1004 |
|
| 1005 |
|
| 1006 |
def check_rpcs_equal(md1, md2): |
| 1007 |
__tracebackhide__ = True |
| 1008 |
|
| 1009 |
simple_fields = [ |
| 1010 |
"LINE_OFF", |
| 1011 |
"SAMP_OFF", |
| 1012 |
"LAT_OFF", |
| 1013 |
"LONG_OFF", |
| 1014 |
"HEIGHT_OFF", |
| 1015 |
"LINE_SCALE", |
| 1016 |
"SAMP_SCALE", |
| 1017 |
"LAT_SCALE", |
| 1018 |
"LONG_SCALE", |
| 1019 |
"HEIGHT_SCALE", |
| 1020 |
] |
| 1021 |
coef_fields = [ |
| 1022 |
"LINE_NUM_COEFF", |
| 1023 |
"LINE_DEN_COEFF", |
| 1024 |
"SAMP_NUM_COEFF", |
| 1025 |
"SAMP_DEN_COEFF", |
| 1026 |
] |
| 1027 |
|
| 1028 |
for sf in simple_fields: |
| 1029 |
|
| 1030 |
assert sf in md1 |
| 1031 |
assert sf in md2 |
| 1032 |
assert approx_equal(float(md1[sf]), float(md2[sf])) |
| 1033 |
|
| 1034 |
for cf in coef_fields: |
| 1035 |
|
| 1036 |
list1 = md1[cf].split() |
| 1037 |
list2 = md2[cf].split() |
| 1038 |
|
| 1039 |
assert len(list1) == 20, "%s value list length wrong(1)" % cf |
| 1040 |
|
| 1041 |
assert len(list2) == 20, "%s value list length wrong(2)" % cf |
| 1042 |
|
| 1043 |
for i in range(20): |
| 1044 |
assert approx_equal( |
| 1045 |
float(list1[i]), float(list2[i]) |
| 1046 |
), "%s[%d] values differ." % (cf, i) |
| 1047 |
|
| 1048 |
|
| 1049 |
############################################################################### |
| 1050 |
# Test if geotransforms are equal with an epsilon tolerance |
| 1051 |
# |
| 1052 |
|
| 1053 |
|
| 1054 |
def check_geotransform(gt1, gt2, gt_epsilon): |
| 1055 |
__tracebackhide__ = True |
| 1056 |
assert gt1 == pytest.approx(gt2, abs=gt_epsilon), "Geotransform differs." |
| 1057 |
|
| 1058 |
|
| 1059 |
############################################################################### |
| 1060 |
# Download file at url 'url' and put it as 'filename' in 'tmp/cache/' |
| 1061 |
# |
| 1062 |
# If 'filename' already exits in 'tmp/cache/', it is not downloaded |
| 1063 |
# If GDAL_DOWNLOAD_TEST_DATA is not defined, the function fails |
| 1064 |
# If GDAL_DOWNLOAD_TEST_DATA is defined, 'url' is downloaded as 'filename' in 'tmp/cache/' |
| 1065 |
|
| 1066 |
|
| 1067 |
def download_file( |
| 1068 |
url, |
| 1069 |
filename=None, |
| 1070 |
download_size=-1, |
| 1071 |
force_download=False, |
| 1072 |
max_download_duration=None, |
| 1073 |
base_dir="tmp/cache", |
| 1074 |
): |
| 1075 |
|
| 1076 |
if filename is None: |
| 1077 |
filename = os.path.basename(url) |
| 1078 |
elif filename.startswith(base_dir + "/"): |
| 1079 |
filename = filename[len(base_dir + "/") :] |
| 1080 |
|
| 1081 |
if os.path.exists(os.path.join(base_dir, filename)): |
| 1082 |
return True |
| 1083 |
|
| 1084 |
if not (force_download or download_test_data()): |
| 1085 |
return False |
| 1086 |
|
| 1087 |
val = None |
| 1088 |
start_time = time.time() |
| 1089 |
try: |
| 1090 |
handle = gdalurlopen(url) |
| 1091 |
if handle is None: |
| 1092 |
return False |
| 1093 |
if download_size == -1: |
| 1094 |
try: |
| 1095 |
handle_info = handle.info() |
| 1096 |
download_size = int(handle_info["content-length"]) |
| 1097 |
print("Downloading %s (length = %d bytes)..." % (url, download_size)) |
| 1098 |
except Exception: |
| 1099 |
print("Downloading %s..." % (url)) |
| 1100 |
else: |
| 1101 |
print("Downloading %d bytes from %s..." % (download_size, url)) |
| 1102 |
except Exception: |
| 1103 |
return False |
| 1104 |
|
| 1105 |
if download_size >= 0: |
| 1106 |
sys.stdout.write("Progress: ") |
| 1107 |
nLastTick = -1 |
| 1108 |
val = "".encode("ascii") |
| 1109 |
while len(val) < download_size or download_size < 0: |
| 1110 |
chunk_size = 1024 |
| 1111 |
if download_size >= 0 and len(val) + chunk_size > download_size: |
| 1112 |
chunk_size = download_size - len(val) |
| 1113 |
try: |
| 1114 |
chunk = handle.read(chunk_size) |
| 1115 |
except Exception: |
| 1116 |
print("Did not get expected data length.") |
| 1117 |
return False |
| 1118 |
val = val + chunk |
| 1119 |
if len(chunk) < chunk_size: |
| 1120 |
if download_size < 0: |
| 1121 |
break |
| 1122 |
print("Did not get expected data length.") |
| 1123 |
return False |
| 1124 |
if download_size >= 0: |
| 1125 |
nThisTick = int(40 * len(val) / download_size) |
| 1126 |
while nThisTick > nLastTick: |
| 1127 |
nLastTick = nLastTick + 1 |
| 1128 |
if nLastTick % 4 == 0: |
| 1129 |
sys.stdout.write("%d" % int((nLastTick / 4) * 10)) |
| 1130 |
else: |
| 1131 |
sys.stdout.write(".") |
| 1132 |
nLastTick = nThisTick |
| 1133 |
if nThisTick == 40: |
| 1134 |
sys.stdout.write(" - done.\n") |
| 1135 |
|
| 1136 |
current_time = time.time() |
| 1137 |
if ( |
| 1138 |
max_download_duration is not None |
| 1139 |
and current_time - start_time > max_download_duration |
| 1140 |
): |
| 1141 |
print("Download aborted due to timeout.") |
| 1142 |
return False |
| 1143 |
|
| 1144 |
try: |
| 1145 |
os.stat(base_dir) |
| 1146 |
except OSError: |
| 1147 |
os.mkdir(base_dir) |
| 1148 |
|
| 1149 |
try: |
| 1150 |
open(base_dir + "/" + filename, "wb").write(val) |
| 1151 |
return True |
| 1152 |
except IOError: |
| 1153 |
print("Cannot write %s" % (filename)) |
| 1154 |
return False |
| 1155 |
|
| 1156 |
|
| 1157 |
# Attempt to download file using `download_file`; skip test in case of failure |
| 1158 |
def download_or_skip(url, *args, **kwargs): |
| 1159 |
__tracebackhide__ = True |
| 1160 |
|
| 1161 |
msg = io.StringIO() |
| 1162 |
with contextlib.redirect_stdout(msg): |
| 1163 |
success = download_file(url, *args, **kwargs) |
| 1164 |
|
| 1165 |
if not success: |
| 1166 |
if download_test_data(): |
| 1167 |
pytest.skip(f"Failed to download {url} : {msg.getvalue()}") |
| 1168 |
else: |
| 1169 |
pytest.skip("GDAL_DOWNLOAD_TEST_DATA is not set to YES") |
| 1170 |
|
| 1171 |
|
| 1172 |
############################################################################### |
| 1173 |
# GDAL data type to python struct format |
| 1174 |
def gdal_data_type_to_python_struct_format(datatype): |
| 1175 |
type_char = "B" |
| 1176 |
if datatype == gdal.GDT_Int16: |
| 1177 |
type_char = "h" |
| 1178 |
elif datatype == gdal.GDT_UInt16: |
| 1179 |
type_char = "H" |
| 1180 |
elif datatype == gdal.GDT_Int32: |
| 1181 |
type_char = "i" |
| 1182 |
elif datatype == gdal.GDT_UInt32: |
| 1183 |
type_char = "I" |
| 1184 |
elif datatype == gdal.GDT_Float32: |
| 1185 |
type_char = "f" |
| 1186 |
elif datatype == gdal.GDT_Float64: |
| 1187 |
type_char = "d" |
| 1188 |
return type_char |
| 1189 |
|
| 1190 |
|
| 1191 |
############################################################################### |
| 1192 |
# Compare the values of the pixels |
| 1193 |
|
| 1194 |
|
| 1195 |
def compare_ds(ds1, ds2, xoff=0, yoff=0, width=0, height=0, verbose=1): |
| 1196 |
import struct |
| 1197 |
|
| 1198 |
if width == 0: |
| 1199 |
width = ds1.RasterXSize |
| 1200 |
if height == 0: |
| 1201 |
height = ds1.RasterYSize |
| 1202 |
data1 = ds1.GetRasterBand(1).ReadRaster(xoff, yoff, width, height) |
| 1203 |
type_char = gdal_data_type_to_python_struct_format(ds1.GetRasterBand(1).DataType) |
| 1204 |
val_array1 = struct.unpack(type_char * width * height, data1) |
| 1205 |
|
| 1206 |
data2 = ds2.GetRasterBand(1).ReadRaster(xoff, yoff, width, height) |
| 1207 |
type_char = gdal_data_type_to_python_struct_format(ds2.GetRasterBand(1).DataType) |
| 1208 |
val_array2 = struct.unpack(type_char * width * height, data2) |
| 1209 |
|
| 1210 |
maxdiff = 0.0 |
| 1211 |
ndiffs = 0 |
| 1212 |
for i in range(width * height): |
| 1213 |
diff = val_array1[i] - val_array2[i] |
| 1214 |
if diff != 0: |
| 1215 |
# print(val_array1[i]) |
| 1216 |
# print(val_array2[i]) |
| 1217 |
ndiffs = ndiffs + 1 |
| 1218 |
if abs(diff) > maxdiff: |
| 1219 |
maxdiff = abs(diff) |
| 1220 |
if verbose: |
| 1221 |
print( |
| 1222 |
"Diff at pixel (%d, %d) : %f" |
| 1223 |
% (i % width, i / width, float(diff)) |
| 1224 |
) |
| 1225 |
elif ndiffs < 10: |
| 1226 |
if verbose: |
| 1227 |
print( |
| 1228 |
"Diff at pixel (%d, %d) : %f" |
| 1229 |
% (i % width, i / width, float(diff)) |
| 1230 |
) |
| 1231 |
if maxdiff != 0 and verbose: |
| 1232 |
print("Max diff : %d" % (maxdiff)) |
| 1233 |
print("Number of diffs : %d" % (ndiffs)) |
| 1234 |
|
| 1235 |
return maxdiff |
| 1236 |
|
| 1237 |
|
| 1238 |
############################################################################### |
| 1239 |
# Deregister all JPEG2000 drivers, except the one passed as an argument |
| 1240 |
|
| 1241 |
|
| 1242 |
def deregister_all_jpeg2000_drivers_but(name_of_driver_to_keep): |
| 1243 |
global jp2kak_drv, jpeg2000_drv, jp2ecw_drv, jp2mrsid_drv, jp2openjpeg_drv, jp2lura_drv |
| 1244 |
global jp2kak_drv_unregistered, jpeg2000_drv_unregistered, jp2ecw_drv_unregistered, jp2mrsid_drv_unregistered, jp2openjpeg_drv_unregistered, jp2lura_drv_unregistered |
| 1245 |
|
| 1246 |
# Deregister other potential conflicting JPEG2000 drivers that will |
| 1247 |
# be re-registered in the cleanup |
| 1248 |
jp2kak_drv = gdal.GetDriverByName("JP2KAK") |
| 1249 |
if name_of_driver_to_keep != "JP2KAK" and jp2kak_drv: |
| 1250 |
gdal.Debug("gdaltest", "Deregistering JP2KAK") |
| 1251 |
jp2kak_drv.Deregister() |
| 1252 |
jp2kak_drv_unregistered = True |
| 1253 |
|
| 1254 |
jpeg2000_drv = gdal.GetDriverByName("JPEG2000") |
| 1255 |
if name_of_driver_to_keep != "JPEG2000" and jpeg2000_drv: |
| 1256 |
gdal.Debug("gdaltest", "Deregistering JPEG2000") |
| 1257 |
jpeg2000_drv.Deregister() |
| 1258 |
jpeg2000_drv_unregistered = True |
| 1259 |
|
| 1260 |
jp2ecw_drv = gdal.GetDriverByName("JP2ECW") |
| 1261 |
if name_of_driver_to_keep != "JP2ECW" and jp2ecw_drv: |
| 1262 |
gdal.Debug("gdaltest.", "Deregistering JP2ECW") |
| 1263 |
jp2ecw_drv.Deregister() |
| 1264 |
jp2ecw_drv_unregistered = True |
| 1265 |
|
| 1266 |
jp2mrsid_drv = gdal.GetDriverByName("JP2MrSID") |
| 1267 |
if name_of_driver_to_keep != "JP2MrSID" and jp2mrsid_drv: |
| 1268 |
gdal.Debug("gdaltest.", "Deregistering JP2MrSID") |
| 1269 |
jp2mrsid_drv.Deregister() |
| 1270 |
jp2mrsid_drv_unregistered = True |
| 1271 |
|
| 1272 |
jp2openjpeg_drv = gdal.GetDriverByName("JP2OpenJPEG") |
| 1273 |
if name_of_driver_to_keep != "JP2OpenJPEG" and jp2openjpeg_drv: |
| 1274 |
gdal.Debug("gdaltest.", "Deregistering JP2OpenJPEG") |
| 1275 |
jp2openjpeg_drv.Deregister() |
| 1276 |
jp2openjpeg_drv_unregistered = True |
| 1277 |
|
| 1278 |
jp2lura_drv = gdal.GetDriverByName("JP2Lura") |
| 1279 |
if name_of_driver_to_keep != "JP2Lura" and jp2lura_drv: |
| 1280 |
gdal.Debug("gdaltest.", "Deregistering JP2Lura") |
| 1281 |
jp2lura_drv.Deregister() |
| 1282 |
jp2lura_drv_unregistered = True |
| 1283 |
|
| 1284 |
return True |
| 1285 |
|
| 1286 |
|
| 1287 |
############################################################################### |
| 1288 |
# Re-register all JPEG2000 drivers previously disabled by |
| 1289 |
# deregister_all_jpeg2000_drivers_but |
| 1290 |
|
| 1291 |
|
| 1292 |
def reregister_all_jpeg2000_drivers(): |
| 1293 |
global jp2kak_drv, jpeg2000_drv, jp2ecw_drv, jp2mrsid_drv, jp2openjpeg_drv, jp2lura_drv |
| 1294 |
global jp2kak_drv_unregistered, jpeg2000_drv_unregistered, jp2ecw_drv_unregistered, jp2mrsid_drv_unregistered, jp2openjpeg_drv_unregistered, jp2lura_drv_unregistered |
| 1295 |
|
| 1296 |
if jp2kak_drv_unregistered: |
| 1297 |
jp2kak_drv.Register() |
| 1298 |
jp2kak_drv_unregistered = False |
| 1299 |
gdal.Debug("gdaltest", "Registering JP2KAK") |
| 1300 |
|
| 1301 |
if jpeg2000_drv_unregistered: |
| 1302 |
jpeg2000_drv.Register() |
| 1303 |
jpeg2000_drv_unregistered = False |
| 1304 |
gdal.Debug("gdaltest", "Registering JPEG2000") |
| 1305 |
|
| 1306 |
if jp2ecw_drv_unregistered: |
| 1307 |
jp2ecw_drv.Register() |
| 1308 |
jp2ecw_drv_unregistered = False |
| 1309 |
gdal.Debug("gdaltest", "Registering JP2ECW") |
| 1310 |
|
| 1311 |
if jp2mrsid_drv_unregistered: |
| 1312 |
jp2mrsid_drv.Register() |
| 1313 |
jp2mrsid_drv_unregistered = False |
| 1314 |
gdal.Debug("gdaltest", "Registering JP2MrSID") |
| 1315 |
|
| 1316 |
if jp2openjpeg_drv_unregistered: |
| 1317 |
jp2openjpeg_drv.Register() |
| 1318 |
jp2openjpeg_drv_unregistered = False |
| 1319 |
gdal.Debug("gdaltest", "Registering JP2OpenJPEG") |
| 1320 |
|
| 1321 |
if jp2lura_drv_unregistered: |
| 1322 |
jp2lura_drv.Register() |
| 1323 |
jp2lura_drv_unregistered = False |
| 1324 |
gdal.Debug("gdaltest", "Registering JP2Lura") |
| 1325 |
|
| 1326 |
return True |
| 1327 |
|
| 1328 |
|
| 1329 |
############################################################################### |
| 1330 |
# Determine if the filesystem supports sparse files. |
| 1331 |
# Currently, this will only work on Linux (or any *NIX that has the stat |
| 1332 |
# command line utility) |
| 1333 |
|
| 1334 |
|
| 1335 |
def filesystem_supports_sparse_files(path): |
| 1336 |
|
| 1337 |
if gdal.GetConfigOption("TRAVIS", None): |
| 1338 |
return False |
| 1339 |
|
| 1340 |
try: |
| 1341 |
(ret, err) = runexternal_out_and_err(f'stat -f -c "%T" {path}') |
| 1342 |
except OSError: |
| 1343 |
return False |
| 1344 |
|
| 1345 |
if err != "": |
| 1346 |
print("Cannot determine if filesystem supports sparse files") |
| 1347 |
return False |
| 1348 |
|
| 1349 |
if "fat32" in ret: |
| 1350 |
print("File system does not support sparse files") |
| 1351 |
return False |
| 1352 |
|
| 1353 |
if "wslfs" in ret or "0x53464846" in ret: |
| 1354 |
# wslfs for older stat versions |
| 1355 |
print( |
| 1356 |
"Windows Subsystem for Linux FS is at the time of " |
| 1357 |
+ "writing not known to support sparse files" |
| 1358 |
) |
| 1359 |
return False |
| 1360 |
|
| 1361 |
# Add here any missing filesystem supporting sparse files |
| 1362 |
# See http://en.wikipedia.org/wiki/Comparison_of_file_systems |
| 1363 |
filesystems_supporting_sparse_files = { |
| 1364 |
"ext3", |
| 1365 |
"ext4", |
| 1366 |
"reiser", |
| 1367 |
"xfs", |
| 1368 |
"jfs", |
| 1369 |
"zfs", |
| 1370 |
"ntfs", |
| 1371 |
} |
| 1372 |
|
| 1373 |
for fs in filesystems_supporting_sparse_files: |
| 1374 |
if fs in ret: |
| 1375 |
return True |
| 1376 |
|
| 1377 |
print("Filesystem %s is not believed to support sparse files" % ret) |
| 1378 |
return False |
| 1379 |
|
| 1380 |
|
| 1381 |
############################################################################### |
| 1382 |
# Unzip a file |
| 1383 |
|
| 1384 |
|
| 1385 |
def unzip(target_dir, zipfilename, verbose=False): |
| 1386 |
|
| 1387 |
try: |
| 1388 |
import zipfile |
| 1389 |
|
| 1390 |
zf = zipfile.ZipFile(zipfilename) |
| 1391 |
except ImportError: |
| 1392 |
os.system("unzip -d " + target_dir + " " + zipfilename) |
| 1393 |
return |
| 1394 |
|
| 1395 |
for filename in zf.namelist(): |
| 1396 |
if verbose: |
| 1397 |
print(filename) |
| 1398 |
outfilename = os.path.join(target_dir, filename) |
| 1399 |
if filename.endswith("/"): |
| 1400 |
if not os.path.exists(outfilename): |
| 1401 |
os.makedirs(outfilename) |
| 1402 |
else: |
| 1403 |
outdirname = os.path.dirname(outfilename) |
| 1404 |
if not os.path.exists(outdirname): |
| 1405 |
os.makedirs(outdirname) |
| 1406 |
|
| 1407 |
outfile = open(outfilename, "wb") |
| 1408 |
outfile.write(zf.read(filename)) |
| 1409 |
outfile.close() |
| 1410 |
|
| 1411 |
return |
| 1412 |
|
| 1413 |
|
| 1414 |
isnan = math.isnan |
| 1415 |
|
| 1416 |
############################################################################### |
| 1417 |
# Return NaN |
| 1418 |
|
| 1419 |
|
| 1420 |
def NaN(): |
| 1421 |
return float("nan") |
| 1422 |
|
| 1423 |
|
| 1424 |
############################################################################### |
| 1425 |
# Return positive infinity |
| 1426 |
|
| 1427 |
|
| 1428 |
def posinf(): |
| 1429 |
return float("inf") |
| 1430 |
|
| 1431 |
|
| 1432 |
############################################################################### |
| 1433 |
# Return negative infinity |
| 1434 |
|
| 1435 |
|
| 1436 |
def neginf(): |
| 1437 |
return float("-inf") |
| 1438 |
|
| 1439 |
|
| 1440 |
############################################################################### |
| 1441 |
# Has the user requested to download test data |
| 1442 |
def download_test_data(): |
| 1443 |
val = gdal.GetConfigOption("GDAL_DOWNLOAD_TEST_DATA", None) |
| 1444 |
return val == "yes" or val == "YES" |
| 1445 |
|
| 1446 |
|
| 1447 |
############################################################################### |
| 1448 |
# Has the user requested to run the slow tests |
| 1449 |
def run_slow_tests(): |
| 1450 |
val = gdal.GetConfigOption("GDAL_RUN_SLOW_TESTS", None) |
| 1451 |
return val == "yes" or val == "YES" |
| 1452 |
|
| 1453 |
|
| 1454 |
############################################################################### |
| 1455 |
# Return true if the platform support symlinks |
| 1456 |
|
| 1457 |
|
| 1458 |
def support_symlink(): |
| 1459 |
if sys.platform.startswith("linux"): |
| 1460 |
return True |
| 1461 |
if sys.platform.find("freebsd") != -1: |
| 1462 |
return True |
| 1463 |
if sys.platform == "darwin": |
| 1464 |
return True |
| 1465 |
if sys.platform.find("sunos") != -1: |
| 1466 |
return True |
| 1467 |
return False |
| 1468 |
|
| 1469 |
|
| 1470 |
############################################################################### |
| 1471 |
# Return True if the test must be skipped |
| 1472 |
|
| 1473 |
|
| 1474 |
def skip_on_travis(): |
| 1475 |
__tracebackhide__ = True |
| 1476 |
val = gdal.GetConfigOption("TRAVIS", None) |
| 1477 |
if val is not None: |
| 1478 |
pytest.skip("Test skipped on Travis") |
| 1479 |
|
| 1480 |
|
| 1481 |
############################################################################### |
| 1482 |
# Return True if the provided name is in TRAVIS_BRANCH or BUILD_NAME |
| 1483 |
|
| 1484 |
|
| 1485 |
def is_travis_branch(name): |
| 1486 |
if "TRAVIS_BRANCH" in os.environ: |
| 1487 |
val = os.environ["TRAVIS_BRANCH"] |
| 1488 |
if name in val: |
| 1489 |
return True |
| 1490 |
if "BUILD_NAME" in os.environ: |
| 1491 |
val = os.environ["BUILD_NAME"] |
| 1492 |
if name in val: |
| 1493 |
return True |
| 1494 |
return False |
| 1495 |
|
| 1496 |
|
| 1497 |
############################################################################### |
| 1498 |
# Return True if we run under CI |
| 1499 |
|
| 1500 |
|
| 1501 |
def is_ci(): |
| 1502 |
return "CI" in os.environ |
| 1503 |
|
| 1504 |
|
| 1505 |
############################################################################### |
| 1506 |
# find_lib_linux() |
| 1507 |
# Parse /proc/self/maps to find an occurrence of libXXXXX.so.* |
| 1508 |
|
| 1509 |
|
| 1510 |
def find_lib_linux(libname): |
| 1511 |
|
| 1512 |
f = open("/proc/self/maps") |
| 1513 |
lines = f.readlines() |
| 1514 |
f.close() |
| 1515 |
|
| 1516 |
for line in lines: |
| 1517 |
if line.rfind("/lib" + libname) == -1 or line.find(".so") == -1: |
| 1518 |
continue |
| 1519 |
|
| 1520 |
i = line.find(" ") |
| 1521 |
if i < 0: |
| 1522 |
continue |
| 1523 |
line = line[i + 1 :] |
| 1524 |
i = line.find(" ") |
| 1525 |
if i < 0: |
| 1526 |
continue |
| 1527 |
line = line[i + 1 :] |
| 1528 |
i = line.find(" ") |
| 1529 |
if i < 0: |
| 1530 |
continue |
| 1531 |
line = line[i + 1 :] |
| 1532 |
i = line.find(" ") |
| 1533 |
if i < 0: |
| 1534 |
continue |
| 1535 |
line = line[i + 1 :] |
| 1536 |
i = line.find(" ") |
| 1537 |
if i < 0: |
| 1538 |
continue |
| 1539 |
line = line[i + 1 :] |
| 1540 |
|
| 1541 |
soname = line.lstrip().rstrip("\n") |
| 1542 |
if soname.rfind("/lib" + libname) == -1: |
| 1543 |
continue |
| 1544 |
|
| 1545 |
return soname |
| 1546 |
|
| 1547 |
return None |
| 1548 |
|
| 1549 |
|
| 1550 |
############################################################################### |
| 1551 |
# find_lib_sunos() |
| 1552 |
# Parse output of pmap to find an occurrence of libXXX.so.* |
| 1553 |
|
| 1554 |
|
| 1555 |
def find_lib_sunos(libname): |
| 1556 |
|
| 1557 |
pid = os.getpid() |
| 1558 |
lines, _ = runexternal_out_and_err("pmap %d" % pid) |
| 1559 |
|
| 1560 |
for line in lines.split("\n"): |
| 1561 |
if line.rfind("/lib" + libname) == -1 or line.find(".so") == -1: |
| 1562 |
continue |
| 1563 |
|
| 1564 |
i = line.find("/") |
| 1565 |
if i < 0: |
| 1566 |
continue |
| 1567 |
line = line[i:] |
| 1568 |
|
| 1569 |
soname = line.lstrip().rstrip("\n") |
| 1570 |
if soname.rfind("/lib" + libname) == -1: |
| 1571 |
continue |
| 1572 |
|
| 1573 |
return soname |
| 1574 |
|
| 1575 |
return None |
| 1576 |
|
| 1577 |
|
| 1578 |
############################################################################### |
| 1579 |
# find_lib_windows() |
| 1580 |
# use Module32First() / Module32Next() API on the current process |
| 1581 |
|
| 1582 |
|
| 1583 |
def find_lib_windows(libname): |
| 1584 |
|
| 1585 |
try: |
| 1586 |
import ctypes |
| 1587 |
except ImportError: |
| 1588 |
return None |
| 1589 |
|
| 1590 |
kernel32 = ctypes.windll.kernel32 |
| 1591 |
|
| 1592 |
MAX_MODULE_NAME32 = 255 |
| 1593 |
MAX_PATH = 260 |
| 1594 |
|
| 1595 |
TH32CS_SNAPMODULE = 0x00000008 |
| 1596 |
|
| 1597 |
class MODULEENTRY32(ctypes.Structure): |
| 1598 |
_fields_ = [ |
| 1599 |
("dwSize", ctypes.c_int), |
| 1600 |
("th32ModuleID", ctypes.c_int), |
| 1601 |
("th32ProcessID", ctypes.c_int), |
| 1602 |
("GlblcntUsage", ctypes.c_int), |
| 1603 |
("ProccntUsage", ctypes.c_int), |
| 1604 |
("modBaseAddr", ctypes.c_char_p), |
| 1605 |
("modBaseSize", ctypes.c_int), |
| 1606 |
("hModule", ctypes.c_void_p), |
| 1607 |
("szModule", ctypes.c_char * (MAX_MODULE_NAME32 + 1)), |
| 1608 |
("szExePath", ctypes.c_char * MAX_PATH), |
| 1609 |
] |
| 1610 |
|
| 1611 |
Module32First = kernel32.Module32First |
| 1612 |
Module32First.argtypes = [ctypes.c_void_p, ctypes.POINTER(MODULEENTRY32)] |
| 1613 |
Module32First.rettypes = ctypes.c_int |
| 1614 |
|
| 1615 |
Module32Next = kernel32.Module32Next |
| 1616 |
Module32Next.argtypes = [ctypes.c_void_p, ctypes.POINTER(MODULEENTRY32)] |
| 1617 |
Module32Next.rettypes = ctypes.c_int |
| 1618 |
|
| 1619 |
CreateToolhelp32Snapshot = kernel32.CreateToolhelp32Snapshot |
| 1620 |
CreateToolhelp32Snapshot.argtypes = [ctypes.c_int, ctypes.c_int] |
| 1621 |
CreateToolhelp32Snapshot.rettypes = ctypes.c_void_p |
| 1622 |
|
| 1623 |
CloseHandle = kernel32.CloseHandle |
| 1624 |
CloseHandle.argtypes = [ctypes.c_void_p] |
| 1625 |
CloseHandle.rettypes = ctypes.c_int |
| 1626 |
|
| 1627 |
GetLastError = kernel32.GetLastError |
| 1628 |
GetLastError.argtypes = [] |
| 1629 |
GetLastError.rettypes = ctypes.c_int |
| 1630 |
|
| 1631 |
snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0) |
| 1632 |
if snapshot is None: |
| 1633 |
return None |
| 1634 |
|
| 1635 |
soname = None |
| 1636 |
|
| 1637 |
i = 0 |
| 1638 |
while True: |
| 1639 |
entry = MODULEENTRY32() |
| 1640 |
entry.dwSize = ctypes.sizeof(MODULEENTRY32) |
| 1641 |
pentry = ctypes.pointer(entry) |
| 1642 |
if i == 0: |
| 1643 |
ret = Module32First(snapshot, pentry) |
| 1644 |
else: |
| 1645 |
ret = Module32Next(snapshot, pentry) |
| 1646 |
i = i + 1 |
| 1647 |
if ret == 0: |
| 1648 |
break |
| 1649 |
|
| 1650 |
try: |
| 1651 |
path = entry.szExePath.decode("latin1") |
| 1652 |
except Exception: |
| 1653 |
continue |
| 1654 |
|
| 1655 |
i = path.rfind("\\" + libname) |
| 1656 |
if i < 0: |
| 1657 |
continue |
| 1658 |
if path[i + 1 :].find("\\") >= 0: |
| 1659 |
continue |
| 1660 |
# Avoid matching gdal_PLUGIN.dll |
| 1661 |
if path[i + 1 :].find("_") >= 0: |
| 1662 |
continue |
| 1663 |
soname = path |
| 1664 |
break |
| 1665 |
|
| 1666 |
CloseHandle(snapshot) |
| 1667 |
|
| 1668 |
return soname |
| 1669 |
|
| 1670 |
|
| 1671 |
############################################################################### |
| 1672 |
# find_lib() |
| 1673 |
|
| 1674 |
|
| 1675 |
def find_lib(mylib): |
| 1676 |
if sys.platform.startswith("linux"): |
| 1677 |
return find_lib_linux(mylib) |
| 1678 |
if sys.platform.startswith("sunos"): |
| 1679 |
return find_lib_sunos(mylib) |
| 1680 |
if sys.platform.startswith("win32"): |
| 1681 |
return find_lib_windows(mylib) |
| 1682 |
# sorry mac users or other BSDs |
| 1683 |
# should be doable |
| 1684 |
return None |
| 1685 |
|
| 1686 |
|
| 1687 |
############################################################################### |
| 1688 |
# get_opened_files() |
| 1689 |
|
| 1690 |
|
| 1691 |
get_opened_files_has_warned = False |
| 1692 |
|
| 1693 |
|
| 1694 |
def get_opened_files(): |
| 1695 |
if not sys.platform.startswith("linux"): |
| 1696 |
return [] |
| 1697 |
fdpath = "/proc/%d/fd" % os.getpid() |
| 1698 |
if not os.path.exists(fdpath): |
| 1699 |
global get_opened_files_has_warned |
| 1700 |
if not get_opened_files_has_warned: |
| 1701 |
get_opened_files_has_warned = True |
| 1702 |
print("get_opened_files() not supported due to /proc not being readable") |
| 1703 |
return [] |
| 1704 |
file_numbers = os.listdir(fdpath) |
| 1705 |
filenames = [] |
| 1706 |
for fd in file_numbers: |
| 1707 |
try: |
| 1708 |
filename = os.readlink("%s/%s" % (fdpath, fd)) |
| 1709 |
if ( |
| 1710 |
not filename.startswith("/dev/") |
| 1711 |
and not filename.startswith("pipe:") |
| 1712 |
and filename.find("proj.db") < 0 |
| 1713 |
): |
| 1714 |
filenames.append(filename) |
| 1715 |
except OSError: |
| 1716 |
pass |
| 1717 |
return filenames |
| 1718 |
|
| 1719 |
|
| 1720 |
############################################################################### |
| 1721 |
# is_file_open() |
| 1722 |
|
| 1723 |
|
| 1724 |
def is_file_open(filename): |
| 1725 |
for got_filename in get_opened_files(): |
| 1726 |
if filename in got_filename: |
| 1727 |
return True |
| 1728 |
return False |
| 1729 |
|
| 1730 |
|
| 1731 |
############################################################################### |
| 1732 |
# built_against_curl() |
| 1733 |
|
| 1734 |
|
| 1735 |
def built_against_curl(): |
| 1736 |
return "CURL_ENABLED=YES" in gdal.VersionInfo("BUILD_INFO") |
| 1737 |
|
| 1738 |
|
| 1739 |
############################################################################### |
| 1740 |
# error_handler() |
| 1741 |
# Allow use of "with" for an ErrorHandler that always pops at the scope close. |
| 1742 |
# Defaults to suppressing errors and warnings. |
| 1743 |
|
| 1744 |
|
| 1745 |
@contextlib.contextmanager |
| 1746 |
def error_handler(error_name="CPLQuietErrorHandler"): |
| 1747 |
handler = gdal.PushErrorHandler(error_name) |
| 1748 |
try: |
| 1749 |
yield handler |
| 1750 |
finally: |
| 1751 |
gdal.PopErrorHandler() |
| 1752 |
|
| 1753 |
|
| 1754 |
############################################################################### |
| 1755 |
# Temporarily define a new value of block cache |
| 1756 |
|
| 1757 |
|
| 1758 |
@contextlib.contextmanager |
| 1759 |
def SetCacheMax(val): |
| 1760 |
oldval = gdal.GetCacheMax() |
| 1761 |
gdal.SetCacheMax(val) |
| 1762 |
try: |
| 1763 |
yield |
| 1764 |
finally: |
| 1765 |
gdal.SetCacheMax(oldval) |
| 1766 |
|
| 1767 |
|
| 1768 |
############################################################################### |
| 1769 |
# Temporarily enable exceptions for gdal, ogr and osr modules |
| 1770 |
|
| 1771 |
|
| 1772 |
@contextlib.contextmanager |
| 1773 |
def enable_exceptions(): |
| 1774 |
from osgeo import ogr, osr |
| 1775 |
|
| 1776 |
try: |
| 1777 |
with gdal.ExceptionMgr(useExceptions=True), osr.ExceptionMgr( |
| 1778 |
useExceptions=True |
| 1779 |
), ogr.ExceptionMgr(useExceptions=True): |
| 1780 |
yield |
| 1781 |
except AttributeError: |
| 1782 |
# GDAL <3.7 |
| 1783 |
yield |
| 1784 |
|
| 1785 |
|
| 1786 |
############################################################################### |
| 1787 |
# Temporarily disable exceptions for gdal, ogr and osr modules |
| 1788 |
|
| 1789 |
|
| 1790 |
@contextlib.contextmanager |
| 1791 |
def disable_exceptions(): |
| 1792 |
from osgeo import ogr, osr |
| 1793 |
|
| 1794 |
try: |
| 1795 |
with gdal.ExceptionMgr(useExceptions=False), osr.ExceptionMgr( |
| 1796 |
useExceptions=False |
| 1797 |
), ogr.ExceptionMgr(useExceptions=False): |
| 1798 |
yield |
| 1799 |
except AttributeError: |
| 1800 |
# GDAL <3.7 |
| 1801 |
yield |
| 1802 |
|
| 1803 |
|
| 1804 |
############################################################################### |
| 1805 |
# Temporarily define a configuration option |
| 1806 |
|
| 1807 |
|
| 1808 |
try: |
| 1809 |
config_option = gdal.config_option |
| 1810 |
except AttributeError: |
| 1811 |
# GDAL <3.7 |
| 1812 |
@contextlib.contextmanager |
| 1813 |
def config_option(key, val): |
| 1814 |
oldval = gdal.GetConfigOption(key) |
| 1815 |
gdal.SetConfigOption(key, val) |
| 1816 |
try: |
| 1817 |
yield |
| 1818 |
finally: |
| 1819 |
gdal.SetConfigOption(key, oldval) |
| 1820 |
|
| 1821 |
|
| 1822 |
############################################################################### |
| 1823 |
# Temporarily define a set of configuration options |
| 1824 |
|
| 1825 |
|
| 1826 |
try: |
| 1827 |
config_options = gdal.config_options |
| 1828 |
except AttributeError: |
| 1829 |
# GDAL <3.7 |
| 1830 |
@contextlib.contextmanager |
| 1831 |
def config_options(options): |
| 1832 |
oldvals = {key: gdal.GetConfigOption(key) for key in options} |
| 1833 |
for key in options: |
| 1834 |
gdal.SetConfigOption(key, options[key]) |
| 1835 |
try: |
| 1836 |
yield |
| 1837 |
finally: |
| 1838 |
for key in options: |
| 1839 |
gdal.SetConfigOption(key, oldvals[key]) |
| 1840 |
|
| 1841 |
|
| 1842 |
############################################################################### |
| 1843 |
# Temporarily define VSI credentials |
| 1844 |
|
| 1845 |
credential_keys = set() |
| 1846 |
|
| 1847 |
|
| 1848 |
@contextlib.contextmanager |
| 1849 |
def credentials(prefix, options): |
| 1850 |
global credential_keys |
| 1851 |
# Special processing for nested with credentials() call on the same key |
| 1852 |
clear_credentials = prefix not in credential_keys |
| 1853 |
credential_keys.add(prefix) |
| 1854 |
for key in options: |
| 1855 |
gdal.SetCredential(prefix, key, options[key]) |
| 1856 |
try: |
| 1857 |
yield |
| 1858 |
finally: |
| 1859 |
if clear_credentials: |
| 1860 |
credential_keys.remove(prefix) |
| 1861 |
gdal.ClearCredentials(prefix) |
| 1862 |
|
| 1863 |
|
| 1864 |
############################################################################### |
| 1865 |
# Temporarily create a file |
| 1866 |
|
| 1867 |
|
| 1868 |
@contextlib.contextmanager |
| 1869 |
def tempfile(filename, content): |
| 1870 |
gdal.FileFromMemBuffer(filename, content) |
| 1871 |
try: |
| 1872 |
yield |
| 1873 |
finally: |
| 1874 |
gdal.Unlink(filename) |
| 1875 |
|
| 1876 |
|
| 1877 |
############################################################################### |
| 1878 |
|
| 1879 |
|
| 1880 |
def gdalurlopen(url, timeout=10): |
| 1881 |
old_timeout = socket.getdefaulttimeout() |
| 1882 |
socket.setdefaulttimeout(timeout) |
| 1883 |
proxy = None |
| 1884 |
|
| 1885 |
if "GDAL_HTTP_PROXY" in os.environ: |
| 1886 |
proxy = os.environ["GDAL_HTTP_PROXY"] |
| 1887 |
protocol = "http" |
| 1888 |
|
| 1889 |
if "GDAL_HTTPS_PROXY" in os.environ and url.startswith("https"): |
| 1890 |
proxy = os.environ["GDAL_HTTPS_PROXY"] |
| 1891 |
protocol = "https" |
| 1892 |
|
| 1893 |
if proxy is not None: |
| 1894 |
if "GDAL_HTTP_PROXYUSERPWD" in os.environ: |
| 1895 |
proxyuserpwd = os.environ["GDAL_HTTP_PROXYUSERPWD"] |
| 1896 |
proxy_handler = urllib.request.ProxyHandler( |
| 1897 |
{protocol: f"{protocol}://{proxyuserpwd}@{proxy}"} |
| 1898 |
) |
| 1899 |
else: |
| 1900 |
proxyuserpwd = None |
| 1901 |
proxy_handler = urllib.request.ProxyHandler( |
| 1902 |
{protocol: f"{protocol}://{proxy}"} |
| 1903 |
) |
| 1904 |
|
| 1905 |
opener = urllib.request.build_opener(proxy_handler, urllib.request.HTTPHandler) |
| 1906 |
|
| 1907 |
urllib.request.install_opener(opener) |
| 1908 |
|
| 1909 |
try: |
| 1910 |
handle = urllib.request.urlopen(url) |
| 1911 |
socket.setdefaulttimeout(old_timeout) |
| 1912 |
return handle |
| 1913 |
except urllib.error.HTTPError as e: |
| 1914 |
print(f"HTTP service for {url} is down (HTTP Error: {e.code})") |
| 1915 |
socket.setdefaulttimeout(old_timeout) |
| 1916 |
return None |
| 1917 |
except urllib.error.ContentTooShortError: |
| 1918 |
print(f"HTTP content too short for {url}.") |
| 1919 |
socket.setdefaulttimeout(old_timeout) |
| 1920 |
return None |
| 1921 |
except urllib.error.URLError as e: |
| 1922 |
print(f"HTTP service for {url} is down (URL Error: {e.reason})") |
| 1923 |
socket.setdefaulttimeout(old_timeout) |
| 1924 |
return None |
| 1925 |
except socket.timeout: |
| 1926 |
print(f"HTTP service for {url} timed out") |
| 1927 |
socket.setdefaulttimeout(old_timeout) |
| 1928 |
return None |
| 1929 |
|
| 1930 |
|
| 1931 |
def runexternal( |
| 1932 |
cmd, |
| 1933 |
strin=None, |
| 1934 |
check_memleak=True, |
| 1935 |
display_live_on_parent_stdout=False, |
| 1936 |
encoding="latin1", |
| 1937 |
): |
| 1938 |
# pylint: disable=unused-argument |
| 1939 |
if sys.platform == "win32": |
| 1940 |
command = cmd |
| 1941 |
else: |
| 1942 |
command = shlex.split(cmd) |
| 1943 |
if strin is None: |
| 1944 |
p = subprocess.Popen(command, stdout=subprocess.PIPE) |
| 1945 |
else: |
| 1946 |
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
| 1947 |
p.stdin.write(strin.encode("ascii")) |
| 1948 |
p.stdin.close() |
| 1949 |
|
| 1950 |
if p.stdout is not None: |
| 1951 |
if display_live_on_parent_stdout: |
| 1952 |
ret = "" |
| 1953 |
ret_stdout = p.stdout |
| 1954 |
while True: |
| 1955 |
c = ret_stdout.read(1).decode(encoding) |
| 1956 |
if c == "": |
| 1957 |
break |
| 1958 |
ret = ret + c |
| 1959 |
sys.stdout.write(c) |
| 1960 |
else: |
| 1961 |
ret = p.stdout.read().decode(encoding) |
| 1962 |
else: |
| 1963 |
ret = "" |
| 1964 |
|
| 1965 |
waitcode = p.wait() |
| 1966 |
if waitcode != 0: |
| 1967 |
ret = f"{ret}\nERROR ret code = {waitcode}" |
| 1968 |
|
| 1969 |
return ret |
| 1970 |
|
| 1971 |
|
| 1972 |
def _read_in_thread(f, q): |
| 1973 |
q.put(f.read()) |
| 1974 |
f.close() |
| 1975 |
|
| 1976 |
|
| 1977 |
def runexternal_out_and_err(cmd, check_memleak=True, encoding="ascii"): |
| 1978 |
# pylint: disable=unused-argument |
| 1979 |
if sys.platform == "win32": |
| 1980 |
command = cmd |
| 1981 |
else: |
| 1982 |
command = shlex.split(cmd) |
| 1983 |
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 1984 |
|
| 1985 |
if p.stdout is not None: |
| 1986 |
q_stdout = Queue() |
| 1987 |
t_stdout = Thread(target=_read_in_thread, args=(p.stdout, q_stdout)) |
| 1988 |
t_stdout.start() |
| 1989 |
else: |
| 1990 |
q_stdout = None |
| 1991 |
ret_stdout = "" |
| 1992 |
|
| 1993 |
if p.stderr is not None: |
| 1994 |
q_stderr = Queue() |
| 1995 |
t_stderr = Thread(target=_read_in_thread, args=(p.stderr, q_stderr)) |
| 1996 |
t_stderr.start() |
| 1997 |
else: |
| 1998 |
q_stderr = None |
| 1999 |
ret_stderr = "" |
| 2000 |
|
| 2001 |
if q_stdout is not None: |
| 2002 |
ret_stdout = q_stdout.get().decode(encoding) |
| 2003 |
if q_stderr is not None: |
| 2004 |
ret_stderr = q_stderr.get().decode(encoding) |
| 2005 |
|
| 2006 |
waitcode = p.wait() |
| 2007 |
if waitcode != 0: |
| 2008 |
ret_stderr = f"{ret_stderr}\nERROR ret code = {waitcode}" |
| 2009 |
|
| 2010 |
return (ret_stdout, ret_stderr) |
| 2011 |
|
| 2012 |
|
| 2013 |
############################################################################### |
| 2014 |
# Validate JSON according to a JSON schema |
| 2015 |
# |
| 2016 |
# "jsn" should be a string or a json object |
| 2017 |
# "schema" should be a path to file containing a JSON schema. If the |
| 2018 |
# file is not found relative to the current working directory or GDAL_DATA, |
| 2019 |
# the test will fail. |
| 2020 |
def validate_json(jsn, schema): |
| 2021 |
__tracebackhide__ = True |
| 2022 |
|
| 2023 |
try: |
| 2024 |
import jsonschema |
| 2025 |
except ImportError: |
| 2026 |
pytest.skip("jsonschema module not available") |
| 2027 |
|
| 2028 |
if not os.path.exists(schema): |
| 2029 |
gdal_data = gdal.GetConfigOption("GDAL_DATA") |
| 2030 |
|
| 2031 |
if gdal_data and os.path.exists(os.path.join(gdal_data, schema)): |
| 2032 |
schema = os.path.join(gdal_data, schema) |
| 2033 |
else: |
| 2034 |
pytest.fail(f"Could not find schema {schema}") |
| 2035 |
|
| 2036 |
if isinstance(jsn, str): |
| 2037 |
jsn = json.loads(jsn) |
| 2038 |
|
| 2039 |
schema = json.loads(open(schema, "rb").read()) |
| 2040 |
|
| 2041 |
if sys.version_info >= (3, 8): |
| 2042 |
from importlib.metadata import version |
| 2043 |
|
| 2044 |
jsonschema_version = version("jsonschema") |
| 2045 |
else: |
| 2046 |
from pkg_resources import get_distribution |
| 2047 |
|
| 2048 |
jsonschema_version = get_distribution("jsonschema").version |
| 2049 |
|
| 2050 |
def versiontuple(v): |
| 2051 |
return tuple(map(int, (v.split(".")))) |
| 2052 |
|
| 2053 |
# jsonschema 4.18 deprecates automatic resolution of "$ref" for security |
| 2054 |
# reason. Use a custom retrieve method. |
| 2055 |
# Cf https://python-jsonschema.readthedocs.io/en/latest/referencing/#automatically-retrieving-resources-over-http |
| 2056 |
if versiontuple(jsonschema_version) >= (4, 18): |
| 2057 |
from referencing import Registry, Resource |
| 2058 |
|
| 2059 |
def retrieve_remote_file(uri: str): |
| 2060 |
if not uri.startswith("http://") and not uri.startswith("https://"): |
| 2061 |
raise Exception(f"Cannot retrieve {uri}") |
| 2062 |
os.makedirs("tmp/cache", exist_ok=True) |
| 2063 |
filename = "tmp/cache/" + os.path.basename(uri) |
| 2064 |
if not download_file(uri, filename=filename, force_download=True): |
| 2065 |
raise Exception(f"Cannot download {uri}") |
| 2066 |
response = open(filename, "rb").read() |
| 2067 |
return Resource.from_contents(json.loads(response)) |
| 2068 |
|
| 2069 |
registry = Registry(retrieve=retrieve_remote_file) |
| 2070 |
validator_cls = jsonschema.validators.validator_for(schema) |
| 2071 |
validator_cls(schema, registry=registry).validate(jsn) |
| 2072 |
|
| 2073 |
else: |
| 2074 |
# jsonschema < 4.18 |
| 2075 |
try: |
| 2076 |
jsonschema.validate(instance=jsn, schema=schema) |
| 2077 |
except jsonschema.exceptions.RefResolutionError: |
| 2078 |
pytest.skip("Failed to resolve remote reference in JSON schema") |
| 2079 |
|
| 2080 |
|
| 2081 |
############################################################################### |
| 2082 |
# Close and reopen a dataset |
| 2083 |
|
| 2084 |
|
| 2085 |
def reopen(ds, update=False, open_options=None): |
| 2086 |
|
| 2087 |
ds_loc = ds.GetDescription() |
| 2088 |
ds_drv = ds.GetDriver() |
| 2089 |
|
| 2090 |
ds.Close() |
| 2091 |
|
| 2092 |
if isinstance(ds, ogr.DataSource) and open_options is None: |
| 2093 |
return ogr.Open(ds_loc, update) |
| 2094 |
|
| 2095 |
flags = 0 |
| 2096 |
if update: |
| 2097 |
flags = gdal.OF_UPDATE |
| 2098 |
|
| 2099 |
if open_options is None: |
| 2100 |
open_options = {} |
| 2101 |
|
| 2102 |
return gdal.OpenEx( |
| 2103 |
ds_loc, |
| 2104 |
flags, |
| 2105 |
allowed_drivers=[ds_drv.GetDescription()], |
| 2106 |
open_options=open_options, |
| 2107 |
) |