diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 076a35c1a505..4f25fe990dad 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -21,7 +21,8 @@ gdalinfo --version
Run autotest suite:
```
cd ../autotest
-python run_all.py
+pip install -r requirements.txt
+pytest
```
Git workflows with GDAL
diff --git a/appveyor.yml b/appveyor.yml
index 02b57110ea26..5b6c93ee34bc 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -155,7 +155,8 @@ test_script:
cd $env:APPVEYOR_BUILD_FOLDER\autotest\cpp
exec { nmake /f makefile.vc check MSVC_VER=$env:MSVC_VER $env:WIN64_ARG }
cd $env:APPVEYOR_BUILD_FOLDER\autotest
- exec { python run_all.py }
+ exec { pip install -Ur requirements.txt }
+ exec { pytest -vv }
cd $env:APPVEYOR_BUILD_FOLDER\gdal\swig\csharp
exec { nmake /f makefile.vc test}
diff --git a/autotest/GNUmakefile b/autotest/GNUmakefile
index c0fa6c8c7ea8..61e42ea9a772 100644
--- a/autotest/GNUmakefile
+++ b/autotest/GNUmakefile
@@ -2,25 +2,25 @@ all:
@echo "Run 'make -j test'"
gcore-test:
- python run_all.py gcore
+ pytest gcore
gdrivers-test:
- python run_all.py gdrivers
+ pytest gdrivers
alg-test:
- python run_all.py alg
+ pytest alg
osr-test:
- python run_all.py osr
+ pytest osr
ogr-test:
- python run_all.py ogr
+ pytest ogr
utilities-test:
- python run_all.py utilities
+ pytest utilities
pyscripts-test:
- python run_all.py pyscripts
+ pytest pyscripts
test check:
@$(MAKE) $(MFLAGS) gcore-test gdrivers-test alg-test ogr-test osr-test utilities-test pyscripts-test
diff --git a/autotest/README b/autotest/README
deleted file mode 100644
index 27628ccda5c7..000000000000
--- a/autotest/README
+++ /dev/null
@@ -1,15 +0,0 @@
----------------------
-GDAL Autotest Package
----------------------
-
-
-Notes about availability of GDAL sample and test data
------------------------------------------------------
-
-The GDAL Team makes every effort to assure that all sample data files
-available from GDAL download server (http://download.osgeo.org/gdal/data/) and
-test data files used in GDAL Autotest package (https://github.com/OSGeo/gdal/tree/master/autotest)
-are available as public and freely redistributable geodata.
-
---
-http://gdal.org/
diff --git a/autotest/README.md b/autotest/README.md
new file mode 100644
index 000000000000..5e866c0404d7
--- /dev/null
+++ b/autotest/README.md
@@ -0,0 +1,56 @@
+# GDAL test suite
+
+
+## How to run tests
+
+1. You need to install `pytest` to run the test suite. This should do it:
+
+```bash
+cd autotest
+pip install -r ./requirements.txt
+```
+
+2. Then, run tests with:
+
+```bash
+pytest
+```
+
+3. Some quick usage tips:
+
+```bash
+# get more verbose output; don't capture stdout/stdin
+pytest -vvs
+
+# run all the gcore tests
+pytest gcore/
+
+# run a particular module only
+pytest gcore/basic_test.py
+```
+
+
+## GDAL's tests are not independent
+
+GDAL's test functions are not currently independent of each other. In particular, running individual test functions from a given module may not work. Most tests were originally written with the assumption that entire modules will be run at once.
+
+Practically, this means that you should avoid using:
+
+
+* pytest's `--last-failed` / `--lf` option (since it runs only failed tests, not the whole module)
+* test specifiers that run individual tests (e.g. `pytest gcore/basic_test.py::test_basic_test_1` )
+* the xunit plugin to run tests in parallel, unless you also use `--dist=loadfile`. (This may have other issues; untested)
+
+This will hopefully be addressed in the future. When writing new tests, please try to make them independent of each other.
+
+
+## Notes about availability of GDAL sample and test data
+
+The GDAL Team makes every effort to assure that all sample data files
+available from GDAL download server (http://download.osgeo.org/gdal/data/) and
+test data files used in GDAL Autotest package (https://github.com/OSGeo/gdal/tree/master/autotest)
+are available as public and freely redistributable geodata.
+
+--
+
+http://gdal.org/
diff --git a/autotest/alg/__init__.py b/autotest/alg/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/autotest/alg/applyverticalshiftgrid.py b/autotest/alg/applyverticalshiftgrid.py
index 63e7c8504e50..688c69c622bc 100755
--- a/autotest/alg/applyverticalshiftgrid.py
+++ b/autotest/alg/applyverticalshiftgrid.py
@@ -29,9 +29,7 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal, osr
@@ -40,42 +38,24 @@
# Rather dummy test: grid = DEM
-def applyverticalshiftgrid_1():
+def test_applyverticalshiftgrid_1():
src_ds = gdal.Open('../gcore/data/byte.tif')
src_ds = gdal.Translate('', src_ds, format='MEM',
width=20, height=40)
grid_ds = gdal.Translate('', src_ds, format='MEM')
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds)
- if out_ds.GetRasterBand(1).DataType != gdal.GDT_Byte:
- gdaltest.post_reason('fail')
- print(out_ds.GetRasterBand(1).DataType)
- return 'fail'
- if out_ds.RasterXSize != src_ds.RasterXSize:
- gdaltest.post_reason('fail')
- print(out_ds.RasterXSize)
- return 'fail'
- if out_ds.RasterYSize != src_ds.RasterYSize:
- gdaltest.post_reason('fail')
- print(out_ds.RasterYSize)
- return 'fail'
- if out_ds.GetGeoTransform() != src_ds.GetGeoTransform():
- gdaltest.post_reason('fail')
- print(out_ds.GetGeoTransform())
- return 'fail'
- if out_ds.GetProjectionRef() != src_ds.GetProjectionRef():
- gdaltest.post_reason('fail')
- print(out_ds.GetProjectionRef())
- return 'fail'
+ assert out_ds.GetRasterBand(1).DataType == gdal.GDT_Byte
+ assert out_ds.RasterXSize == src_ds.RasterXSize
+ assert out_ds.RasterYSize == src_ds.RasterYSize
+ assert out_ds.GetGeoTransform() == src_ds.GetGeoTransform()
+ assert out_ds.GetProjectionRef() == src_ds.GetProjectionRef()
# Check that we can drop the reference to the sources
src_ds = None
grid_ds = None
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 10038:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 10038
src_ds = gdal.Open('../gcore/data/byte.tif')
src_ds = gdal.Translate('', src_ds, format='MEM',
@@ -85,31 +65,20 @@ def applyverticalshiftgrid_1():
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, src_ds,
options=['BLOCKSIZE=15'])
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 10038:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 10038
# Inverse transformer
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, src_ds, True,
options=['DATATYPE=Float32'])
- if out_ds.GetRasterBand(1).DataType != gdal.GDT_Float32:
- gdaltest.post_reason('fail')
- print(out_ds.GetRasterBand(1).DataType)
- return 'fail'
+ assert out_ds.GetRasterBand(1).DataType == gdal.GDT_Float32
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 0:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 0
###############################################################################
# Error cases
-def applyverticalshiftgrid_2():
+def test_applyverticalshiftgrid_2():
sr = osr.SpatialReference()
sr.SetFromUserInput("WGS84")
@@ -130,10 +99,7 @@ def applyverticalshiftgrid_2():
grid_ds.AddBand(gdal.GDT_Byte)
with gdaltest.error_handler():
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds)
- if out_ds is not None:
- gdaltest.post_reason('fail')
- print(i)
- return 'fail'
+ assert out_ds is None, i
# Non invertable source geotransform
src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
@@ -144,9 +110,7 @@ def applyverticalshiftgrid_2():
grid_ds.SetProjection(sr.ExportToWkt())
with gdaltest.error_handler():
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds)
- if out_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert out_ds is None
# Non invertable grid geotransform
src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
@@ -157,9 +121,7 @@ def applyverticalshiftgrid_2():
grid_ds.SetProjection(sr.ExportToWkt())
with gdaltest.error_handler():
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds)
- if out_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert out_ds is None
# No PROJ.4 translation for source SRS, coordinate transformation
# initialization has failed
@@ -171,9 +133,7 @@ def applyverticalshiftgrid_2():
grid_ds.SetProjection('LOCAL_CS["foo"]')
with gdaltest.error_handler():
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds)
- if out_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert out_ds is None
# Out of memory
if gdal.GetConfigOption('SKIP_MEM_INTENSIVE_TEST') is None:
@@ -186,9 +146,7 @@ def applyverticalshiftgrid_2():
with gdaltest.error_handler():
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds,
options=['BLOCKSIZE=2000000000'])
- if out_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert out_ds is None
# Wrong DATATYPE
src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
@@ -200,68 +158,41 @@ def applyverticalshiftgrid_2():
with gdaltest.error_handler():
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds,
options=['DATATYPE=x'])
- if out_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert out_ds is None
###############################################################################
# Test with grid and src not in same projection
-def applyverticalshiftgrid_3():
+def test_applyverticalshiftgrid_3():
src_ds = gdal.Open('../gcore/data/byte.tif')
grid_ds = gdal.Warp('', src_ds, format='MEM', dstSRS='EPSG:4326',
width=40, height=40)
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds,
options=['RESAMPLING=NEAREST'])
- if out_ds.RasterXSize != src_ds.RasterXSize:
- gdaltest.post_reason('fail')
- print(out_ds.RasterXSize)
- return 'fail'
- if out_ds.RasterYSize != src_ds.RasterYSize:
- gdaltest.post_reason('fail')
- print(out_ds.RasterYSize)
- return 'fail'
- if out_ds.GetGeoTransform() != src_ds.GetGeoTransform():
- gdaltest.post_reason('fail')
- print(out_ds.GetGeoTransform())
- return 'fail'
- if out_ds.GetProjectionRef() != src_ds.GetProjectionRef():
- gdaltest.post_reason('fail')
- print(out_ds.GetProjectionRef())
- return 'fail'
+ assert out_ds.RasterXSize == src_ds.RasterXSize
+ assert out_ds.RasterYSize == src_ds.RasterYSize
+ assert out_ds.GetGeoTransform() == src_ds.GetGeoTransform()
+ assert out_ds.GetProjectionRef() == src_ds.GetProjectionRef()
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 5112:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 5112
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds,
options=['RESAMPLING=BILINEAR'])
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 4867 and cs != 4868:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 4867 or cs == 4868
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds,
options=['RESAMPLING=CUBIC'])
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 4841 and cs != 4854:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4841 or cs == 4854
###############################################################################
# Test nodata
-def applyverticalshiftgrid_4():
+def test_applyverticalshiftgrid_4():
sr = osr.SpatialReference()
sr.SetFromUserInput("WGS84")
@@ -277,15 +208,9 @@ def applyverticalshiftgrid_4():
grid_ds.SetProjection(sr.ExportToWkt())
grid_ds.GetRasterBand(1).Fill(30)
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds)
- if out_ds.GetRasterBand(1).GetNoDataValue() != 1:
- gdaltest.post_reason('fail')
- print(out_ds.GetRasterBand(1).GetNoDataValue())
- return 'fail'
+ assert out_ds.GetRasterBand(1).GetNoDataValue() == 1
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 1:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 1
# Nodata on grid
src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
@@ -298,15 +223,9 @@ def applyverticalshiftgrid_4():
grid_ds.GetRasterBand(1).Fill(30)
grid_ds.GetRasterBand(1).SetNoDataValue(30)
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds)
- if out_ds.GetRasterBand(1).GetNoDataValue() is not None:
- gdaltest.post_reason('fail')
- print(out_ds.GetRasterBand(1).GetNoDataValue())
- return 'fail'
+ assert out_ds.GetRasterBand(1).GetNoDataValue() is None
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 1:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 1
# ERROR_ON_MISSING_VERT_SHIFT due to non compatible extents
src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
@@ -320,9 +239,7 @@ def applyverticalshiftgrid_4():
options=['ERROR_ON_MISSING_VERT_SHIFT=YES'])
with gdaltest.error_handler():
data = out_ds.GetRasterBand(1).ReadRaster()
- if data is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert data is None
# ERROR_ON_MISSING_VERT_SHIFT due to nodata in grid
src_ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
@@ -337,17 +254,13 @@ def applyverticalshiftgrid_4():
options=['ERROR_ON_MISSING_VERT_SHIFT=YES'])
with gdaltest.error_handler():
data = out_ds.GetRasterBand(1).ReadRaster()
- if data is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert data is None
###############################################################################
# Test scaling parameters
-def applyverticalshiftgrid_5():
+def test_applyverticalshiftgrid_5():
src_ds = gdal.Open('../gcore/data/byte.tif')
grid_ds = gdal.Translate('', src_ds, format='MEM')
@@ -357,10 +270,7 @@ def applyverticalshiftgrid_5():
scaleParams=[[0, 1, 0, 0.5]])
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds, srcUnitToMeter=2)
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 4672:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 4672
src_ds = gdal.Open('../gcore/data/byte.tif')
grid_ds = gdal.Translate('', src_ds, format='MEM')
@@ -370,18 +280,13 @@ def applyverticalshiftgrid_5():
scaleParams=[[0, 1, 0, 0.5]])
out_ds = gdal.ApplyVerticalShiftGrid(src_ds, grid_ds, dstUnitToMeter=0.5)
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 4672:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4672
###############################################################################
# Simulate EGM grids
-def applyverticalshiftgrid_6():
+def test_applyverticalshiftgrid_6():
grid_ds = gdal.GetDriverByName('GTX').Create(
'/vsimem/applyverticalshiftgrid_6.gtx', 1440, 721, 1, gdal.GDT_Float32)
@@ -392,20 +297,15 @@ def applyverticalshiftgrid_6():
ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM',
dstSRS='+proj=utm +zone=11 +datum=NAD27 +geoidgrids=/vsimem/applyverticalshiftgrid_6.gtx +vunits=m +no_defs')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 4783:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 4783
gdal.Unlink('/vsimem/applyverticalshiftgrid_6.gtx')
- return 'success'
-
###############################################################################
# Simulate USA geoid grids with long origin > 180
-def applyverticalshiftgrid_7():
+def test_applyverticalshiftgrid_7():
grid_ds = gdal.GetDriverByName('GTX').Create(
'/vsimem/applyverticalshiftgrid_7.gtx', 700, 721, 1, gdal.GDT_Float32)
@@ -416,30 +316,9 @@ def applyverticalshiftgrid_7():
ds = gdal.Warp('', '../gcore/data/byte.tif', format='MEM',
dstSRS='+proj=utm +zone=11 +datum=NAD27 +geoidgrids=/vsimem/applyverticalshiftgrid_7.gtx +vunits=m +no_defs')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 4783:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 4783
gdal.Unlink('/vsimem/applyverticalshiftgrid_7.gtx')
- return 'success'
-
-
-gdaltest_list = [
- applyverticalshiftgrid_1,
- applyverticalshiftgrid_2,
- applyverticalshiftgrid_3,
- applyverticalshiftgrid_4,
- applyverticalshiftgrid_5,
- applyverticalshiftgrid_6,
- applyverticalshiftgrid_7
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('applyverticalshiftgrid')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/contour.py b/autotest/alg/contour.py
index d208fc54a86d..8092a7a0fe0e 100755
--- a/autotest/alg/contour.py
+++ b/autotest/alg/contour.py
@@ -30,20 +30,18 @@
import array
import os
-import sys
-sys.path.append('../pymod')
from osgeo import gdal
from osgeo import ogr
-import gdaltest
import ogrtest
+import pytest
###############################################################################
# Test with -a and -i options
-def contour_1():
+def test_contour_1():
try:
os.remove('tmp/contour.shp')
@@ -103,37 +101,29 @@ def contour_1():
lyr = ogr_ds.ExecuteSQL("select * from contour order by elev asc")
- if lyr.GetFeatureCount() != len(expected_envelopes):
- print('Got %d features. Expected %d' % (lyr.GetFeatureCount(), len(expected_envelopes)))
- return 'fail'
+ assert lyr.GetFeatureCount() == len(expected_envelopes)
i = 0
feat = lyr.GetNextFeature()
while feat is not None:
envelope = feat.GetGeometryRef().GetEnvelope()
- if feat.GetField('elev') != expected_height[i]:
- print('Got %f. Expected %f' % (feat.GetField('elev'), expected_height[i]))
- return 'fail'
+ assert feat.GetField('elev') == expected_height[i]
for j in range(4):
if abs(expected_envelopes[i][j] - envelope[j]) > precision / 2 * 1.001:
print('i=%d, wkt=%s' % (i, feat.GetGeometryRef().ExportToWkt()))
print(feat.GetGeometryRef().GetEnvelope())
- print(expected_envelopes[i])
- print('%f, %f' % (expected_envelopes[i][j] - envelope[j], precision / 2))
- return 'fail'
+ pytest.fail('%f, %f' % (expected_envelopes[i][j] - envelope[j], precision / 2))
i = i + 1
feat = lyr.GetNextFeature()
ogr_ds.ReleaseResultSet(lyr)
ogr_ds.Destroy()
- return 'success'
-
###############################################################################
# Test with -fl option and -3d option
-def contour_2():
+def test_contour_2():
try:
os.remove('tmp/contour.shp')
@@ -169,40 +159,30 @@ def contour_2():
lyr = ogr_ds.ExecuteSQL("select * from contour order by elev asc")
- if lyr.GetFeatureCount() != len(expected_envelopes):
- print('Got %d features. Expected %d' % (lyr.GetFeatureCount(), len(expected_envelopes)))
- return 'fail'
+ assert lyr.GetFeatureCount() == len(expected_envelopes)
i = 0
feat = lyr.GetNextFeature()
while feat is not None:
- if feat.GetGeometryRef().GetZ(0) != expected_height[i]:
- print('Got %f as z. Expected %f' % (feat.GetGeometryRef().GetZ(0), expected_height[i]))
- return 'fail'
+ assert feat.GetGeometryRef().GetZ(0) == expected_height[i]
envelope = feat.GetGeometryRef().GetEnvelope()
- if feat.GetField('elev') != expected_height[i]:
- print('Got %f. Expected %f' % (feat.GetField('elev'), expected_height[i]))
- return 'fail'
+ assert feat.GetField('elev') == expected_height[i]
for j in range(4):
if abs(expected_envelopes[i][j] - envelope[j]) > precision / 2 * 1.001:
print('i=%d, wkt=%s' % (i, feat.GetGeometryRef().ExportToWkt()))
print(feat.GetGeometryRef().GetEnvelope())
- print(expected_envelopes[i])
- print('%f, %f' % (expected_envelopes[i][j] - envelope[j], precision / 2))
- return 'fail'
+ pytest.fail('%f, %f' % (expected_envelopes[i][j] - envelope[j], precision / 2))
i = i + 1
feat = lyr.GetNextFeature()
ogr_ds.ReleaseResultSet(lyr)
ogr_ds.Destroy()
- return 'success'
-
###############################################################################
#
-def contour_real_world_case():
+def test_contour_real_world_case():
ogr_ds = ogr.GetDriverByName('Memory').CreateDataSource('')
ogr_lyr = ogr_ds.CreateLayer('contour', geom_type=ogr.wkbLineString)
@@ -216,17 +196,13 @@ def contour_real_world_case():
ds = None
ogr_lyr.SetAttributeFilter('elev = 330')
- if ogr_lyr.GetFeatureCount() != 1:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ogr_lyr.GetFeatureCount() == 1
f = ogr_lyr.GetNextFeature()
- if ogrtest.check_feature_geometry(f, 'LINESTRING (4.50497512437811 11.5,4.5 11.501996007984,3.5 11.8333333333333,2.5 11.5049751243781,2.490099009901 11.5,2.0 10.5,2.5 10.1666666666667,3.0 9.5,3.5 9.21428571428571,4.49800399201597 8.5,4.5 8.49857346647646,5.5 8.16666666666667,6.5 8.0,7.5 8.0,8.0 7.5,8.5 7.0,9.490099009901 6.5,9.5 6.49667774086379,10.5 6.16666666666667,11.4950248756219 5.5,11.5 5.49833610648919,12.5 5.49667774086379,13.5 5.49800399201597,13.501996007984 5.5,13.5 5.50199600798403,12.501996007984 6.5,12.5 6.50142653352354,11.5 6.509900990099,10.509900990099 7.5,10.5 7.50142653352354,9.5 7.9,8.50332225913621 8.5,8.5 8.50249376558603,7.83333333333333 9.5,7.5 10.0,7.0 10.5,6.5 10.7857142857143,5.5 11.1666666666667,4.50497512437811 11.5)', 0.01) != 0:
- return 'fail'
- return 'success'
+ assert ogrtest.check_feature_geometry(f, 'LINESTRING (4.50497512437811 11.5,4.5 11.501996007984,3.5 11.8333333333333,2.5 11.5049751243781,2.490099009901 11.5,2.0 10.5,2.5 10.1666666666667,3.0 9.5,3.5 9.21428571428571,4.49800399201597 8.5,4.5 8.49857346647646,5.5 8.16666666666667,6.5 8.0,7.5 8.0,8.0 7.5,8.5 7.0,9.490099009901 6.5,9.5 6.49667774086379,10.5 6.16666666666667,11.4950248756219 5.5,11.5 5.49833610648919,12.5 5.49667774086379,13.5 5.49800399201597,13.501996007984 5.5,13.5 5.50199600798403,12.501996007984 6.5,12.5 6.50142653352354,11.5 6.509900990099,10.509900990099 7.5,10.5 7.50142653352354,9.5 7.9,8.50332225913621 8.5,8.5 8.50249376558603,7.83333333333333 9.5,7.5 10.0,7.0 10.5,6.5 10.7857142857143,5.5 11.1666666666667,4.50497512437811 11.5)', 0.01) == 0
# Test with -p option (polygonize)
-def contour_3():
+def test_contour_3():
try:
os.remove('tmp/contour.shp')
@@ -270,63 +246,40 @@ def contour_3():
lyr = ogr_ds.ExecuteSQL("select * from contour order by elevMin asc")
- if lyr.GetFeatureCount() != len(expected_envelopes):
- print('Got %d features. Expected %d' % (lyr.GetFeatureCount(), len(expected_envelopes)))
- return 'fail'
+ assert lyr.GetFeatureCount() == len(expected_envelopes)
i = 0
feat = lyr.GetNextFeature()
while feat is not None:
if i < 3 and feat.GetField('elevMax') != expected_height[i]:
- print('Got %f as z. Expected %f' % (feat.GetField('elevMax'), expected_height[i]))
- return 'fail'
+ pytest.fail('Got %f as z. Expected %f' % (feat.GetField('elevMax'), expected_height[i]))
elif i > 0 and i < 3 and feat.GetField('elevMin') != expected_height[i-1]:
- print('Got %f as z. Expected %f' % (feat.GetField('elevMin'), expected_height[i-1]))
- return 'fail'
+ pytest.fail('Got %f as z. Expected %f' % (feat.GetField('elevMin'), expected_height[i-1]))
envelope = feat.GetGeometryRef().GetEnvelope()
for j in range(4):
if abs(expected_envelopes[i][j] - envelope[j]) > precision / 2 * 1.001:
print('i=%d, wkt=%s' % (i, feat.GetGeometryRef().ExportToWkt()))
print(feat.GetGeometryRef().GetEnvelope())
- print(expected_envelopes[i])
- print('%f, %f' % (expected_envelopes[i][j] - envelope[j], precision / 2))
- return 'fail'
+ pytest.fail('%f, %f' % (expected_envelopes[i][j] - envelope[j], precision / 2))
i = i + 1
feat = lyr.GetNextFeature()
ogr_ds.ReleaseResultSet(lyr)
ogr_ds.Destroy()
- return 'success'
-
###############################################################################
# Cleanup
-def contour_cleanup():
+def test_contour_cleanup():
ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/contour.shp')
try:
os.remove('tmp/gdal_contour.tif')
except OSError:
pass
- return 'success'
-
-
-gdaltest_list = [
- contour_1,
- contour_2,
- contour_real_world_case,
- contour_3,
- contour_cleanup
-]
-
-
-if __name__ == '__main__':
+
- gdaltest.setup_run('contour')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/cutline.py b/autotest/alg/cutline.py
index ffacaa73d128..8dc96d8b263a 100755
--- a/autotest/alg/cutline.py
+++ b/autotest/alg/cutline.py
@@ -30,18 +30,17 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
from osgeo import gdal
import ogrtest
import gdaltest
+import pytest
###############################################################################
-def cutline_1():
+def test_cutline_1():
tst = gdaltest.GDALTest('VRT', 'cutline_noblend.vrt', 1, 11409)
return tst.testOpen()
@@ -49,10 +48,10 @@ def cutline_1():
###############################################################################
-def cutline_2():
+def test_cutline_2():
if not ogrtest.have_geos():
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('VRT', 'cutline_blend.vrt', 1, 21395)
return tst.testOpen()
@@ -60,10 +59,10 @@ def cutline_2():
###############################################################################
-def cutline_3():
+def test_cutline_3():
if not ogrtest.have_geos():
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('VRT', 'cutline_multipolygon.vrt', 1, 20827)
return tst.testOpen()
@@ -71,10 +70,10 @@ def cutline_3():
###############################################################################
-def cutline_4():
+def test_cutline_4():
if not ogrtest.have_geos():
- return 'skip'
+ pytest.skip()
ds = gdal.Translate('/vsimem/utmsmall.tif', '../gcore/data/utmsmall.tif')
ds.BuildOverviews('NEAR', [2])
@@ -113,28 +112,11 @@ def cutline_4():
""")
out_ds = gdal.Translate('', ds, options='-of MEM -outsize 50%% 50%%')
cs = out_ds.GetRasterBand(1).Checksum()
- if cs != 5170:
- print(cs)
- return 'fail'
+ assert cs == 5170
gdal.Unlink('/vsimem/utmsmall.tif')
- return 'success'
-
###############################################################################
-gdaltest_list = [
- cutline_1,
- cutline_2,
- cutline_3,
- cutline_4
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('cutline')
-
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/dither.py b/autotest/alg/dither.py
index 72b301fac490..6233f6399c5a 100755
--- a/autotest/alg/dither.py
+++ b/autotest/alg/dither.py
@@ -29,19 +29,17 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Test
-def dither_1():
+def test_dither_1():
drv = gdal.GetDriverByName('GTiff')
@@ -69,9 +67,7 @@ def dither_1():
dst_band = None
dst_ds = None
- if ct.GetCount() != nColors:
- gdaltest.post_reason('color table size wrong')
- return 'fail'
+ assert ct.GetCount() == nColors, 'color table size wrong'
ref_ct = [(36, 48, 32, 255), (92, 120, 20, 255), (88, 96, 20, 255), (92, 132, 56, 255),
(0, 0, 0, 255), (96, 152, 24, 255), (60, 112, 32, 255), (164, 164, 108, 255)]
@@ -83,29 +79,19 @@ def dither_1():
for j in range(4):
if ct_data[j] != ref_data[j]:
- gdaltest.post_reason('color table mismatch')
for k in range(nColors):
print(ct.GetColorEntry(k))
print(ref_ct[k])
- return 'fail'
+ pytest.fail('color table mismatch')
if cs == cs_expected or gdal.GetConfigOption('CPL_DEBUG', 'OFF') != 'ON':
drv.Delete('tmp/rgbsmall.tif')
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
+ pytest.fail('got wrong checksum')
- return 'success'
+
-gdaltest_list = [
- dither_1
-]
-
-if __name__ == '__main__':
- gdaltest.setup_run('dither')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/polygonize.py b/autotest/alg/polygonize.py
index 84e98c9ed094..41bc879ba4ff 100755
--- a/autotest/alg/polygonize.py
+++ b/autotest/alg/polygonize.py
@@ -29,11 +29,8 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
-import gdaltest
import ogrtest
from osgeo import gdal, ogr
@@ -42,7 +39,7 @@
# Test a fairly simple case, with nodata masking.
-def polygonize_1(is_int_polygonize=True):
+def test_polygonize_1(is_int_polygonize=True):
src_ds = gdal.Open('data/polygonize_in.grd')
src_band = src_ds.GetRasterBand(1)
@@ -61,16 +58,12 @@ def polygonize_1(is_int_polygonize=True):
result = gdal.Polygonize(src_band, src_band.GetMaskBand(), mem_layer, 0)
else:
result = gdal.FPolygonize(src_band, src_band.GetMaskBand(), mem_layer, 0)
- if result != 0:
- gdaltest.post_reason('Polygonize failed')
- return 'fail'
+ assert result == 0, 'Polygonize failed'
# Confirm we get the set of expected features in the output layer.
expected_feature_number = 13
- if mem_layer.GetFeatureCount() != expected_feature_number:
- gdaltest.post_reason('GetFeatureCount() returned %d instead of %d' % (mem_layer.GetFeatureCount(), expected_feature_number))
- return 'fail'
+ assert mem_layer.GetFeatureCount() == expected_feature_number
expect = [107, 123, 115, 115, 140, 148, 123, 140, 156,
100, 101, 102, 103]
@@ -85,17 +78,17 @@ def polygonize_1(is_int_polygonize=True):
tr = 0
feat_read.Destroy()
- return 'success' if tr else 'fail'
+ assert tr
-def polygonize_1_float():
- return polygonize_1(is_int_polygonize=False)
+def test_polygonize_1_float():
+ return test_polygonize_1(is_int_polygonize=False)
###############################################################################
# Test a simple case without masking.
-def polygonize_2():
+def test_polygonize_2():
src_ds = gdal.Open('data/polygonize_in.grd')
src_band = src_ds.GetRasterBand(1)
@@ -111,29 +104,25 @@ def polygonize_2():
# run the algorithm.
result = gdal.Polygonize(src_band, None, mem_layer, 0)
- if result != 0:
- gdaltest.post_reason('Polygonize failed')
- return 'fail'
+ assert result == 0, 'Polygonize failed'
# Confirm we get the set of expected features in the output layer.
expected_feature_number = 17
- if mem_layer.GetFeatureCount() != expected_feature_number:
- gdaltest.post_reason('GetFeatureCount() returned %d instead of %d' % (mem_layer.GetFeatureCount(), expected_feature_number))
- return 'fail'
+ assert mem_layer.GetFeatureCount() == expected_feature_number
expect = [107, 123, 115, 132, 115, 132, 140, 132, 148, 123, 140,
132, 156, 100, 101, 102, 103]
tr = ogrtest.check_features_against_list(mem_layer, 'DN', expect)
- return 'success' if tr else 'fail'
+ assert tr
###############################################################################
# A more involved case with a complex looping.
-def polygonize_3():
+def test_polygonize_3():
src_ds = gdal.Open('data/polygonize_in_2.grd')
src_band = src_ds.GetRasterBand(1)
@@ -149,16 +138,12 @@ def polygonize_3():
# run the algorithm.
result = gdal.Polygonize(src_band, None, mem_layer, 0)
- if result != 0:
- gdaltest.post_reason('Polygonize failed')
- return 'fail'
+ assert result == 0, 'Polygonize failed'
# Confirm we get the expected count of features.
expected_feature_number = 125
- if mem_layer.GetFeatureCount() != expected_feature_number:
- gdaltest.post_reason('GetFeatureCount() returned %d instead of %d' % (mem_layer.GetFeatureCount(), expected_feature_number))
- return 'fail'
+ assert mem_layer.GetFeatureCount() == expected_feature_number
# check at least one geometry.
mem_layer.SetAttributeFilter('dn = 0')
@@ -170,13 +155,13 @@ def polygonize_3():
tr = 1
feat_read.Destroy()
- return 'success' if tr else 'fail'
+ assert tr
###############################################################################
# Test a simple case without masking but with 8-connectedness.
-def polygonize_4():
+def test_polygonize_4():
src_ds = gdal.Open('data/polygonize_in.grd')
src_band = src_ds.GetRasterBand(1)
@@ -192,37 +177,19 @@ def polygonize_4():
# run the algorithm.
result = gdal.Polygonize(src_band, None, mem_layer, 0, ["8CONNECTED=8"])
- if result != 0:
- gdaltest.post_reason('Polygonize failed')
- return 'fail'
+ assert result == 0, 'Polygonize failed'
# Confirm we get the set of expected features in the output layer.
expected_feature_number = 16
- if mem_layer.GetFeatureCount() != expected_feature_number:
- gdaltest.post_reason('GetFeatureCount() returned %d instead of %d' % (mem_layer.GetFeatureCount(), expected_feature_number))
- return 'fail'
+ assert mem_layer.GetFeatureCount() == expected_feature_number
expect = [107, 123, 132, 115, 132, 115, 140, 148,
123, 140, 132, 156, 100, 101, 102, 103]
tr = ogrtest.check_features_against_list(mem_layer, 'DN', expect)
- return 'success' if tr else 'fail'
+ assert tr
-gdaltest_list = [
- polygonize_1,
- polygonize_1_float,
- polygonize_2,
- polygonize_3,
- polygonize_4
-]
-if __name__ == '__main__':
-
- gdaltest.setup_run('polygonize')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/proximity.py b/autotest/alg/proximity.py
index 8276b165c75a..ba1f98c5c40c 100755
--- a/autotest/alg/proximity.py
+++ b/autotest/alg/proximity.py
@@ -28,19 +28,17 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Test a fairly default case.
-def proximity_1():
+def test_proximity_1():
drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/pat.tif')
@@ -63,15 +61,13 @@ def proximity_1():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Try several options
-def proximity_2():
+def test_proximity_2():
drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/pat.tif')
@@ -98,15 +94,13 @@ def proximity_2():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Try input nodata option
-def proximity_3():
+def test_proximity_3():
drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/pat.tif')
@@ -133,21 +127,7 @@ def proximity_3():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
-
-gdaltest_list = [
- proximity_1,
- proximity_2,
- proximity_3
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('proximity')
+ pytest.fail('got wrong checksum')
+
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/rasterize.py b/autotest/alg/rasterize.py
index 66ba514800c5..19a0cc67c42d 100755
--- a/autotest/alg/rasterize.py
+++ b/autotest/alg/rasterize.py
@@ -29,20 +29,18 @@
###############################################################################
import struct
-import sys
-sys.path.append('../pymod')
-import gdaltest
import ogrtest
from osgeo import gdal, ogr, osr
+import pytest
###############################################################################
# Simple polygon rasterization.
-def rasterize_1():
+def test_rasterize_1():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
@@ -84,10 +82,7 @@ def rasterize_1():
err = gdal.RasterizeLayer(target_ds, [3, 2, 1], rast_mem_lyr,
burn_values=[200, 220, 240])
- if err != 0:
- print(err)
- gdaltest.post_reason('got non-zero result code from RasterizeLayer')
- return 'fail'
+ assert err == 0, 'got non-zero result code from RasterizeLayer'
# Check results.
@@ -95,18 +90,15 @@ def rasterize_1():
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
- gdaltest.post_reason('Did not get expected image checksum')
-
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_1.tif', target_ds)
- return 'fail'
-
- return 'success'
+ pytest.fail('Did not get expected image checksum')
+
###############################################################################
# Test rasterization with ALL_TOUCHED.
-def rasterize_2():
+def test_rasterize_2():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
@@ -130,10 +122,7 @@ def rasterize_2():
options=["ALL_TOUCHED=TRUE"])
gdal.PopErrorHandler()
- if err != 0:
- print(err)
- gdaltest.post_reason('got non-zero result code from RasterizeLayer')
- return 'fail'
+ assert err == 0, 'got non-zero result code from RasterizeLayer'
# Check results.
@@ -141,18 +130,15 @@ def rasterize_2():
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
- gdaltest.post_reason('Did not get expected image checksum')
-
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_2.tif', target_ds)
- return 'fail'
-
- return 'success'
+ pytest.fail('Did not get expected image checksum')
+
###############################################################################
# Rasterization with BURN_VALUE_FROM.
-def rasterize_3():
+def test_rasterize_3():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
@@ -187,10 +173,7 @@ def rasterize_3():
err = gdal.RasterizeLayer(target_ds, [3, 2, 1], rast_mem_lyr,
burn_values=[10, 10, 55], options=["BURN_VALUE_FROM=Z"])
- if err != 0:
- print(err)
- gdaltest.post_reason('got non-zero result code from RasterizeLayer')
- return 'fail'
+ assert err == 0, 'got non-zero result code from RasterizeLayer'
# Check results.
@@ -198,17 +181,15 @@ def rasterize_3():
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
- gdaltest.post_reason('Did not get expected image checksum')
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_3.tif', target_ds)
- return 'fail'
-
- return 'success'
+ pytest.fail('Did not get expected image checksum')
+
###############################################################################
# Rasterization with ATTRIBUTE.
-def rasterize_4():
+def test_rasterize_4():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
@@ -247,27 +228,22 @@ def rasterize_4():
err = gdal.RasterizeLayer(target_ds, [1, 2, 3], rast_mem_lyr,
options=["ATTRIBUTE=CELSIUS"])
- if err != 0:
- print(err)
- gdaltest.post_reason('got non-zero result code from RasterizeLayer')
- return 'fail'
+ assert err == 0, 'got non-zero result code from RasterizeLayer'
# Check results.
expected = 16265
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
- gdaltest.post_reason('Did not get expected image checksum')
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_4.tif', target_ds)
- return 'fail'
-
- return 'success'
+ pytest.fail('Did not get expected image checksum')
+
###############################################################################
# Rasterization with MERGE_ALG=ADD.
-def rasterize_5():
+def test_rasterize_5():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
@@ -316,10 +292,7 @@ def rasterize_5():
burn_values=[100, 110, 120],
options=["MERGE_ALG=ADD"])
- if err != 0:
- print(err)
- gdaltest.post_reason('got non-zero result code from RasterizeLayer')
- return 'fail'
+ assert err == 0, 'got non-zero result code from RasterizeLayer'
# Check results.
@@ -327,18 +300,15 @@ def rasterize_5():
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
- gdaltest.post_reason('Did not get expected image checksum')
-
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_5.tif', target_ds)
- return 'fail'
-
- return 'success'
+ pytest.fail('Did not get expected image checksum')
+
###############################################################################
# Test bug fix for #5580 (used to hang)
-def rasterize_6():
+def test_rasterize_6():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
@@ -358,22 +328,5 @@ def rasterize_6():
gdal.RasterizeLayer(mask_ds, [1], layer, burn_values=[1], options=["ALL_TOUCHED"])
- return 'success'
-
-
-gdaltest_list = [
- rasterize_1,
- rasterize_2,
- rasterize_3,
- rasterize_4,
- rasterize_5,
- rasterize_6
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('rasterize')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/reproject.py b/autotest/alg/reproject.py
index cde70c0dbbb6..24f34cb24e95 100755
--- a/autotest/alg/reproject.py
+++ b/autotest/alg/reproject.py
@@ -29,20 +29,18 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
from osgeo import osr
+import pytest
###############################################################################
# Test a trivial case.
-def reproject_1():
+def test_reproject_1():
drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('../gcore/data/byte.tif')
@@ -62,15 +60,13 @@ def reproject_1():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Test a real reprojection case.
-def reproject_2():
+def test_reproject_2():
sr = osr.SpatialReference()
sr.ImportFromEPSG(32611)
@@ -95,15 +91,13 @@ def reproject_2():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Test nodata values
-def reproject_3():
+def test_reproject_3():
data = '\x02\x7f\x7f\x02\x02\x7f\x7f\x02\x02\x7f\x7f\x02'
src_ds = gdal.GetDriverByName('MEM').Create('', 4, 3)
@@ -120,18 +114,15 @@ def reproject_3():
got_data = dst_ds.GetRasterBand(1).ReadRaster(0, 0, 6, 3).decode('latin1')
expected_data = '\x03\x7f\x7f\x7f\x03\x03\x03\x7f\x7f\x7f\x03\x03\x03\x7f\x7f\x7f\x03\x03'
if got_data != expected_data:
- gdaltest.post_reason('fail')
import struct
- print(struct.unpack('B' * 18, got_data))
- return 'fail'
-
- return 'success'
+ pytest.fail(struct.unpack('B' * 18, got_data))
+
###############################################################################
# Test warp options
-def reproject_4():
+def test_reproject_4():
data = '\x02\x7f\x7f\x02\x02\x7f\x7f\x02\x02\x7f\x7f\x02'
src_ds = gdal.GetDriverByName('MEM').Create('', 4, 3)
@@ -147,25 +138,9 @@ def reproject_4():
got_data = dst_ds.GetRasterBand(1).ReadRaster(0, 0, 6, 3).decode('latin1')
expected_data = '\x03\x7f\x7f\x7f\x03\x03\x03\x7f\x7f\x7f\x03\x03\x03\x7f\x7f\x7f\x03\x03'
if got_data != expected_data:
- gdaltest.post_reason('fail')
import struct
- print(struct.unpack('B' * 18, got_data))
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = [
- reproject_1,
- reproject_2,
- reproject_3,
- reproject_4
-]
-
-if __name__ == '__main__':
+ pytest.fail(struct.unpack('B' * 18, got_data))
- gdaltest.setup_run('reproject')
+
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/sieve.py b/autotest/alg/sieve.py
index 0486e0409600..154b7532ddc1 100755
--- a/autotest/alg/sieve.py
+++ b/autotest/alg/sieve.py
@@ -29,19 +29,17 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Test a fairly default case.
-def sieve_1():
+def test_sieve_1():
drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/sieve_src.grd')
@@ -64,15 +62,13 @@ def sieve_1():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Try eight connected.
-def sieve_2():
+def test_sieve_2():
drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/sieve_src.grd')
@@ -95,15 +91,13 @@ def sieve_2():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Do a sieve resulting in unmergable polygons.
-def sieve_3():
+def test_sieve_3():
drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/unmergable.grd')
@@ -127,15 +121,13 @@ def sieve_3():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Try the bug 2634 simplified data.
-def sieve_4():
+def test_sieve_4():
drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/sieve_2634.grd')
@@ -158,16 +150,14 @@ def sieve_4():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Same as sieve_1, but we provide a mask band
# This should yield the same result as we use an opaque band
-def sieve_5():
+def test_sieve_5():
drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/sieve_src.grd')
@@ -190,21 +180,19 @@ def sieve_5():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Performance test. When increasing the 'size' parameter, performance
# should stay roughly linear with the number of pixels (i.e. size^2)
-def sieve_6():
+def test_sieve_6():
try:
import numpy
except ImportError:
- return 'skip'
+ pytest.skip()
# Try 3002. Should run in less than 10 seconds
# size = 3002
@@ -229,16 +217,14 @@ def sieve_6():
cs = band.Checksum()
if (size == 102 and cs != 60955) or (size == 3002 and cs != 63178):
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
-
- return 'success'
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Test with nodata
-def sieve_7():
+def test_sieve_7():
gdal.FileFromMemBuffer('/vsimem/sieve_7.asc', """ncols 7
nrows 7
@@ -287,15 +273,13 @@ def sieve_7():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
+ pytest.fail('got wrong checksum')
+
###############################################################################
# Test propagation in our search of biggest neighbour
-def sieve_8():
+def test_sieve_8():
gdal.FileFromMemBuffer('/vsimem/sieve_8.asc',
"""ncols 7
@@ -336,26 +320,7 @@ def sieve_8():
if cs != cs_expected:
print('Got: ', cs)
- gdaltest.post_reason('got wrong checksum')
- return 'fail'
- return 'success'
-
-
-gdaltest_list = [
- sieve_1,
- sieve_2,
- sieve_3,
- sieve_4,
- sieve_5,
- sieve_6,
- sieve_7,
- sieve_8
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('sieve')
+ pytest.fail('got wrong checksum')
+
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/tps.py b/autotest/alg/tps.py
index 2823496f0e59..426fff879d3c 100755
--- a/autotest/alg/tps.py
+++ b/autotest/alg/tps.py
@@ -29,9 +29,7 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal, osr
@@ -40,7 +38,7 @@
# Test error case (#5586)
-def tps_1():
+def test_tps_1():
drv = gdal.GetDriverByName('MEM')
ds = drv.Create('foo', 2, 2)
@@ -58,20 +56,7 @@ def tps_1():
transformer = gdal.Transformer(ds, None,
['DST_SRS=' + utm_wkt,
'METHOD=GCP_TPS'])
- if transformer is not None:
- return 'fail'
+ assert transformer is None
- return 'success'
-gdaltest_list = [
- tps_1,
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('tps')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/transformgeoloc.py b/autotest/alg/transformgeoloc.py
index 0c0d6a01f233..34b43e40cc4a 100755
--- a/autotest/alg/transformgeoloc.py
+++ b/autotest/alg/transformgeoloc.py
@@ -30,24 +30,22 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
from osgeo import osr
+import pytest
###############################################################################
# Test a fairly default case.
-def transformgeoloc_1():
+def test_transformgeoloc_1():
try:
import numpy
except ImportError:
- return 'skip'
+ pytest.skip()
# Setup 2x2 geolocation arrays in a memory dataset with lat/long values.
@@ -82,17 +80,5 @@ def transformgeoloc_1():
print(geoloc_ds.ReadAsArray())
- return 'success'
-gdaltest_list = [
- transformgeoloc_1,
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('transform_geoloc')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/alg/warp.py b/autotest/alg/warp.py
index 7f0657c7fde2..2f03746e51c1 100755
--- a/autotest/alg/warp.py
+++ b/autotest/alg/warp.py
@@ -33,15 +33,14 @@
###############################################################################
import os
-import sys
import shutil
-sys.path.append('../pymod')
from osgeo import gdal
from osgeo import osr
import gdaltest
+import pytest
###############################################################################
# Verify that we always getting the same image when warping.
@@ -50,11 +49,11 @@
# Upsampling
-def warp_1():
+def test_warp_1():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_near.vrt')
ref_ds = gdal.Open('data/utmsmall_near.tiff')
@@ -62,18 +61,14 @@ def warp_1():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_1_short():
+def test_warp_1_short():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_near_short.vrt')
ref_ds = gdal.Open('data/utmsmall_near.tiff')
@@ -81,18 +76,14 @@ def warp_1_short():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_1_ushort():
+def test_warp_1_ushort():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_near_ushort.vrt')
ref_ds = gdal.Open('data/utmsmall_near.tiff')
@@ -100,18 +91,14 @@ def warp_1_ushort():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_1_float():
+def test_warp_1_float():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_near_float.vrt')
ref_ds = gdal.Open('data/utmsmall_near.tiff')
@@ -119,18 +106,14 @@ def warp_1_float():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_2():
+def test_warp_2():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_blinear.vrt')
ref_ds = gdal.Open('data/utmsmall_blinear.tiff')
@@ -138,18 +121,14 @@ def warp_2():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_2_short():
+def test_warp_2_short():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_blinear_short.vrt')
ref_ds = gdal.Open('data/utmsmall_blinear.tiff')
@@ -157,18 +136,14 @@ def warp_2_short():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_2_ushort():
+def test_warp_2_ushort():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_blinear_ushort.vrt')
ref_ds = gdal.Open('data/utmsmall_blinear.tiff')
@@ -176,18 +151,14 @@ def warp_2_ushort():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_2_downsize():
+def test_warp_2_downsize():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_bilinear_2.vrt')
ref_ds = gdal.Open('data/utmsmall_bilinear_2.tif')
@@ -195,18 +166,14 @@ def warp_2_downsize():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_3():
+def test_warp_3():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubic.vrt')
ref_ds = gdal.Open('data/utmsmall_cubic.tiff')
@@ -214,18 +181,14 @@ def warp_3():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_3_short():
+def test_warp_3_short():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubic_short.vrt')
ref_ds = gdal.Open('data/utmsmall_cubic.tiff')
@@ -233,18 +196,14 @@ def warp_3_short():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_3_ushort():
+def test_warp_3_ushort():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubic_ushort.vrt')
ref_ds = gdal.Open('data/utmsmall_cubic.tiff')
@@ -252,18 +211,14 @@ def warp_3_ushort():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_3_downsize():
+def test_warp_3_downsize():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubic_2.vrt')
ref_ds = gdal.Open('data/utmsmall_cubic_2.tif')
@@ -271,18 +226,14 @@ def warp_3_downsize():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_3_float_downsize():
+def test_warp_3_float_downsize():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubic_2_float.vrt')
ref_ds = gdal.Open('data/utmsmall_cubic_2.tif')
@@ -290,18 +241,14 @@ def warp_3_float_downsize():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_4():
+def test_warp_4():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubicspline.vrt')
ref_ds = gdal.Open('data/utmsmall_cubicspline.tiff')
@@ -309,18 +256,14 @@ def warp_4():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_4_short():
+def test_warp_4_short():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubicspline_short.vrt')
ref_ds = gdal.Open('data/utmsmall_cubicspline.tiff')
@@ -328,18 +271,14 @@ def warp_4_short():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_4_ushort():
+def test_warp_4_ushort():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubicspline_ushort.vrt')
ref_ds = gdal.Open('data/utmsmall_cubicspline.tiff')
@@ -347,18 +286,14 @@ def warp_4_ushort():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_4_downsize():
+def test_warp_4_downsize():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubicspline_2.vrt')
ref_ds = gdal.Open('data/utmsmall_cubicspline_2.tif')
@@ -366,18 +301,14 @@ def warp_4_downsize():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_4_short_downsize():
+def test_warp_4_short_downsize():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubicspline_wt_short.vrt')
ref_ds = gdal.Open('data/utmsmall_cubicspline_2.tif')
@@ -385,18 +316,14 @@ def warp_4_short_downsize():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_4_float_downsize():
+def test_warp_4_float_downsize():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_cubicspline_wt_float32.vrt')
ref_ds = gdal.Open('data/utmsmall_cubicspline_2.tif')
@@ -404,18 +331,14 @@ def warp_4_float_downsize():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_5():
+def test_warp_5():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_lanczos.vrt')
ref_ds = gdal.Open('data/utmsmall_lanczos.tiff')
@@ -423,18 +346,14 @@ def warp_5():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_5_downsize():
+def test_warp_5_downsize():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_lanczos_2.vrt')
ref_ds = gdal.Open('data/utmsmall_lanczos_2.tif')
@@ -442,53 +361,49 @@ def warp_5_downsize():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Downsampling
-def warp_6():
+def test_warp_6():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('VRT', 'utmsmall_ds_near.vrt', 1, 4770)
return tst.testOpen()
-def warp_7():
+def test_warp_7():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('VRT', 'utmsmall_ds_blinear.vrt', 1, 4755)
return tst.testOpen()
-def warp_8():
+def test_warp_8():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('VRT', 'utmsmall_ds_cubic.vrt', 1, 4833)
return tst.testOpen()
-def warp_9():
+def test_warp_9():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_ds_cubicspline.vrt')
ref_ds = gdal.Open('data/utmsmall_ds_cubicspline.tiff')
@@ -496,18 +411,14 @@ def warp_9():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
+ assert maxdiff <= 1, 'Image too different from reference'
- return 'success'
-
-def warp_10():
+def test_warp_10():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_ds_lanczos.vrt')
ref_ds = gdal.Open('data/utmsmall_ds_lanczos.tiff')
@@ -515,18 +426,14 @@ def warp_10():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
-def warp_11():
+def test_warp_11():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('VRT', 'rgbsmall_dstalpha.vrt', 4, 30658)
@@ -535,11 +442,11 @@ def warp_11():
# Test warping an empty RGBA with bilinear resampling
-def warp_12():
+def test_warp_12():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/empty.tif', 20, 20, 4)
ds.GetRasterBand(1).Fill(0)
@@ -560,11 +467,11 @@ def warp_12():
# Test warping an empty RGBA with cubic resampling
-def warp_13():
+def test_warp_13():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/empty.tif', 20, 20, 4)
ds.GetRasterBand(1).Fill(0)
@@ -585,11 +492,11 @@ def warp_13():
# Test warping an empty RGBA with cubic spline resampling
-def warp_14():
+def test_warp_14():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/empty.tif', 20, 20, 4)
ds.GetRasterBand(1).Fill(0)
@@ -610,11 +517,11 @@ def warp_14():
# Test GWKNearestFloat with transparent source alpha band
-def warp_15():
+def test_warp_15():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/test.tif', 20, 20, 4)
ds.GetRasterBand(1).Fill(0)
@@ -635,11 +542,11 @@ def warp_15():
# Test GWKNearestFloat with opaque source alpha band
-def warp_16():
+def test_warp_16():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/test.tif', 20, 20, 4)
ds.GetRasterBand(1).Fill(255)
@@ -660,11 +567,11 @@ def warp_16():
# Test GWKNearestShort with transparent source alpha band
-def warp_17():
+def test_warp_17():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/test.tif', 20, 20, 4)
ds.GetRasterBand(1).Fill(0)
@@ -685,11 +592,11 @@ def warp_17():
# Test GWKNearestShort with opaque source alpha band
-def warp_18():
+def test_warp_18():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/test.tif', 20, 20, 4)
ds.GetRasterBand(1).Fill(255)
@@ -727,23 +634,18 @@ def warp_19_internal(size, datatype, resampling_string):
gdaltest.tiff_drv.Delete('tmp/testwarp.tif')
- if checksum != checksum_ref:
- print('got %d, expected %d' % (checksum, checksum_ref))
- gdaltest.post_reason('Result different from source')
- return 'fail'
+ assert checksum == checksum_ref
gdaltest.tiff_drv.Delete('tmp/test.tif')
- return 'success'
-
# Test all data types and resampling methods for very small images
# to test edge behaviour
-def warp_19():
+def test_warp_19():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
datatypes = [gdal.GDT_Byte,
gdal.GDT_Int16,
@@ -765,19 +667,15 @@ def warp_19():
print('Testing size = %d ...' % size)
for method in methods:
for datatype in datatypes:
- if warp_19_internal(size, datatype, method) != 'success':
- print('fail with size = %d, data type = %d and method %s' % (size, datatype, method))
- return 'fail'
-
- return 'success'
+ warp_19_internal(size, datatype, method)
# Test fix for #2724 (initialization of destination area to nodata in warped VRT)
-def warp_20():
+def test_warp_20():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('VRT', 'white_nodata.vrt', 1, 1705)
@@ -787,7 +685,7 @@ def warp_20():
# Test overviews on warped VRT files
-def warp_21():
+def test_warp_21():
shutil.copy('data/utmsmall_near.vrt', 'tmp/warp_21.vrt')
@@ -797,7 +695,7 @@ def warp_21():
ds = gdal.Open('tmp/warp_21.vrt')
if ds.GetRasterBand(1).GetOverviewCount() != 1:
- return 'skip'
+ pytest.skip()
ds.GetRasterBand(1).GetOverview(0).Checksum()
@@ -805,14 +703,12 @@ def warp_21():
os.remove('tmp/warp_21.vrt')
- return 'success'
-
###############################################################################
# Test warping with datasets which are "bigger" than the wm parameter.
# Would have detected issue of #3458
-def warp_22():
+def test_warp_22():
# Generate source image with non uniform data
w = 1001
@@ -866,7 +762,7 @@ def warp_22():
# Test warping with datasets where some RasterIO() requests involve nBufXSize == 0 (#3582)
-def warp_23():
+def test_warp_23():
gcp1 = gdal.GCP()
gcp1.GCPPixel = 3213
@@ -943,40 +839,32 @@ def warp_23():
# left pixel being not set in GWKBilinearResample() case)
-def warp_24():
+def test_warp_24():
ds_ref = gdal.Open('data/test3658.tif')
cs_ref = ds_ref.GetRasterBand(1).Checksum()
ds = gdal.Warp('', ds_ref, options='-of MEM -r bilinear')
cs = ds.GetRasterBand(1).Checksum()
- if cs != cs_ref:
- gdaltest.post_reason('did not get expected checksum')
- return 'fail'
-
- return 'success'
+ assert cs == cs_ref, 'did not get expected checksum'
###############################################################################
# Test -refine_gcps (#4143)
-def warp_25():
+def test_warp_25():
ds = gdal.Open('data/refine_gcps.vrt')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 4672:
- gdaltest.post_reason('did not get expected checksum')
- return 'fail'
-
- return 'success'
+ assert cs == 4672, 'did not get expected checksum'
###############################################################################
# Test serializing and deserializing TPS transformer
-def warp_26():
+def test_warp_26():
gdal.Translate('tmp/warp_25_gcp.vrt', '../gcore/data/byte.tif',
options='-of VRT -gcp 0 0 0 20 -gcp 0 20 0 0 '
@@ -988,15 +876,11 @@ def warp_26():
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 4672:
- gdaltest.post_reason('did not get expected checksum')
- return 'fail'
+ assert cs == 4672, 'did not get expected checksum'
os.unlink('tmp/warp_25_gcp.vrt')
os.unlink('tmp/warp_25_warp.vrt')
- return 'success'
-
###############################################################################
# Pure Python reprojection example. Nothing particular, just make use of existing
# API.
@@ -1007,7 +891,7 @@ def warp_27_progress_callback(pct, message, user_data):
return 1 # 1 to continue, 0 to stop
-def warp_27():
+def test_warp_27():
# Open source dataset
src_ds = gdal.Open('../gcore/data/byte.tif')
@@ -1064,38 +948,29 @@ def warp_27():
ref_cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != ref_cs:
- return 'fail'
+ assert cs == ref_cs
gdal.Unlink('tmp/warp_27.tif')
gdal.Unlink('tmp/warp_27_ref.tif')
- return 'success'
-
###############################################################################
# Test reading a VRT with a destination alpha band, but no explicit
# INIT_DEST setting
-def warp_28():
+def test_warp_28():
ds = gdal.Open('data/utm_alpha_noinit.vrt')
cs1 = ds.GetRasterBand(1).Checksum()
cs2 = ds.GetRasterBand(2).Checksum()
- if cs1 == 0 or cs2 == 0:
- gdaltest.post_reason('bad checksum')
- print(cs1)
- print(cs2)
- return 'fail'
+ assert not (cs1 == 0 or cs2 == 0), 'bad checksum'
ds = None
- return 'success'
-
###############################################################################
# Test multi-thread computations
-def warp_29():
+def test_warp_29():
ds = gdal.Open('data/white_nodata.vrt')
cs_monothread = ds.GetRasterBand(1).Checksum()
@@ -1110,9 +985,7 @@ def warp_29():
gdal.SetConfigOption('GDAL_NUM_THREADS', old_val)
gdal.SetConfigOption('WARP_THREAD_CHUNK_SIZE', None)
- if cs_monothread != cs_multithread:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert cs_monothread == cs_multithread
old_val = gdal.GetConfigOption('GDAL_NUM_THREADS')
gdal.SetConfigOption('GDAL_NUM_THREADS', '2')
@@ -1123,9 +996,7 @@ def warp_29():
gdal.SetConfigOption('GDAL_NUM_THREADS', old_val)
gdal.SetConfigOption('WARP_THREAD_CHUNK_SIZE', None)
- if cs_monothread != cs_multithread:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert cs_monothread == cs_multithread
src_ds = gdal.Open('../gcore/data/byte.tif')
@@ -1138,9 +1009,7 @@ def warp_29():
gdal.SetConfigOption('WARP_THREAD_CHUNK_SIZE', None)
ds = None
- if got_cs != src_ds.GetRasterBand(1).Checksum():
- gdaltest.post_reason('failed')
- return 'fail'
+ assert got_cs == src_ds.GetRasterBand(1).Checksum()
ds = gdal.Open('data/byte_tps.vrt')
old_val = gdal.GetConfigOption('GDAL_NUM_THREADS')
@@ -1151,14 +1020,10 @@ def warp_29():
gdal.SetConfigOption('WARP_THREAD_CHUNK_SIZE', None)
ds = None
- if got_cs != src_ds.GetRasterBand(1).Checksum():
- gdaltest.post_reason('failed')
- return 'fail'
+ assert got_cs == src_ds.GetRasterBand(1).Checksum()
src_ds = None
- return 'success'
-
###############################################################################
# Test warping interruption
@@ -1168,7 +1033,7 @@ def warp_30_progress_callback(pct, message, user_data):
return bool(pct <= 0.2)
-def warp_30():
+def test_warp_30():
# Open source dataset
src_ds = gdal.Open('../gcore/data/byte.tif')
@@ -1215,9 +1080,7 @@ def warp_30():
cbk_user_data) # Progress callback user data
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert ret != 0
old_val = gdal.GetConfigOption('GDAL_NUM_THREADS')
gdal.SetConfigOption('GDAL_NUM_THREADS', '2')
@@ -1234,22 +1097,18 @@ def warp_30():
gdal.PopErrorHandler()
gdal.SetConfigOption('GDAL_NUM_THREADS', old_val)
- if ret == 0:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert ret != 0
gdal.Unlink('/vsimem/warp_30.tif')
- return 'success'
-
# Average (Byte)
-def warp_31():
+def test_warp_31():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_average.vrt')
ref_ds = gdal.Open('data/utmsmall_average.tiff')
@@ -1257,20 +1116,16 @@ def warp_31():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Average (Float)
-def warp_32():
+def test_warp_32():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_average_float.vrt')
ref_ds = gdal.Open('data/utmsmall_average_float.tiff')
@@ -1278,20 +1133,16 @@ def warp_32():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Mode (Byte)
-def warp_33():
+def test_warp_33():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_mode.vrt')
ref_ds = gdal.Open('data/utmsmall_mode.tiff')
@@ -1299,20 +1150,16 @@ def warp_33():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Mode (Int16)
-def warp_34():
+def test_warp_34():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_mode_int16.vrt')
ref_ds = gdal.Open('data/utmsmall_mode_int16.tiff')
@@ -1320,20 +1167,16 @@ def warp_34():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Mode (Int16 - signed with negative values)
-def warp_35():
+def test_warp_35():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall-int16-neg_mode.vrt')
ref_ds = gdal.Open('data/utmsmall-int16-neg_mode.tiff')
@@ -1341,20 +1184,16 @@ def warp_35():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Mode (Int32) - this uses algorithm 2 (inefficient)
-def warp_36():
+def test_warp_36():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_mode_int32.vrt')
ref_ds = gdal.Open('data/utmsmall_mode_int32.tiff')
@@ -1362,17 +1201,13 @@ def warp_36():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
###############################################################################
# Test a few error cases
-def warp_37():
+def test_warp_37():
# Open source dataset
src_ds = gdal.Open('../gcore/data/byte.tif')
@@ -1386,9 +1221,7 @@ def warp_37():
tmp_ds = gdal.AutoCreateWarpedVRT(src_ds, None, dst_wkt)
gdal.PopErrorHandler()
gdal.ErrorReset()
- if tmp_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert tmp_ds is None
# Incompatible projection (UTM 40 is on the other side of the earth w.r.t UTM 11)
sr = osr.SpatialReference()
@@ -1400,17 +1233,13 @@ def warp_37():
tmp_ds = gdal.AutoCreateWarpedVRT(src_ds, None, dst_wkt)
gdal.PopErrorHandler()
gdal.ErrorReset()
- if tmp_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert tmp_ds is None
###############################################################################
# Test a warp with GCPs on the *destination* image.
-def warp_38():
+def test_warp_38():
# Create an output file with GCPs.
out_file = 'tmp/warp_38.tif'
@@ -1434,19 +1263,15 @@ def warp_38():
# Should exactly match the source file.
exp_cs = 30546
- if cs != exp_cs:
- gdaltest.post_reason('Got %d instead of expected checksum %d.' % (
- cs, exp_cs))
- return 'fail'
+ assert cs == exp_cs
os.unlink(out_file)
- return 'success'
###############################################################################
# Test a warp with GCPs for TPS on the *destination* image.
-def warp_39():
+def test_warp_39():
# Create an output file with GCPs.
out_file = 'tmp/warp_39.tif'
@@ -1470,23 +1295,19 @@ def warp_39():
# Should exactly match the source file.
exp_cs = 30546
- if cs != exp_cs:
- gdaltest.post_reason('Got %d instead of expected checksum %d.' % (
- cs, exp_cs))
- return 'fail'
+ assert cs == exp_cs
os.unlink(out_file)
- return 'success'
###############################################################################
# test average (#5311)
-def warp_40():
+def test_warp_40():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/2by2.vrt')
ref_ds = gdal.Open('data/2by2.tif')
@@ -1494,17 +1315,13 @@ def warp_40():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
###############################################################################
# test GDALSuggestedWarpOutput (#5693)
-def warp_41():
+def test_warp_41():
src_ds = gdal.Open("""
-2.0037508340000000e+07, 5.9716428339481353e-01, 0.0000000000000000e+00, 2.0037508340000000e+07, 0.0000000000000000e+00, -5.9716428339481353e-01
@@ -1520,31 +1337,24 @@ def warp_41():
""")
vrt_ds = gdal.AutoCreateWarpedVRT(src_ds, None, None, gdal.GRA_NearestNeighbour, 0.3)
- if vrt_ds.RasterXSize != src_ds.RasterXSize:
- gdaltest.post_reason('fail')
- return 'fail'
- if vrt_ds.RasterYSize != src_ds.RasterYSize:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert vrt_ds.RasterXSize == src_ds.RasterXSize
+ assert vrt_ds.RasterYSize == src_ds.RasterYSize
src_gt = src_ds.GetGeoTransform()
vrt_gt = vrt_ds.GetGeoTransform()
for i in range(6):
- if abs(src_gt[i] - vrt_gt[i]) > 1e-5:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert abs(src_gt[i] - vrt_gt[i]) <= 1e-5
+
###############################################################################
# Maximum
-def warp_42():
+def test_warp_42():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_max.vrt')
ref_ds = gdal.Open('data/utmsmall_max.tif')
@@ -1552,20 +1362,16 @@ def warp_42():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Minimum
-def warp_43():
+def test_warp_43():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_min.vrt')
ref_ds = gdal.Open('data/utmsmall_min.tif')
@@ -1573,20 +1379,16 @@ def warp_43():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Median
-def warp_44():
+def test_warp_44():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_med.vrt')
ref_ds = gdal.Open('data/utmsmall_med.tif')
@@ -1594,20 +1396,16 @@ def warp_44():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Quartile 1
-def warp_45():
+def test_warp_45():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_Q1.vrt')
ref_ds = gdal.Open('data/utmsmall_Q1.tif')
@@ -1615,20 +1413,16 @@ def warp_45():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Quartile 3
-def warp_46():
+def test_warp_46():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall_Q3.vrt')
ref_ds = gdal.Open('data/utmsmall_Q3.tif')
@@ -1636,20 +1430,16 @@ def warp_46():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Maximum (Int16 - signed with negative values)
-def warp_47():
+def test_warp_47():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall-int16-neg_max.vrt')
ref_ds = gdal.Open('data/utmsmall-int16-neg_max.tif')
@@ -1657,20 +1447,16 @@ def warp_47():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Minimum (Int16 - signed with negative values)
-def warp_48():
+def test_warp_48():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall-int16-neg_min.vrt')
ref_ds = gdal.Open('data/utmsmall-int16-neg_min.tif')
@@ -1678,20 +1464,16 @@ def warp_48():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Median (Int16 - signed with negative values)
-def warp_49():
+def test_warp_49():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall-int16-neg_med.vrt')
ref_ds = gdal.Open('data/utmsmall-int16-neg_med.tif')
@@ -1699,20 +1481,16 @@ def warp_49():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Quartile 1 (Int16 - signed with negative values)
-def warp_50():
+def test_warp_50():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall-int16-neg_Q1.vrt')
ref_ds = gdal.Open('data/utmsmall-int16-neg_Q1.tif')
@@ -1720,20 +1498,16 @@ def warp_50():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
# Quartile 3 (Int16 - signed with negative values)
-def warp_51():
+def test_warp_51():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.tiff_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/utmsmall-int16-neg_Q3.vrt')
ref_ds = gdal.Open('data/utmsmall-int16-neg_Q3.tif')
@@ -1741,17 +1515,13 @@ def warp_51():
ds = None
ref_ds = None
- if maxdiff > 1:
- gdaltest.post_reason('Image too different from reference')
- return 'fail'
-
- return 'success'
+ assert maxdiff <= 1, 'Image too different from reference'
###############################################################################
# Test fix for #6182
-def warp_52():
+def test_warp_52():
src_ds = gdal.GetDriverByName('MEM').Create('', 4096, 4096, 3, gdal.GDT_UInt16)
rpc = [
@@ -1787,23 +1557,16 @@ def warp_52():
resampleAlg=gdal.GRA_Cubic)
end = time.time()
- if end - start > 5:
- gdaltest.post_reason('processing time was way too long')
- return 'fail'
+ assert end - start <= 5, 'processing time was way too long'
cs = out_ds.GetRasterBand(4).Checksum()
- if cs != 3188:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 3188
###############################################################################
# Test Grey+Alpha
-def warp_53():
+def test_warp_53():
for typestr in ('Byte', 'UInt16', 'Int16'):
src_ds = gdal.Translate('', '../gcore/data/byte.tif',
@@ -1830,21 +1593,16 @@ def warp_53():
cs1 = dst_ds.GetRasterBand(1).Checksum()
cs2 = dst_ds.GetRasterBand(2).Checksum()
if cs1 not in expected_cs or cs2 not in [3903, 4138]:
- gdaltest.post_reason('fail')
print(typestr)
print(option)
- print(alg_name)
- print(cs1)
- print(cs2)
- return 'fail'
-
- return 'success'
+ pytest.fail(alg_name)
+
###############################################################################
# Test Alpha on UInt16/Int16
-def warp_54():
+def test_warp_54():
# UInt16
src_ds = gdal.Translate('', '../gcore/data/stefan_full_rgba.tif',
@@ -1853,12 +1611,7 @@ def warp_54():
for i in range(4):
expected_cs = src_ds.GetRasterBand(i + 1).Checksum()
got_cs = dst_ds.GetRasterBand(i + 1).Checksum()
- if expected_cs != got_cs:
- gdaltest.post_reason('fail')
- print(i)
- print(got_cs)
- print(expected_cs)
- return 'fail'
+ assert expected_cs == got_cs, i
# Int16
src_ds = gdal.Translate('', '../gcore/data/stefan_full_rgba.tif',
@@ -1867,12 +1620,7 @@ def warp_54():
for i in range(4):
expected_cs = src_ds.GetRasterBand(i + 1).Checksum()
got_cs = dst_ds.GetRasterBand(i + 1).Checksum()
- if expected_cs != got_cs:
- gdaltest.post_reason('fail')
- print(i)
- print(got_cs)
- print(expected_cs)
- return 'fail'
+ assert expected_cs == got_cs, i
# Test NBITS
src_ds = gdal.Translate('', '../gcore/data/stefan_full_rgba.tif',
@@ -1883,48 +1631,36 @@ def warp_54():
for i in range(4):
expected_cs = src_ds.GetRasterBand(i + 1).Checksum()
got_cs = dst_ds.GetRasterBand(i + 1).Checksum()
- if expected_cs != got_cs:
- gdaltest.post_reason('fail')
- print(i)
- print(got_cs)
- print(expected_cs)
- return 'fail'
+ assert expected_cs == got_cs, i
dst_ds = None
gdal.Unlink('/vsimem/warp_54.tif')
- return 'success'
-
###############################################################################
# Test warped VRT with source overview, target GT != GenImgProjetion target GT
# and subsampling (#6972)
-def warp_55():
+def test_warp_55():
ds = gdal.Open('data/warpedvrt_with_ovr.vrt')
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs != 25128:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 25128
ds = None
- return 'success'
-
###############################################################################
# Test bilinear interpolation when warping into same coordinate system (and
# same size). This test crops a single pixel out of a 3-by-3 image.
-def warp_56():
+def test_warp_56():
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
import numpy
except (ImportError, AttributeError):
- return 'skip'
+ pytest.skip()
pix_ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
src_ds = gdal.GetDriverByName('MEM').Create('', 3, 3)
@@ -1941,94 +1677,5 @@ def warp_56():
exp = 0 if off < 1 else 100 * (off - 1)**2
warped = pix_ds.GetRasterBand(1).ReadAsArray()[0, 0]
- if abs(warped - exp) > 0.6:
- gdaltest.post_reason('offset: {}, expected: {:.0f}, got: {}'.format(off, exp, warped))
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = [
- warp_1,
- warp_1_short,
- warp_1_ushort,
- warp_1_float,
- warp_2,
- warp_2_short,
- warp_2_ushort,
- warp_2_downsize,
- warp_3,
- warp_3_short,
- warp_3_ushort,
- warp_3_downsize,
- warp_3_float_downsize,
- warp_4,
- warp_4_short,
- warp_4_ushort,
- warp_4_downsize,
- warp_4_short_downsize,
- warp_4_float_downsize,
- warp_5,
- warp_5_downsize,
- warp_6,
- warp_7,
- warp_8,
- warp_9,
- warp_10,
- warp_11,
- warp_12,
- warp_13,
- warp_14,
- warp_15,
- warp_16,
- warp_17,
- warp_18,
- warp_19,
- warp_20,
- warp_21,
- warp_22,
- warp_23,
- warp_24,
- warp_25,
- warp_26,
- warp_27,
- warp_28,
- warp_29,
- warp_30,
- warp_31,
- warp_32,
- warp_33,
- warp_34,
- warp_35,
- warp_36,
- warp_37,
- warp_38,
- warp_39,
- warp_39,
- warp_40,
- warp_41,
- warp_42,
- warp_43,
- warp_44,
- warp_45,
- warp_46,
- warp_47,
- warp_48,
- warp_49,
- warp_50,
- warp_51,
- warp_52,
- warp_53,
- warp_54,
- warp_55,
- warp_56
-]
-# gdaltest_list = [ warp_55 ]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('warp')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ assert abs(warped - exp) <= 0.6, \
+ 'offset: {}, expected: {:.0f}, got: {}'.format(off, exp, warped)
diff --git a/autotest/conftest.py b/autotest/conftest.py
new file mode 100644
index 000000000000..f859ca16295a
--- /dev/null
+++ b/autotest/conftest.py
@@ -0,0 +1,68 @@
+# coding: utf-8
+from __future__ import absolute_import, division, print_function
+
+import os
+import sys
+
+import pytest
+
+import gdal
+
+# Put the pymod dir on the path, so modules can `import gdaltest`
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "pymod"))
+
+# put the autotest dir on the path too. This lets us import all test modules
+sys.path.insert(1, os.path.dirname(__file__))
+
+
+# These files may be non-importable, and don't contain tests anyway.
+# So we skip searching them during test collection.
+collect_ignore = ["gdrivers/netcdf_cfchecks.py"]
+
+# we set ECW to not resolve projection and datum strings to get 3.x behavior.
+gdal.SetConfigOption("ECW_DO_NOT_RESOLVE_DATUM_PROJECTION", "YES")
+
+if 'APPLY_LOCALE' in os.environ:
+ import locale
+ locale.setlocale(locale.LC_ALL, '')
+
+
+@pytest.fixture(scope="module", autouse=True)
+def chdir_to_test_file(request):
+ """
+ Changes to the same directory as the test file.
+ Also puts that directory at the start of sys.path,
+ so that imports of other files in the same directory are easy.
+
+ Tests have grown to expect this.
+
+ NOTE: This happens when the test is *run*, not during collection.
+ So test modules must not rely on it at module level.
+ """
+ old = os.getcwd()
+
+ os.chdir(os.path.dirname(request.module.__file__))
+ sys.path.insert(0, ".")
+ yield
+ if sys.path and sys.path[0] == ".":
+ sys.path.pop(0)
+ os.chdir(old)
+
+
+def pytest_collection_modifyitems(config, items):
+ # skip tests with @pytest.mark.require_driver(name) when the driver isn't available
+ skip = pytest.mark.skip("Driver not present")
+ import gdaltest
+
+ drivers_checked = {}
+ for item in items:
+ for mark in item.iter_markers('require_driver'):
+ driver_name = mark.args[0]
+ if driver_name not in drivers_checked:
+ driver = gdal.GetDriverByName(driver_name)
+ drivers_checked[driver_name] = bool(driver)
+ if driver:
+ # Store the driver on gdaltest module so test functions can assume it's there.
+ setattr(gdaltest, '%s_drv' % driver_name.lower(), driver)
+ if not drivers_checked[driver_name]:
+ item.add_marker(skip)
diff --git a/autotest/gcore/__init__.py b/autotest/gcore/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/autotest/gcore/aaigrid_read.py b/autotest/gcore/aaigrid_read.py
index 01df8465a4e6..fe3adea4a01a 100755
--- a/autotest/gcore/aaigrid_read.py
+++ b/autotest/gcore/aaigrid_read.py
@@ -25,31 +25,24 @@
# Boston, MA 02111-1307, USA.
###############################################################################
-import sys
-
-sys.path.append('../pymod')
+import pytest
import gdaltest
###############################################################################
# When imported build a list of units based on the files available.
-gdaltest_list = []
-
init_list = [
- ('byte.tif.grd', 1, 4672, None)]
-
-for item in init_list:
- ut = gdaltest.GDALTest('AAIGrid', item[0], item[1], item[2])
- if ut is None:
- print('AAIGrid tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testOpen, item[0]))
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('aaigrid_read')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ ('byte.tif.grd', 4672),
+]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.require_driver('AAIGrid')
+def test_aaigrid_open(filename, checksum):
+ ut = gdaltest.GDALTest('AAIGrid', filename, 1, checksum)
+ ut.testOpen()
diff --git a/autotest/gcore/aaigrid_write.py b/autotest/gcore/aaigrid_write.py
index c9931850ddd8..5a3b784cb83b 100755
--- a/autotest/gcore/aaigrid_write.py
+++ b/autotest/gcore/aaigrid_write.py
@@ -26,35 +26,27 @@
# Boston, MA 02111-1307, USA.
###############################################################################
-import sys
-
-sys.path.append('../pymod')
+import pytest
import gdaltest
###############################################################################
# When imported build a list of units based on the files available.
-gdaltest_list = []
-
init_list = [
- ('byte.tif', 1, 4672, None),
- ('int16.tif', 1, 4672, None),
- ('uint16.tif', 1, 4672, None),
- ('float32.tif', 1, 4672, None),
- ('utmsmall.tif', 1, 50054, None)]
-
-for item in init_list:
- ut = gdaltest.GDALTest('AAIGrid', item[0], item[1], item[2])
- if ut is None:
- print('AAIGrid tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testCreateCopy, item[0]))
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('aaigrid_write')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ ('byte.tif', 4672),
+ ('int16.tif', 4672),
+ ('uint16.tif', 4672),
+ ('float32.tif', 4672),
+ ('utmsmall.tif', 50054)]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.require_driver('AAIGrid')
+def test_aaigrid_create(filename, checksum):
+ ut = gdaltest.GDALTest('AAIGrid', filename, 1, checksum)
+ ut.testCreateCopy()
diff --git a/autotest/gcore/asyncreader.py b/autotest/gcore/asyncreader.py
index 5abd0c7b3553..9c855b148102 100755
--- a/autotest/gcore/asyncreader.py
+++ b/autotest/gcore/asyncreader.py
@@ -28,27 +28,22 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
###############################################################################
# Test AsyncReader interface on the default (synchronous) implementation
-def asyncreader_1():
+def test_asyncreader_1():
ds = gdal.Open('data/rgbsmall.tif')
asyncreader = ds.BeginAsyncReader(0, 0, ds.RasterXSize, ds.RasterYSize)
buf = asyncreader.GetBuffer()
result = asyncreader.GetNextUpdatedRegion(0)
- if result != [gdal.GARIO_COMPLETE, 0, 0, ds.RasterXSize, ds.RasterYSize]:
- gdaltest.post_reason('wrong return values for GetNextUpdatedRegion()')
- print(result)
- return 'fail'
+ assert result == [gdal.GARIO_COMPLETE, 0, 0, ds.RasterXSize, ds.RasterYSize], \
+ 'wrong return values for GetNextUpdatedRegion()'
ds.EndAsyncReader(asyncreader)
asyncreader = None
@@ -63,22 +58,9 @@ def asyncreader_1():
gdal.Unlink('/vsimem/asyncresult.tif')
for i, csum in enumerate(cs):
- if csum != expected_cs[i]:
- gdaltest.post_reason('did not get expected checksum for band %d' % (i + 1))
- print(csum)
- print(expected_cs[i])
- return 'fail'
+ assert csum == expected_cs[i], ('did not get expected checksum for band %d' % (i + 1))
- return 'success'
+
-gdaltest_list = [asyncreader_1]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('asyncreader')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/basic_test.py b/autotest/gcore/basic_test.py
index 46ffdb2e0242..bf7567069970 100755
--- a/autotest/gcore/basic_test.py
+++ b/autotest/gcore/basic_test.py
@@ -30,12 +30,13 @@
###############################################################################
import os
+import subprocess
import sys
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal
+import pytest
# Nothing exciting here. Just trying to open non existing files,
# or empty names, or files that are not valid datasets...
@@ -48,20 +49,19 @@ def matches_non_existing_error_msg(msg):
return m1 or m2 or m3
-def basic_test_1():
+def test_basic_test_1():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('non_existing_ds', gdal.GA_ReadOnly)
gdal.PopErrorHandler()
if ds is None and matches_non_existing_error_msg(gdal.GetLastErrorMsg()):
- return 'success'
- gdaltest.post_reason('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
- return 'fail'
+ return
+ pytest.fail('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
-def basic_test_strace_non_existing_file():
+def test_basic_test_strace_non_existing_file():
if not sys.platform.startswith('linux'):
- return 'skip'
+ pytest.skip()
python_exe = sys.executable
cmd = "strace -f %s -c \"from osgeo import gdal; " % python_exe + (
@@ -69,104 +69,90 @@ def basic_test_strace_non_existing_file():
" \" ")
try:
(_, err) = gdaltest.runexternal_out_and_err(cmd)
- except:
+ except Exception:
# strace not available
- return 'skip'
+ pytest.skip()
interesting_lines = []
for line in err.split('\n'):
if line.find('non_existing_ds') >= 0:
interesting_lines += [ line ]
# Only 3 calls on the file are legit: open(), stat() and readlink()
- if len(interesting_lines) > 3:
- gdaltest.post_reason('too many system calls accessing file')
- print(interesting_lines)
- return 'fail'
+ assert len(interesting_lines) <= 3, 'too many system calls accessing file'
- return 'success'
-def basic_test_2():
+def test_basic_test_2():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('non_existing_ds', gdal.GA_Update)
gdal.PopErrorHandler()
if ds is None and matches_non_existing_error_msg(gdal.GetLastErrorMsg()):
- return 'success'
- gdaltest.post_reason('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
- return 'fail'
+ return
+ pytest.fail('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
-def basic_test_3():
+def test_basic_test_3():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('', gdal.GA_ReadOnly)
gdal.PopErrorHandler()
if ds is None and matches_non_existing_error_msg(gdal.GetLastErrorMsg()):
- return 'success'
- gdaltest.post_reason('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
- return 'fail'
+ return
+ pytest.fail('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
-def basic_test_4():
+def test_basic_test_4():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('', gdal.GA_Update)
gdal.PopErrorHandler()
if ds is None and matches_non_existing_error_msg(gdal.GetLastErrorMsg()):
- return 'success'
- gdaltest.post_reason('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
- return 'fail'
+ return
+ pytest.fail('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
-def basic_test_5():
+def test_basic_test_5():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('data/doctype.xml', gdal.GA_ReadOnly)
gdal.PopErrorHandler()
last_error = gdal.GetLastErrorMsg()
expected = '`data/doctype.xml\' not recognized as a supported file format'
if ds is None and expected in last_error:
- return 'success'
- return 'fail'
+ return
+ pytest.fail()
###############################################################################
# Issue several AllRegister() to check that GDAL drivers are good citizens
-def basic_test_6():
+def test_basic_test_6():
gdal.AllRegister()
gdal.AllRegister()
gdal.AllRegister()
- return 'success'
-
###############################################################################
# Test fix for #3077 (check that errors are cleared when using UseExceptions())
def basic_test_7_internal():
- try:
+
+ with pytest.raises(Exception):
gdal.Open('non_existing_ds', gdal.GA_ReadOnly)
- gdaltest.post_reason('opening should have thrown an exception')
- return 'fail'
- except:
- # Special case: we should still be able to get the error message
- # until we call a new GDAL function
- if not matches_non_existing_error_msg(gdal.GetLastErrorMsg()):
- gdaltest.post_reason('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
- return 'fail'
- if gdal.GetLastErrorType() == 0:
- gdaltest.post_reason('did not get expected error type')
- return 'fail'
+ # Special case: we should still be able to get the error message
+ # until we call a new GDAL function
+ assert matches_non_existing_error_msg(gdal.GetLastErrorMsg()), ('did not get expected error message, got %s' % gdal.GetLastErrorMsg())
+
+ # Special case: we should still be able to get the error message
+ # until we call a new GDAL function
+ assert matches_non_existing_error_msg(gdal.GetLastErrorMsg()), 'did not get expected error message, got %s' % gdal.GetLastErrorMsg()
- # Should issue an implicit CPLErrorReset()
- gdal.GetCacheMax()
+ assert gdal.GetLastErrorType() != 0, 'did not get expected error type'
- if gdal.GetLastErrorType() != 0:
- gdaltest.post_reason('got unexpected error type')
- return 'fail'
+ # Should issue an implicit CPLErrorReset()
+ gdal.GetCacheMax()
- return 'success'
+ assert gdal.GetLastErrorType() == 0, 'got unexpected error type'
-def basic_test_7():
+def test_basic_test_7():
old_use_exceptions_status = gdal.GetUseExceptions()
gdal.UseExceptions()
ret = basic_test_7_internal()
@@ -178,35 +164,35 @@ def basic_test_7():
# Test gdal.VersionInfo('RELEASE_DATE') and gdal.VersionInfo('LICENSE')
-def basic_test_8():
+def test_basic_test_8():
ret = gdal.VersionInfo('RELEASE_DATE')
- if len(ret) != 8:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
+ assert len(ret) == 8
python_exe = sys.executable
if sys.platform == 'win32':
python_exe = python_exe.replace('\\', '/')
- ret = gdaltest.runexternal(python_exe + ' basic_test.py LICENSE 0')
- if ret.find('GDAL/OGR is released under the MIT/X license') != 0 and ret.find('GDAL/OGR Licensing') < 0:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
-
- f = open('tmp/LICENSE.TXT', 'wt')
- f.write('fake_license')
- f.close()
- ret = gdaltest.runexternal(python_exe + ' basic_test.py LICENSE 1')
+ license_text = gdal.VersionInfo('LICENSE')
+ assert (
+ license_text.startswith('GDAL/OGR is released under the MIT/X license')
+ or 'GDAL/OGR Licensing' in license_text
+ )
+
+ # Use a subprocess to avoid the cached license text
+ env = os.environ.copy()
+ env['GDAL_DATA'] = 'tmp'
+ with open('tmp/LICENSE.TXT', 'wt') as f:
+ f.write('fake_license')
+ license_text = subprocess.check_output(
+ [sys.executable, 'basic_test_subprocess.py'],
+ env=env
+ ).decode('utf-8')
os.unlink('tmp/LICENSE.TXT')
- if ret.find('fake_license') != 0 and ret.find('GDAL/OGR Licensing') < 0:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
+ assert (
+ license_text.startswith(u'fake_license')
+ )
- return 'success'
###############################################################################
# Test gdal.PushErrorHandler() with a Python error handler
@@ -218,7 +204,7 @@ def my_python_error_handler(eErrClass, err_no, msg):
gdaltest.msg = msg
-def basic_test_9():
+def test_basic_test_9():
gdaltest.eErrClass = 0
gdaltest.err_no = 0
@@ -227,19 +213,11 @@ def basic_test_9():
gdal.Error(1, 2, 'test')
gdal.PopErrorHandler()
- if gdaltest.eErrClass != 1:
- gdaltest.post_reason('fail')
- return 'fail'
-
- if gdaltest.err_no != 2:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdaltest.eErrClass == 1
- if gdaltest.msg != 'test':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdaltest.err_no == 2
- return 'success'
+ assert gdaltest.msg == 'test'
###############################################################################
# Test gdal.PushErrorHandler() with a Python error handler as a method (#5186)
@@ -257,7 +235,7 @@ def handler(self, eErrClass, err_no, msg):
self.msg = msg
-def basic_test_10():
+def test_basic_test_10():
# Check that reference counting works OK
gdal.PushErrorHandler(my_python_error_handler_class().handler)
@@ -269,126 +247,78 @@ def basic_test_10():
gdal.Error(1, 2, 'test')
gdal.PopErrorHandler()
- if error_handler.eErrClass != 1:
- gdaltest.post_reason('fail')
- return 'fail'
-
- if error_handler.err_no != 2:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert error_handler.eErrClass == 1
- if error_handler.msg != 'test':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert error_handler.err_no == 2
- return 'success'
+ assert error_handler.msg == 'test'
###############################################################################
# Test gdal.OpenEx()
-def basic_test_11():
+def test_basic_test_11():
ds = gdal.OpenEx('data/byte.tif')
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('data/byte.tif', gdal.OF_RASTER)
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('data/byte.tif', gdal.OF_VECTOR)
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
ds = gdal.OpenEx('data/byte.tif', gdal.OF_RASTER | gdal.OF_VECTOR)
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('data/byte.tif', gdal.OF_ALL)
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('data/byte.tif', gdal.OF_UPDATE)
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('data/byte.tif', gdal.OF_RASTER | gdal.OF_VECTOR | gdal.OF_UPDATE | gdal.OF_VERBOSE_ERROR)
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('data/byte.tif', allowed_drivers=[])
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('data/byte.tif', allowed_drivers=['GTiff'])
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('data/byte.tif', allowed_drivers=['PNG'])
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
with gdaltest.error_handler():
ds = gdal.OpenEx('data/byte.tif', open_options=['FOO'])
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ar_ds = [gdal.OpenEx('data/byte.tif', gdal.OF_SHARED) for _ in range(1024)]
- if ar_ds[1023] is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ar_ds[1023] is not None
ar_ds = None
ds = gdal.OpenEx('../ogr/data/poly.shp', gdal.OF_RASTER)
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
ds = gdal.OpenEx('../ogr/data/poly.shp', gdal.OF_VECTOR)
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetLayerCount() != 1:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetLayer(0) is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
+ assert ds.GetLayerCount() == 1
+ assert ds.GetLayer(0) is not None
ds.GetLayer(0).GetMetadata()
ds = gdal.OpenEx('../ogr/data/poly.shp', allowed_drivers=['ESRI Shapefile'])
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('../ogr/data/poly.shp', gdal.OF_RASTER | gdal.OF_VECTOR)
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
ds = gdal.OpenEx('non existing')
- if ds is not None or gdal.GetLastErrorMsg() != '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None and gdal.GetLastErrorMsg() == ''
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.OpenEx('non existing', gdal.OF_VERBOSE_ERROR)
gdal.PopErrorHandler()
- if ds is not None or gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None and gdal.GetLastErrorMsg() != ''
old_use_exceptions_status = gdal.GetUseExceptions()
gdal.UseExceptions()
@@ -399,75 +329,43 @@ def basic_test_11():
got_exception = True
if old_use_exceptions_status == 0:
gdal.DontUseExceptions()
- if not got_exception:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert got_exception
###############################################################################
# Test GDAL layer API
-def basic_test_12():
+def test_basic_test_12():
ds = gdal.GetDriverByName('MEMORY').Create('bar', 0, 0, 0)
- if ds.GetDescription() != 'bar':
- gdaltest.post_reason('failure')
- print(ds.GetDescription())
- return 'fail'
+ assert ds.GetDescription() == 'bar'
lyr = ds.CreateLayer("foo")
- if lyr is None:
- gdaltest.post_reason('failure')
- return 'fail'
- if lyr.GetDescription() != 'foo':
- gdaltest.post_reason('failure')
- print(lyr.GetDescription())
- return 'fail'
+ assert lyr is not None
+ assert lyr.GetDescription() == 'foo'
from osgeo import ogr
- if lyr.TestCapability(ogr.OLCCreateField) != 1:
- gdaltest.post_reason('failure')
- return 'fail'
- if ds.GetLayerCount() != 1:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert lyr.TestCapability(ogr.OLCCreateField) == 1
+ assert ds.GetLayerCount() == 1
lyr = ds.GetLayerByName("foo")
- if lyr is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert lyr is not None
lyr = ds.GetLayerByIndex(0)
- if lyr is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert lyr is not None
lyr = ds.GetLayer(0)
- if lyr is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert lyr is not None
sql_lyr = ds.ExecuteSQL('SELECT * FROM foo')
- if sql_lyr is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert sql_lyr is not None
ds.ReleaseResultSet(sql_lyr)
new_lyr = ds.CopyLayer(lyr, 'bar')
- if new_lyr is None:
- gdaltest.post_reason('failure')
- return 'fail'
- if ds.DeleteLayer(0) != 0:
- gdaltest.post_reason('failure')
- return 'fail'
- if ds.DeleteLayer('bar') != 0:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert new_lyr is not None
+ assert ds.DeleteLayer(0) == 0
+ assert ds.DeleteLayer('bar') == 0
ds.SetStyleTable(ds.GetStyleTable())
ds = None
- return 'success'
-
###############################################################################
# Test correct sorting of StringList / metadata (#5540, #5557)
-def basic_test_13():
+def test_basic_test_13():
ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
for i in range(3):
@@ -484,90 +382,56 @@ def basic_test_13():
ds.SetMetadataItem("ScaleBounds", "True")
ds.SetMetadataItem("ScaleBounds.MaxScale", "2000000")
- if ds.GetMetadataItem('scalebounds') != 'True':
- gdaltest.post_reason('failure')
- return 'fail'
- if ds.GetMetadataItem('ScaleBounds') != 'True':
- gdaltest.post_reason('failure')
- return 'fail'
- if ds.GetMetadataItem('SCALEBOUNDS') != 'True':
- gdaltest.post_reason('failure')
- return 'fail'
- if ds.GetMetadataItem('ScaleBounds.MinScale') != '0':
- gdaltest.post_reason('failure')
- return 'fail'
- if ds.GetMetadataItem('ScaleBounds.MaxScale') != '2000000':
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetMetadataItem('scalebounds') == 'True'
+ assert ds.GetMetadataItem('ScaleBounds') == 'True'
+ assert ds.GetMetadataItem('SCALEBOUNDS') == 'True'
+ assert ds.GetMetadataItem('ScaleBounds.MinScale') == '0'
+ assert ds.GetMetadataItem('ScaleBounds.MaxScale') == '2000000'
ds = None
ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
for i in range(200):
ds.SetMetadataItem("FILENAME_%d" % i, "%d" % i)
for i in range(200):
- if ds.GetMetadataItem("FILENAME_%d" % i) != '%d' % i:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetMetadataItem("FILENAME_%d" % i) == '%d' % i
- return 'success'
###############################################################################
# Test SetMetadata()
-def basic_test_14():
+def test_basic_test_14():
ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
ds.SetMetadata('foo')
- if ds.GetMetadata_List() != ['foo']:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetMetadata_List() == ['foo']
- try:
+ with pytest.raises(Exception):
ds.SetMetadata(5)
- gdaltest.post_reason('failure')
- return 'fail'
- except:
- pass
+
ds.SetMetadata(['foo=bar'])
- if ds.GetMetadata_List() != ['foo=bar']:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetMetadata_List() == ['foo=bar']
- try:
+ with pytest.raises(Exception):
ds.SetMetadata([5])
- gdaltest.post_reason('failure')
- return 'fail'
- except:
- pass
+
ds.SetMetadata({'foo': 'baz'})
- if ds.GetMetadata_List() != ['foo=baz']:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetMetadata_List() == ['foo=baz']
- try:
+ with pytest.raises(Exception):
ds.SetMetadata({'foo': 5})
- gdaltest.post_reason('failure')
- return 'fail'
- except:
- pass
+
- try:
+ with pytest.raises(Exception):
ds.SetMetadata({5: 'baz'})
- gdaltest.post_reason('failure')
- return 'fail'
- except:
- pass
+
- try:
+ with pytest.raises(Exception):
ds.SetMetadata({5: 6})
- gdaltest.post_reason('failure')
- return 'fail'
- except:
- pass
+
if sys.version_info >= (3, 0, 0):
val = '\u00e9ven'
@@ -575,31 +439,20 @@ def basic_test_14():
exec("val = u'\\u00e9ven'")
ds.SetMetadata({'bar': val})
- if ds.GetMetadata()['bar'] != val:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetMetadata()['bar'] == val
ds.SetMetadata({val: 'baz'})
- if ds.GetMetadata()[val] != 'baz':
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetMetadata()[val] == 'baz'
- try:
+ with pytest.raises(Exception):
ds.SetMetadata({val: 5})
- gdaltest.post_reason('failure')
- return 'fail'
- except:
- pass
+
- try:
+ with pytest.raises(Exception):
ds.SetMetadata({5: val})
- gdaltest.post_reason('failure')
- return 'fail'
- except:
- pass
-
- return 'success'
+
+
###############################################################################
# Test errors with progress callback
@@ -618,65 +471,48 @@ def basic_test_15_cbk_bad_ret(a, b, c):
return 'ok'
-def basic_test_15():
+def test_basic_test_15():
+ mem_driver = gdal.GetDriverByName('MEM')
- try:
+ with pytest.raises(Exception):
with gdaltest.error_handler():
gdal.GetDriverByName('MEM').CreateCopy('', gdal.GetDriverByName('MEM').Create('', 1, 1), callback='foo')
- gdaltest.post_reason('fail')
- return 'fail'
- except:
- pass
- with gdaltest.error_handler():
- ds = gdal.GetDriverByName('MEM').CreateCopy('', gdal.GetDriverByName('MEM').Create('', 1, 1), callback=basic_test_15_cbk_no_argument)
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
with gdaltest.error_handler():
- ds = gdal.GetDriverByName('MEM').CreateCopy('', gdal.GetDriverByName('MEM').Create('', 1, 1), callback=basic_test_15_cbk_no_ret)
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ ds = mem_driver.CreateCopy('', mem_driver.Create('', 1, 1), callback=basic_test_15_cbk_no_argument)
+ assert ds is None
with gdaltest.error_handler():
- ds = gdal.GetDriverByName('MEM').CreateCopy('', gdal.GetDriverByName('MEM').Create('', 1, 1), callback=basic_test_15_cbk_bad_ret)
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ ds = mem_driver.CreateCopy('', mem_driver.Create('', 1, 1), callback=basic_test_15_cbk_no_ret)
+ assert ds is not None
- return 'success'
+ with gdaltest.error_handler():
+ ds = mem_driver.CreateCopy('', mem_driver.Create('', 1, 1), callback=basic_test_15_cbk_bad_ret)
+ assert ds is None
###############################################################################
# Test unrecognized and recognized open options prefixed by @
-def basic_test_16():
+def test_basic_test_16():
gdal.ErrorReset()
gdal.OpenEx('data/byte.tif', open_options=['@UNRECOGNIZED=FOO'])
- if gdal.GetLastErrorMsg() != '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() == ''
gdal.ErrorReset()
gdal.Translate('/vsimem/temp.tif', 'data/byte.tif', options='-co BLOCKYSIZE=10')
with gdaltest.error_handler():
gdal.OpenEx('/vsimem/temp.tif', gdal.OF_UPDATE, open_options=['@NUM_THREADS=INVALID'])
gdal.Unlink('/vsimem/temp.tif')
- if gdal.GetLastErrorMsg() != 'Invalid value for NUM_THREADS: INVALID':
- gdaltest.post_reason('fail')
- print(gdal.GetLastErrorMsg())
- return 'fail'
-
- return 'success'
+ assert gdal.GetLastErrorMsg() == 'Invalid value for NUM_THREADS: INVALID'
###############################################################################
# Test mix of gdal/ogr.UseExceptions()/DontUseExceptions()
-def basic_test_17():
+def test_basic_test_17():
from osgeo import ogr
@@ -689,12 +525,8 @@ def basic_test_17():
pass
gdal.DontUseExceptions()
ogr.DontUseExceptions()
- if gdal.GetUseExceptions():
- gdaltest.post_reason('fail')
- return 'fail'
- if ogr.GetUseExceptions():
- gdaltest.post_reason('fail')
- return 'fail'
+ assert not gdal.GetUseExceptions()
+ assert not ogr.GetUseExceptions()
for _ in range(2):
ogr.UseExceptions()
@@ -711,54 +543,6 @@ def basic_test_17():
except:
gdal.DontUseExceptions()
ogr.DontUseExceptions()
- if flag:
- gdaltest.post_reason('expected failure')
- return 'fail'
- if gdal.GetUseExceptions():
- gdaltest.post_reason('fail')
- return 'fail'
- if ogr.GetUseExceptions():
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = [basic_test_1,
- basic_test_strace_non_existing_file,
- basic_test_2,
- basic_test_3,
- basic_test_4,
- basic_test_5,
- basic_test_6,
- basic_test_7,
- basic_test_8,
- basic_test_9,
- basic_test_10,
- basic_test_11,
- basic_test_12,
- basic_test_13,
- basic_test_14,
- basic_test_15,
- basic_test_16,
- basic_test_17]
-
-
-if __name__ == '__main__':
-
- if len(sys.argv) == 3 and sys.argv[1] == "LICENSE":
- if sys.argv[2] == '0':
- gdal.SetConfigOption('GDAL_DATA', '/foo')
- else:
- gdal.SetConfigOption('GDAL_DATA', 'tmp')
- gdal.VersionInfo('LICENSE')
- print(gdal.VersionInfo('LICENSE'))
- import testnonboundtoswig
- testnonboundtoswig.GDALDestroyDriverManager()
- sys.exit(0)
-
- gdaltest.setup_run('basic_test')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ assert not flag, 'expected failure'
+ assert not gdal.GetUseExceptions()
+ assert not ogr.GetUseExceptions()
diff --git a/autotest/gcore/basic_test_subprocess.py b/autotest/gcore/basic_test_subprocess.py
new file mode 100755
index 000000000000..0cd8457c542a
--- /dev/null
+++ b/autotest/gcore/basic_test_subprocess.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+###############################################################################
+# $Id$
+#
+# Project: GDAL/OGR Test Suite
+# Purpose: Test basic GDAL open
+# Author: Even Rouault
+#
+###############################################################################
+# Copyright (c) 2008-2013, Even Rouault
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+# DEALINGS IN THE SOFTWARE.
+###############################################################################
+
+from osgeo import gdal
+
+
+if __name__ == '__main__':
+ # test_basic_test_8
+ print(gdal.VersionInfo('LICENSE'))
diff --git a/autotest/gcore/bmp_read.py b/autotest/gcore/bmp_read.py
index b9a0c640c65f..84b656523ec8 100755
--- a/autotest/gcore/bmp_read.py
+++ b/autotest/gcore/bmp_read.py
@@ -26,38 +26,44 @@
# Boston, MA 02111-1307, USA.
###############################################################################
-import sys
-sys.path.append('../pymod')
+import pytest
import gdaltest
-###############################################################################
-# When imported build a list of units based on the files available.
-
-gdaltest_list = []
init_list = [
- ('1bit.bmp', 1, 200, None),
- ('4bit_pal.bmp', 1, 2587, None),
- ('8bit_pal.bmp', 1, 4672, None),
- ('byte_rle8.bmp', 1, 4672, None)]
+ ('1bit.bmp', 200),
+ ('4bit_pal.bmp', 2587),
+ ('8bit_pal.bmp', 4672),
+ ('byte_rle8.bmp', 4672)]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.require_driver('BMP')
+def test_bmp_open(filename, checksum):
+ ut = gdaltest.GDALTest('BMP', filename, 1, checksum)
+ ut.testOpen()
-def bmp_online_1():
+def test_bmp_online_1():
if not gdaltest.download_file('http://download.osgeo.org/gdal/data/bmp/8bit_pal_rle.bmp', '8bit_pal_rle.bmp'):
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('BMP', 'tmp/cache/8bit_pal_rle.bmp', 1, 17270, filename_absolute=1)
return tst.testOpen()
-def bmp_online_2():
+def test_bmp_online_2():
if not gdaltest.download_file('http://download.osgeo.org/gdal/data/bmp/24bit.bmp', '24bit.bmp'):
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('BMP', 'tmp/cache/24bit.bmp', 1, 7158, filename_absolute=1)
if tst == 'success':
@@ -66,20 +72,4 @@ def bmp_online_2():
return tst.testOpen()
-for item in init_list:
- ut = gdaltest.GDALTest('BMP', item[0], item[1], item[2])
- if ut is None:
- print('BMP tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testOpen, item[0]))
-
-gdaltest_list.append(bmp_online_1)
-gdaltest_list.append(bmp_online_2)
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('bmp_read')
-
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/bmp_write.py b/autotest/gcore/bmp_write.py
index c54230384835..b996dce49cc7 100755
--- a/autotest/gcore/bmp_write.py
+++ b/autotest/gcore/bmp_write.py
@@ -27,9 +27,8 @@
# Boston, MA 02111-1307, USA.
###############################################################################
-import sys
-sys.path.append('../pymod')
+import pytest
import gdaltest
@@ -37,7 +36,7 @@
# Test creating an in memory copy.
-def bmp_vsimem():
+def test_bmp_vsimem():
tst = gdaltest.GDALTest('BMP', 'byte.tif', 1, 4672)
@@ -47,27 +46,28 @@ def bmp_vsimem():
###############################################################################
# When imported build a list of units based on the files available.
-gdaltest_list = [bmp_vsimem]
-init_list = [
- ('byte.tif', 1, 4672, None),
- ('utmsmall.tif', 1, 50054, None),
- ('8bit_pal.bmp', 1, 4672, None), ]
-
-for item in init_list:
- ut = gdaltest.GDALTest('BMP', item[0], item[1], item[2])
- if ut is None:
- print('BMP tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testCreateCopy, item[0]))
- gdaltest_list.append((ut.testCreate, item[0]))
-
-gdaltest_list.append((gdaltest.clean_tmp, 'bmp_cleanup'))
-if __name__ == '__main__':
-
- gdaltest.setup_run('bmp_write')
+init_list = [
+ ('byte.tif', 4672),
+ ('utmsmall.tif', 50054),
+ ('8bit_pal.bmp', 4672), ]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.parametrize(
+ 'testfunction', [
+ 'testCreateCopy',
+ 'testCreate',
+ ]
+)
+@pytest.mark.require_driver('BMP')
+def test_bmp_create(filename, checksum, testfunction):
+ ut = gdaltest.GDALTest('BMP', filename, 1, checksum)
+ getattr(ut, testfunction)()
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/colortable.py b/autotest/gcore/colortable.py
index 1bbbb8dc06b9..a0d7c9438b81 100755
--- a/autotest/gcore/colortable.py
+++ b/autotest/gcore/colortable.py
@@ -30,18 +30,17 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Create a color table.
-def colortable_1():
+def test_colortable_1():
gdaltest.test_ct_data = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255, 0)]
@@ -49,13 +48,12 @@ def colortable_1():
for i in range(len(gdaltest.test_ct_data)):
gdaltest.test_ct.SetColorEntry(i, gdaltest.test_ct_data[i])
- return 'success'
-
+
###############################################################################
# verify contents.
-def colortable_2():
+def test_colortable_2():
for i in range(len(gdaltest.test_ct_data)):
g_data = gdaltest.test_ct.GetColorEntry(i)
@@ -67,53 +65,33 @@ def colortable_2():
else:
o_v = o_data[j]
- if g_data[j] != o_v:
- gdaltest.post_reason('color table mismatch')
- return 'fail'
-
- return 'success'
+ assert g_data[j] == o_v, 'color table mismatch'
+
###############################################################################
# Test CreateColorRamp()
-def colortable_3():
+def test_colortable_3():
ct = gdal.ColorTable()
try:
ct.CreateColorRamp
except AttributeError:
- return 'skip'
+ pytest.skip()
ct.CreateColorRamp(0, (255, 0, 0), 255, (0, 0, 255))
- if ct.GetColorEntry(0) != (255, 0, 0, 255):
- return 'fail'
-
- if ct.GetColorEntry(255) != (0, 0, 255, 255):
- return 'fail'
+ assert ct.GetColorEntry(0) == (255, 0, 0, 255)
- return 'success'
+ assert ct.GetColorEntry(255) == (0, 0, 255, 255)
###############################################################################
# Cleanup.
-def colortable_cleanup():
+def test_colortable_cleanup():
gdaltest.test_ct = None
- return 'success'
-
-
-gdaltest_list = [
- colortable_1,
- colortable_2,
- colortable_3,
- colortable_cleanup]
-
-if __name__ == '__main__':
- gdaltest.setup_run('colortable')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/envi_read.py b/autotest/gcore/envi_read.py
index c365e6ef5121..b49bd4cc51d4 100755
--- a/autotest/gcore/envi_read.py
+++ b/autotest/gcore/envi_read.py
@@ -27,9 +27,8 @@
# Boston, MA 02111-1307, USA.
###############################################################################
-import sys
-sys.path.append('../pymod')
+import pytest
from osgeo import gdal
import gdaltest
@@ -38,7 +37,7 @@
# Test GDAL_READDIR_LIMIT_ON_OPEN
-def envi_1():
+def test_envi_1():
gdal.SetConfigOption('GDAL_READDIR_LIMIT_ON_OPEN', '1')
@@ -47,43 +46,34 @@ def envi_1():
gdal.SetConfigOption('GDAL_READDIR_LIMIT_ON_OPEN', None)
- if len(filelist) != 2:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
-
- return 'success'
+ assert len(filelist) == 2, 'did not get expected file list.'
###############################################################################
# When imported build a list of units based on the files available.
-gdaltest_list = []
-
init_list = [
- ('byte.raw', 1, 4672, None),
- ('int16.raw', 1, 4672, None),
- ('uint16.raw', 1, 4672, None),
- ('int32.raw', 1, 4672, None),
- ('uint32.raw', 1, 4672, None),
- ('float32.raw', 1, 4672, None),
- ('float64.raw', 1, 4672, None)]
-# ('cfloat32.raw', 1, 5028, None),
-# ('cfloat64.raw', 1, 5028, None)]
-
-
-for item in init_list:
- ut = gdaltest.GDALTest('ENVI', item[0], item[1], item[2])
- if ut is None:
- print('ENVI tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testOpen, item[0]))
-
-gdaltest_list.append(envi_1)
-
-if __name__ == '__main__':
+ ('byte.raw', 4672),
+ ('int16.raw', 4672),
+ ('uint16.raw', 4672),
+ ('int32.raw', 4672),
+ ('uint32.raw', 4672),
+ ('float32.raw', 4672),
+ ('float64.raw', 4672),
+ # ('cfloat32.raw', 5028),
+ # ('cfloat64.raw', 5028),
+]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.require_driver('ENVI')
+def test_envi_open(filename, checksum):
+ ut = gdaltest.GDALTest('ENVI', filename, 1, checksum)
+ ut.testOpen()
- gdaltest.setup_run('envi_read')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/gcps2geotransform.py b/autotest/gcore/gcps2geotransform.py
index a5123fa70684..2cb6e25e92c5 100755
--- a/autotest/gcore/gcps2geotransform.py
+++ b/autotest/gcore/gcps2geotransform.py
@@ -29,10 +29,8 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
from osgeo import gdal
-sys.path.append('../pymod')
import gdaltest
@@ -55,24 +53,21 @@ def _list2gcps(src_list):
###############################################################################
# Test simple exact case of turning GCPs into a GeoTransform.
-def gcps2gt_1():
+def test_gcps2gt_1():
gt = gdal.GCPsToGeoTransform(_list2gcps([
(0.0, 0.0, 400000, 370000),
(100.0, 0.0, 410000, 370000),
(100.0, 200.0, 410000, 368000)
]))
- if not gdaltest.geotransform_equals(
- gt, (400000.0, 100.0, 0.0, 370000.0, 0.0, -10.0), 0.000001):
- return 'fail'
-
- return 'success'
+ assert gdaltest.geotransform_equals(
+ gt, (400000.0, 100.0, 0.0, 370000.0, 0.0, -10.0), 0.000001)
###############################################################################
# Similar but non-exact.
-def gcps2gt_2():
+def test_gcps2gt_2():
gt = gdal.GCPsToGeoTransform(_list2gcps([
(0.0, 0.0, 400000, 370000),
@@ -80,17 +75,14 @@ def gcps2gt_2():
(100.0, 200.0, 410000, 368000),
(0.0, 200.0, 400000, 368000.01)
]))
- if not gdaltest.geotransform_equals(
- gt, (400000.0, 100.0, 0.0, 370000.0025, -5e-05, -9.999975), 0.000001):
- return 'fail'
-
- return 'success'
+ assert gdaltest.geotransform_equals(
+ gt, (400000.0, 100.0, 0.0, 370000.0025, -5e-05, -9.999975), 0.000001)
###############################################################################
# bApproxOK false, and no good solution.
-def gcps2gt_3():
+def test_gcps2gt_3():
approx_ok = 0
gt = gdal.GCPsToGeoTransform(_list2gcps([
@@ -99,48 +91,37 @@ def gcps2gt_3():
(100.0, 200.0, 410000, 368000),
(0.0, 200.0, 400000, 360000)
]), approx_ok)
- if gt is not None:
- gdaltest.post_reason('Expected failure when no good solution.')
- return 'fail'
-
- return 'success'
+ assert gt is None, 'Expected failure when no good solution.'
###############################################################################
# Single point - Should return None.
-def gcps2gt_4():
+def test_gcps2gt_4():
gt = gdal.GCPsToGeoTransform(_list2gcps([
(0.0, 0.0, 400000, 370000),
]))
- if gt is not None:
- gdaltest.post_reason('Expected failure for single GCP.')
- return 'fail'
-
- return 'success'
+ assert gt is None, 'Expected failure for single GCP.'
###############################################################################
# Two points - simple offset and scale, no rotation.
-def gcps2gt_5():
+def test_gcps2gt_5():
gt = gdal.GCPsToGeoTransform(_list2gcps([
(0.0, 0.0, 400000, 370000),
(100.0, 200.0, 410000, 368000),
]))
- if not gdaltest.geotransform_equals(
- gt, (400000.0, 100.0, 0.0, 370000.0, 0.0, -10.0), 0.000001):
- return 'fail'
-
- return 'success'
+ assert gdaltest.geotransform_equals(
+ gt, (400000.0, 100.0, 0.0, 370000.0, 0.0, -10.0), 0.000001)
###############################################################################
# Special case for four points in a particular order. Exact result.
-def gcps2gt_6():
+def test_gcps2gt_6():
gt = gdal.GCPsToGeoTransform(_list2gcps([
(400000, 370000, 400000, 370000),
@@ -148,17 +129,14 @@ def gcps2gt_6():
(410000, 368000, 410000, 368000),
(400000, 368000, 400000, 368000),
]))
- if not gdaltest.geotransform_equals(
- gt, (0.0, 1.0, 0.0, 0.0, 0.0, 1.0), 0.000001):
- return 'fail'
-
- return 'success'
+ assert gdaltest.geotransform_equals(
+ gt, (0.0, 1.0, 0.0, 0.0, 0.0, 1.0), 0.000001)
###############################################################################
# Try a case that is hard to do without normalization.
-def gcps2gt_7():
+def test_gcps2gt_7():
gt = gdal.GCPsToGeoTransform(_list2gcps([
(400000, 370000, 400000, 370000),
@@ -166,17 +144,14 @@ def gcps2gt_7():
(410000, 370000, 410000, 370000),
(400000, 368000, 400000, 368000),
]))
- if not gdaltest.geotransform_equals(
- gt, (0.0, 1.0, 0.0, 0.0, 0.0, 1.0), 0.000001):
- return 'fail'
-
- return 'success'
+ assert gdaltest.geotransform_equals(
+ gt, (0.0, 1.0, 0.0, 0.0, 0.0, 1.0), 0.000001)
###############################################################################
# A fairly messy real world case without a easy to predict result.
-def gcps2gt_8():
+def test_gcps2gt_8():
gt = gdal.GCPsToGeoTransform(_list2gcps([
(0.01, 0.04, -87.05528672907, 39.22759504228),
@@ -188,27 +163,7 @@ def gcps2gt_8():
]))
gt_expected = (-87.056612873288, -2.232795668658e-05, 3.178617809303e-05,
39.227856615716, 2.6091510188921e-05, 1.596921026218e-05)
- if not gdaltest.geotransform_equals(gt, gt_expected, 0.00001):
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = [
- gcps2gt_1,
- gcps2gt_2,
- gcps2gt_3,
- gcps2gt_4,
- gcps2gt_5,
- gcps2gt_6,
- gcps2gt_7,
- gcps2gt_8,
-]
-
-if __name__ == '__main__':
+ assert gdaltest.geotransform_equals(gt, gt_expected, 0.00001)
- gdaltest.setup_run('gcps2geotransform')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/gdal_api_proxy.py b/autotest/gcore/gdal_api_proxy.py
index 6aa16ca2e0f7..a0708896dffe 100755
--- a/autotest/gcore/gdal_api_proxy.py
+++ b/autotest/gcore/gdal_api_proxy.py
@@ -34,99 +34,83 @@
import time
from osgeo import gdal
-sys.path.append('../pymod')
-import gdaltest
+import pytest
###############################################################################
# Test forked gdalserver
-def gdal_api_proxy_1():
-
- import test_py_scripts
+@pytest.fixture
+def gdalserver_path():
import test_cli_utilities
- gdaltest.gdalserver_path = test_cli_utilities.get_cli_utility_path('gdalserver')
- if gdaltest.gdalserver_path is None:
- gdaltest.gdalserver_path = 'gdalserver'
-
- ret = test_py_scripts.run_py_script_as_external_script('.', 'gdal_api_proxy', ' \"%s\" -1' % gdaltest.gdalserver_path, display_live_on_parent_stdout=True)
+ gdalserver_path = test_cli_utilities.get_cli_utility_path('gdalserver')
+ if gdalserver_path is None:
+ gdalserver_path = 'gdalserver'
+ return gdalserver_path
- if ret.find('Failed: 0') == -1:
- return 'fail'
- return 'success'
+def test_gdal_api_proxy_1(gdalserver_path):
+ subprocess.check_call([
+ sys.executable, 'gdal_api_proxy.py', gdalserver_path, '-2',
+ ])
###############################################################################
# Test connection to TCP server
-def gdal_api_proxy_2():
+def test_gdal_api_proxy_2(gdalserver_path):
if sys.version_info < (2, 6, 0):
- return 'skip'
-
- import test_py_scripts
- ret = test_py_scripts.run_py_script_as_external_script('.', 'gdal_api_proxy', ' \"%s\" -2' % gdaltest.gdalserver_path, display_live_on_parent_stdout=True)
-
- if ret.find('Failed: 0') == -1:
- return 'fail'
+ pytest.skip()
- return 'success'
+ subprocess.check_call([
+ sys.executable, 'gdal_api_proxy.py', gdalserver_path, '-2',
+ ])
###############################################################################
# Test connection to Unix socket server
-def gdal_api_proxy_3():
+def test_gdal_api_proxy_3(gdalserver_path):
if sys.version_info < (2, 6, 0):
- return 'skip'
+ pytest.skip()
if sys.platform == 'win32':
- return 'skip'
+ pytest.skip()
if sys.platform == 'darwin':
- print("Fails on MacOSX ('ERROR 1: posix_spawnp() failed'. Not sure why.")
- return 'skip'
+ pytest.skip("Fails on MacOSX ('ERROR 1: posix_spawnp() failed'. Not sure why.")
- import test_py_scripts
- ret = test_py_scripts.run_py_script_as_external_script('.', 'gdal_api_proxy', ' \"%s\" -3' % gdaltest.gdalserver_path, display_live_on_parent_stdout=True)
-
- if ret.find('Failed: 0') == -1:
- return 'fail'
-
- return 'success'
+ subprocess.check_call([
+ sys.executable, 'gdal_api_proxy.py', gdalserver_path, '-3',
+ ])
###############################################################################
# Test -nofork mode
-def gdal_api_proxy_4():
+def test_gdal_api_proxy_4(gdalserver_path):
if sys.version_info < (2, 6, 0):
- return 'skip'
+ pytest.skip()
if sys.platform == 'win32':
- return 'skip'
+ pytest.skip()
if sys.platform == 'darwin':
- print("Fails on MacOSX ('ERROR 1: posix_spawnp() failed'. Not sure why.")
- return 'skip'
-
- import test_py_scripts
- ret = test_py_scripts.run_py_script_as_external_script('.', 'gdal_api_proxy', ' \"%s\" -4' % gdaltest.gdalserver_path, display_live_on_parent_stdout=True)
-
- if ret.find('Failed: 0') == -1:
- return 'fail'
+ pytest.skip("Fails on MacOSX ('ERROR 1: posix_spawnp() failed'. Not sure why.")
- return 'success'
+ subprocess.check_call([
+ sys.executable, 'gdal_api_proxy.py', gdalserver_path, '-4',
+ ])
###############################################################################
#
-def gdal_api_proxy_sub():
+def _gdal_api_proxy_sub():
src_ds = gdal.Open('data/byte.tif')
src_cs = src_ds.GetRasterBand(1).Checksum()
@@ -137,9 +121,7 @@ def gdal_api_proxy_sub():
src_ds = None
drv = gdal.IdentifyDriver('data/byte.tif')
- if drv.GetDescription() != 'API_PROXY':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert drv.GetDescription() == 'API_PROXY'
ds = gdal.GetDriverByName('GTiff').Create('tmp/byte.tif', 1, 1, 3)
ds = None
@@ -147,448 +129,258 @@ def gdal_api_proxy_sub():
src_ds = gdal.Open('data/byte.tif')
ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/byte.tif', src_ds, options=['TILED=YES'])
got_cs = ds.GetRasterBand(1).Checksum()
- if src_cs != got_cs:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_cs == got_cs
ds = None
ds = gdal.Open('tmp/byte.tif', gdal.GA_Update)
ds.SetGeoTransform([1, 2, 3, 4, 5, 6])
got_gt = ds.GetGeoTransform()
- if src_gt == got_gt:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_gt != got_gt
ds.SetGeoTransform(src_gt)
got_gt = ds.GetGeoTransform()
- if src_gt != got_gt:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_gt == got_gt
- if ds.GetGCPCount() != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetGCPCount() == 0
- if ds.GetGCPProjection() != '':
- print(ds.GetGCPProjection())
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetGCPProjection() == ''
- if ds.GetGCPs():
- gdaltest.post_reason('fail')
- return 'fail'
+ assert not ds.GetGCPs()
gcps = [gdal.GCP(0, 1, 2, 3, 4)]
ds.SetGCPs(gcps, "foo")
got_gcps = ds.GetGCPs()
- if len(got_gcps) != 1:
- gdaltest.post_reason('fail')
- return 'fail'
-
- if got_gcps[0].GCPLine != gcps[0].GCPLine or \
- got_gcps[0].GCPPixel != gcps[0].GCPPixel or \
- got_gcps[0].GCPX != gcps[0].GCPX or \
- got_gcps[0].GCPY != gcps[0].GCPY:
- gdaltest.post_reason('fail')
- return 'fail'
-
- if ds.GetGCPProjection() != 'foo':
- gdaltest.post_reason('fail')
- print(ds.GetGCPProjection())
- return 'fail'
+ assert len(got_gcps) == 1
+
+ assert (got_gcps[0].GCPLine == gcps[0].GCPLine and \
+ got_gcps[0].GCPPixel == gcps[0].GCPPixel and \
+ got_gcps[0].GCPX == gcps[0].GCPX and \
+ got_gcps[0].GCPY == gcps[0].GCPY)
+
+ assert ds.GetGCPProjection() == 'foo'
ds.SetGCPs([], "")
- if ds.GetGCPs():
- gdaltest.post_reason('fail')
- return 'fail'
+ assert not ds.GetGCPs()
ds.SetProjection('')
got_prj = ds.GetProjectionRef()
- if src_prj == got_prj:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_prj != got_prj
ds.SetProjection(src_prj)
got_prj = ds.GetProjectionRef()
- if src_prj != got_prj:
- gdaltest.post_reason('fail')
- print(src_prj)
- print(got_prj)
- return 'fail'
+ assert src_prj == got_prj
ds.GetRasterBand(1).Fill(0)
got_cs = ds.GetRasterBand(1).Checksum()
- if got_cs != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_cs == 0
ds.GetRasterBand(1).WriteRaster(0, 0, 20, 20, src_data)
got_cs = ds.GetRasterBand(1).Checksum()
- if src_cs != got_cs:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_cs == got_cs
ds.GetRasterBand(1).Fill(0)
got_cs = ds.GetRasterBand(1).Checksum()
- if got_cs != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_cs == 0
ds.WriteRaster(0, 0, 20, 20, src_data)
got_cs = ds.GetRasterBand(1).Checksum()
- if src_cs != got_cs:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_cs == got_cs
# Not bound to SWIG
# ds.AdviseRead(0,0,20,20,20,20)
got_data = ds.ReadRaster(0, 0, 20, 20)
- if src_data != got_data:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_data == got_data
got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 20, 20)
- if src_data != got_data:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_data == got_data
got_data_weird_spacing = ds.ReadRaster(0, 0, 20, 20, buf_pixel_space=1, buf_line_space=32)
- if len(got_data_weird_spacing) != 32 * (20 - 1) + 20:
- gdaltest.post_reason('fail')
- print(len(got_data_weird_spacing))
- return 'fail'
+ assert len(got_data_weird_spacing) == 32 * (20 - 1) + 20
- if got_data[20:20 + 20] != got_data_weird_spacing[32:32 + 20]:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_data[20:20 + 20] == got_data_weird_spacing[32:32 + 20]
got_data_weird_spacing = ds.GetRasterBand(1).ReadRaster(0, 0, 20, 20, buf_pixel_space=1, buf_line_space=32)
- if len(got_data_weird_spacing) != 32 * (20 - 1) + 20:
- gdaltest.post_reason('fail')
- print(len(got_data_weird_spacing))
- return 'fail'
+ assert len(got_data_weird_spacing) == 32 * (20 - 1) + 20
- if got_data[20:20 + 20] != got_data_weird_spacing[32:32 + 20]:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_data[20:20 + 20] == got_data_weird_spacing[32:32 + 20]
got_block = ds.GetRasterBand(1).ReadBlock(0, 0)
- if len(got_block) != 256 * 256:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert len(got_block) == 256 * 256
- if got_data[20:20 + 20] != got_block[256:256 + 20]:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_data[20:20 + 20] == got_block[256:256 + 20]
ds.FlushCache()
ds.GetRasterBand(1).FlushCache()
got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 20, 20)
- if src_data != got_data:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_data == got_data
- if len(ds.GetFileList()) != 1:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert len(ds.GetFileList()) == 1
- if ds.AddBand(gdal.GDT_Byte) == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.AddBand(gdal.GDT_Byte) != 0
got_md = ds.GetMetadata()
- if src_md != got_md:
- gdaltest.post_reason('fail')
- print(src_md)
- print(got_md)
- return 'fail'
+ assert src_md == got_md
- if ds.GetMetadataItem('AREA_OR_POINT') != 'Area':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('AREA_OR_POINT') == 'Area'
- if ds.GetMetadataItem('foo') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('foo') is None
ds.SetMetadataItem('foo', 'bar')
- if ds.GetMetadataItem('foo') != 'bar':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('foo') == 'bar'
ds.SetMetadata({'foo': 'baz'}, 'OTHER')
- if ds.GetMetadataItem('foo', 'OTHER') != 'baz':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('foo', 'OTHER') == 'baz'
ds.GetRasterBand(1).SetMetadata({'foo': 'baw'}, 'OTHER')
- if ds.GetRasterBand(1).GetMetadataItem('foo', 'OTHER') != 'baw':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMetadataItem('foo', 'OTHER') == 'baw'
- if ds.GetMetadataItem('INTERLEAVE', 'IMAGE_STRUCTURE') != 'BAND':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('INTERLEAVE', 'IMAGE_STRUCTURE') == 'BAND'
- if ds.GetRasterBand(1).GetMetadata():
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetMetadata())
- return 'fail'
+ assert not ds.GetRasterBand(1).GetMetadata()
- if ds.GetRasterBand(1).GetMetadataItem('foo') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMetadataItem('foo') is None
ds.GetRasterBand(1).SetMetadataItem('foo', 'baz')
- if ds.GetRasterBand(1).GetMetadataItem('foo') != 'baz':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMetadataItem('foo') == 'baz'
ds.GetRasterBand(1).SetMetadata({'foo': 'baw'})
- if ds.GetRasterBand(1).GetMetadataItem('foo') != 'baw':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMetadataItem('foo') == 'baw'
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GrayIndex:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_GrayIndex
ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_Undefined)
ct = ds.GetRasterBand(1).GetColorTable()
- if ct is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ct is None
ct = gdal.ColorTable()
ct.SetColorEntry(0, (1, 2, 3))
- if ds.GetRasterBand(1).SetColorTable(ct) != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).SetColorTable(ct) == 0
ct = ds.GetRasterBand(1).GetColorTable()
- if ct is None:
- gdaltest.post_reason('fail')
- return 'fail'
- if ct.GetColorEntry(0) != (1, 2, 3, 255):
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ct is not None
+ assert ct.GetColorEntry(0) == (1, 2, 3, 255)
ct = ds.GetRasterBand(1).GetColorTable()
- if ct is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ct is not None
- if ds.GetRasterBand(1).SetColorTable(None) != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).SetColorTable(None) == 0
ct = ds.GetRasterBand(1).GetColorTable()
- if ct is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ct is None
rat = ds.GetRasterBand(1).GetDefaultRAT()
- if rat is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert rat is None
- if ds.GetRasterBand(1).SetDefaultRAT(None) != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).SetDefaultRAT(None) == 0
ref_rat = gdal.RasterAttributeTable()
- if ds.GetRasterBand(1).SetDefaultRAT(ref_rat) != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).SetDefaultRAT(ref_rat) == 0
rat = ds.GetRasterBand(1).GetDefaultRAT()
- if rat is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert rat is None
- if ds.GetRasterBand(1).SetDefaultRAT(None) != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).SetDefaultRAT(None) == 0
rat = ds.GetRasterBand(1).GetDefaultRAT()
- if rat is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert rat is None
- if ds.GetRasterBand(1).GetMinimum() is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMinimum() is None
got_stats = ds.GetRasterBand(1).GetStatistics(0, 0)
- if got_stats[3] >= 0.0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_stats[3] < 0.0
got_stats = ds.GetRasterBand(1).GetStatistics(1, 1)
- if got_stats[0] != 74.0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_stats[0] == 74.0
- if ds.GetRasterBand(1).GetMinimum() != 74.0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMinimum() == 74.0
- if ds.GetRasterBand(1).GetMaximum() != 255.0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaximum() == 255.0
ds.GetRasterBand(1).SetStatistics(1, 2, 3, 4)
got_stats = ds.GetRasterBand(1).GetStatistics(1, 1)
- if got_stats != [1, 2, 3, 4]:
- print(got_stats)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_stats == [1, 2, 3, 4]
ds.GetRasterBand(1).ComputeStatistics(0)
got_stats = ds.GetRasterBand(1).GetStatistics(1, 1)
- if got_stats[0] != 74.0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_stats[0] == 74.0
minmax = ds.GetRasterBand(1).ComputeRasterMinMax()
- if minmax != (74.0, 255.0):
- gdaltest.post_reason('fail')
- print(minmax)
- return 'fail'
+ assert minmax == (74.0, 255.0)
- if ds.GetRasterBand(1).GetOffset() != 0.0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOffset() == 0.0
- if ds.GetRasterBand(1).GetScale() != 1.0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetScale() == 1.0
ds.GetRasterBand(1).SetOffset(10.0)
- if ds.GetRasterBand(1).GetOffset() != 10.0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOffset() == 10.0
ds.GetRasterBand(1).SetScale(2.0)
- if ds.GetRasterBand(1).GetScale() != 2.0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetScale() == 2.0
ds.BuildOverviews('NEAR', [2])
- if ds.GetRasterBand(1).GetOverviewCount() != 1:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 1
- if ds.GetRasterBand(1).GetOverview(-1) is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverview(-1) is None
- if ds.GetRasterBand(1).GetOverview(0) is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverview(0) is not None
- if ds.GetRasterBand(1).GetOverview(0) is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverview(0) is not None
got_hist = ds.GetRasterBand(1).GetHistogram()
- if len(got_hist) != 256:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert len(got_hist) == 256
(minval, maxval, nitems, got_hist2) = ds.GetRasterBand(1).GetDefaultHistogram()
- if minval != -0.5:
- gdaltest.post_reason('fail')
- return 'fail'
- if maxval != 255.5:
- gdaltest.post_reason('fail')
- return 'fail'
- if nitems != 256:
- gdaltest.post_reason('fail')
- return 'fail'
- if got_hist != got_hist2:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert minval == -0.5
+ assert maxval == 255.5
+ assert nitems == 256
+ assert got_hist == got_hist2
ds.GetRasterBand(1).SetDefaultHistogram(1, 2, [3])
(minval, maxval, nitems, got_hist3) = ds.GetRasterBand(1).GetDefaultHistogram()
- if minval != 1:
- gdaltest.post_reason('fail')
- return 'fail'
- if maxval != 2:
- gdaltest.post_reason('fail')
- return 'fail'
- if nitems != 1:
- gdaltest.post_reason('fail')
- return 'fail'
- if got_hist3[0] != 3:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert minval == 1
+ assert maxval == 2
+ assert nitems == 1
+ assert got_hist3[0] == 3
got_nodatavalue = ds.GetRasterBand(1).GetNoDataValue()
- if got_nodatavalue is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_nodatavalue is None
ds.GetRasterBand(1).SetNoDataValue(123)
got_nodatavalue = ds.GetRasterBand(1).GetNoDataValue()
- if got_nodatavalue != 123:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_nodatavalue == 123
- if ds.GetRasterBand(1).GetMaskFlags() != 8:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == 8
- if ds.GetRasterBand(1).GetMaskBand() is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskBand() is not None
ret = ds.GetRasterBand(1).DeleteNoDataValue()
- if ret != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret == 0
got_nodatavalue = ds.GetRasterBand(1).GetNoDataValue()
- if got_nodatavalue is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_nodatavalue is None
ds.CreateMaskBand(0)
- if ds.GetRasterBand(1).GetMaskFlags() != 2:
- print(ds.GetRasterBand(1).GetMaskFlags())
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == 2
- if ds.GetRasterBand(1).GetMaskBand() is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskBand() is not None
ds.GetRasterBand(1).CreateMaskBand(0)
- if ds.GetRasterBand(1).HasArbitraryOverviews() != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).HasArbitraryOverviews() == 0
ds.GetRasterBand(1).SetUnitType('foo')
- if ds.GetRasterBand(1).GetUnitType() != 'foo':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetUnitType() == 'foo'
- if ds.GetRasterBand(1).GetCategoryNames() is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetCategoryNames() is None
ds.GetRasterBand(1).SetCategoryNames(['foo'])
- if ds.GetRasterBand(1).GetCategoryNames() != ['foo']:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetCategoryNames() == ['foo']
ds.GetRasterBand(1).SetDescription('bar')
@@ -596,40 +388,33 @@ def gdal_api_proxy_sub():
gdal.GetDriverByName('GTiff').Delete('tmp/byte.tif')
- return 'success'
-
###############################################################################
#
-def gdal_api_proxy_sub_clean():
+def _gdal_api_proxy_sub_clean():
if gdaltest.api_proxy_server_p is not None:
try:
gdaltest.api_proxy_server_p.terminate()
- except:
+ except Exception:
pass
gdaltest.api_proxy_server_p.wait()
gdal.Unlink('tmp/gdalapiproxysocket')
- return 'success'
-
-
-gdaltest_list = [gdal_api_proxy_1,
- gdal_api_proxy_2,
- gdal_api_proxy_3,
- gdal_api_proxy_4]
if __name__ == '__main__':
+ sys.path.insert(0, '../pymod')
+ import gdaltest
if len(sys.argv) >= 3 and sys.argv[2] == '-1':
gdal.SetConfigOption('GDAL_API_PROXY', 'YES')
if sys.platform == 'win32':
- gdalserver_path = sys.argv[1]
+ gdalserver_path = sys.argv[1] # noqa
gdal.SetConfigOption('GDAL_API_PROXY_SERVER', gdalserver_path)
gdaltest.api_proxy_server_p = None
- gdaltest_list = [gdal_api_proxy_sub]
+ gdaltest_list = [_gdal_api_proxy_sub]
elif len(sys.argv) >= 3 and sys.argv[2] == '-2':
@@ -653,7 +438,7 @@ def gdal_api_proxy_sub_clean():
gdal.SetConfigOption('GDAL_API_PROXY_SERVER', 'localhost:%d' % port)
print('port = %d' % port)
gdaltest.api_proxy_server_p = p
- gdaltest_list = [gdal_api_proxy_sub, gdal_api_proxy_sub_clean]
+ gdaltest_list = [_gdal_api_proxy_sub, _gdal_api_proxy_sub_clean]
else:
gdaltest_list = []
@@ -667,7 +452,7 @@ def gdal_api_proxy_sub_clean():
gdal.SetConfigOption('GDAL_API_PROXY', 'YES')
gdal.SetConfigOption('GDAL_API_PROXY_SERVER', 'tmp/gdalapiproxysocket')
gdaltest.api_proxy_server_p = p
- gdaltest_list = [gdal_api_proxy_sub, gdal_api_proxy_sub_clean]
+ gdaltest_list = [_gdal_api_proxy_sub, _gdal_api_proxy_sub_clean]
else:
try:
p.terminate()
@@ -686,7 +471,7 @@ def gdal_api_proxy_sub_clean():
gdal.SetConfigOption('GDAL_API_PROXY', 'YES')
gdal.SetConfigOption('GDAL_API_PROXY_SERVER', 'tmp/gdalapiproxysocket')
gdaltest.api_proxy_server_p = p
- gdaltest_list = [gdal_api_proxy_sub, gdal_api_proxy_sub_clean]
+ gdaltest_list = [_gdal_api_proxy_sub, _gdal_api_proxy_sub_clean]
else:
try:
p.terminate()
@@ -695,8 +480,5 @@ def gdal_api_proxy_sub_clean():
p.wait()
gdaltest_list = []
- gdaltest.setup_run('gdal_api_proxy')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ for func in gdaltest_list:
+ func()
diff --git a/autotest/gcore/gdal_stats.py b/autotest/gcore/gdal_stats.py
index 25b031db1277..7619d97db01d 100755
--- a/autotest/gcore/gdal_stats.py
+++ b/autotest/gcore/gdal_stats.py
@@ -28,24 +28,23 @@
###############################################################################
import os
-import sys
import struct
import shutil
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Test handling NaN with GDT_Float32 data
-def stats_nan_1():
+def test_stats_nan_1():
gdaltest.gtiff_drv = gdal.GetDriverByName('GTiff')
if gdaltest.gtiff_drv is None:
- return 'skip'
+ pytest.skip()
stats = (50.0, 58.0, 54.0, 2.5819888974716)
@@ -62,10 +61,10 @@ def stats_nan_1():
# Test handling NaN with GDT_Float64 data
-def stats_nan_2():
+def test_stats_nan_2():
if gdaltest.gtiff_drv is None:
- return 'skip'
+ pytest.skip()
stats = (50.0, 58.0, 54.0, 2.5819888974716)
@@ -82,10 +81,10 @@ def stats_nan_2():
# Test stats on signed byte (#3151)
-def stats_signedbyte():
+def test_stats_signedbyte():
if gdaltest.gtiff_drv is None:
- return 'skip'
+ pytest.skip()
stats = (-128.0, 127.0, -0.2, 80.64)
@@ -103,24 +102,19 @@ def stats_signedbyte():
# Test return of GetStatistics() when we don't have stats and don't
# force their computation (#3572)
-def stats_dont_force():
+def test_stats_dont_force():
gdal.Unlink('data/byte.tif.aux.xml')
ds = gdal.Open('data/byte.tif')
stats = ds.GetRasterBand(1).GetStatistics(0, 0)
- if stats != [0, 0, 0, -1]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
-
- return 'success'
+ assert stats == [0, 0, 0, -1], 'did not get expected stats'
###############################################################################
# Test statistics when stored nodata value doesn't accurately match the nodata
# value used in the imagery (#3573)
-def stats_approx_nodata():
+def test_stats_approx_nodata():
shutil.copyfile('data/minfloat.tif', 'tmp/minfloat.tif')
try:
@@ -143,38 +137,25 @@ def stats_approx_nodata():
os.remove('tmp/minfloat.tif')
if nodata != -3.4028234663852886e+38:
- gdaltest.post_reason('did not get expected nodata')
print("%.18g" % nodata)
- return 'fail'
-
- if stats != [-3.0, 5.0, 1.0, 4.0]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
+ pytest.fail('did not get expected nodata')
- if md != {'STATISTICS_MEAN': '1', 'STATISTICS_MAXIMUM': '5', 'STATISTICS_MINIMUM': '-3', 'STATISTICS_STDDEV': '4', 'STATISTICS_VALID_PERCENT': '50'}:
- gdaltest.post_reason('did not get expected metadata')
- print(md)
- return 'fail'
+ assert stats == [-3.0, 5.0, 1.0, 4.0], 'did not get expected stats'
- if minmax != (-3.0, 5.0):
- gdaltest.post_reason('did not get expected minmax')
- print(minmax)
- return 'fail'
+ assert md == {'STATISTICS_MEAN': '1', 'STATISTICS_MAXIMUM': '5', 'STATISTICS_MINIMUM': '-3', 'STATISTICS_STDDEV': '4', 'STATISTICS_VALID_PERCENT': '50'}, \
+ 'did not get expected metadata'
- return 'success'
+ assert minmax == (-3.0, 5.0), 'did not get expected minmax'
###############################################################################
# Test read and copy of dataset with nan as nodata value (#3576)
-def stats_nan_3():
+def test_stats_nan_3():
src_ds = gdal.Open('data/nan32_nodata.tif')
nodata = src_ds.GetRasterBand(1).GetNoDataValue()
- if not gdaltest.isnan(nodata):
- gdaltest.post_reason('expected nan, got %f' % nodata)
- return 'fail'
+ assert gdaltest.isnan(nodata), ('expected nan, got %f' % nodata)
out_ds = gdaltest.gtiff_drv.CreateCopy('tmp/nan32_nodata.tif', src_ds)
del out_ds
@@ -191,123 +172,84 @@ def stats_nan_3():
ds = None
gdaltest.gtiff_drv.Delete('tmp/nan32_nodata.tif')
- if not gdaltest.isnan(nodata):
- gdaltest.post_reason('expected nan, got %f' % nodata)
- return 'fail'
-
- return 'success'
+ assert gdaltest.isnan(nodata), ('expected nan, got %f' % nodata)
###############################################################################
# Test reading a VRT with a complex source that define nan as band nodata
# and complex source nodata (#3576)
-def stats_nan_4():
+def test_stats_nan_4():
ds = gdal.Open('data/nan32_nodata.vrt')
cs = ds.GetRasterBand(1).Checksum()
nodata = ds.GetRasterBand(1).GetNoDataValue()
ds = None
- if cs != 874:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == 874, 'did not get expected checksum'
- if not gdaltest.isnan(nodata):
- gdaltest.post_reason('expected nan, got %f' % nodata)
- return 'fail'
-
- return 'success'
+ assert gdaltest.isnan(nodata), ('expected nan, got %f' % nodata)
###############################################################################
# Test reading a VRT with a complex source that define 0 as band nodata
# and complex source nodata (nan must be translated to 0 then) (#3576)
-def stats_nan_5():
+def test_stats_nan_5():
ds = gdal.Open('data/nan32_nodata_nan_to_zero.vrt')
cs = ds.GetRasterBand(1).Checksum()
nodata = ds.GetRasterBand(1).GetNoDataValue()
ds = None
- if cs != 978:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- if nodata != 0:
- gdaltest.post_reason('expected nan, got %f' % nodata)
- return 'fail'
+ assert cs == 978, 'did not get expected checksum'
- return 'success'
+ assert nodata == 0, ('expected nan, got %f' % nodata)
###############################################################################
# Test reading a warped VRT with nan as src nodata and dest nodata (#3576)
-def stats_nan_6():
+def test_stats_nan_6():
ds = gdal.Open('data/nan32_nodata_warp.vrt')
cs = ds.GetRasterBand(1).Checksum()
nodata = ds.GetRasterBand(1).GetNoDataValue()
ds = None
- if cs != 874:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- if not gdaltest.isnan(nodata):
- gdaltest.post_reason('expected nan, got %f' % nodata)
- return 'fail'
+ assert cs == 874, 'did not get expected checksum'
- return 'success'
+ assert gdaltest.isnan(nodata), ('expected nan, got %f' % nodata)
###############################################################################
# Test reading a warped VRT with nan as src nodata and 0 as dest nodata (#3576)
-def stats_nan_7():
+def test_stats_nan_7():
ds = gdal.Open('data/nan32_nodata_warp_nan_to_zero.vrt')
cs = ds.GetRasterBand(1).Checksum()
nodata = ds.GetRasterBand(1).GetNoDataValue()
ds = None
- if cs != 978:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == 978, 'did not get expected checksum'
- if nodata != 0:
- gdaltest.post_reason('expected nan, got %f' % nodata)
- return 'fail'
-
- return 'success'
+ assert nodata == 0, ('expected nan, got %f' % nodata)
###############################################################################
# Test reading a warped VRT with zero as src nodata and nan as dest nodata (#3576)
-def stats_nan_8():
+def test_stats_nan_8():
ds = gdal.Open('data/nan32_nodata_warp_zero_to_nan.vrt')
cs = ds.GetRasterBand(1).Checksum()
nodata = ds.GetRasterBand(1).GetNoDataValue()
ds = None
- if cs != 874:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- if not gdaltest.isnan(nodata):
- gdaltest.post_reason('expected nan, got %f' % nodata)
- return 'fail'
+ assert cs == 874, 'did not get expected checksum'
- return 'success'
+ assert gdaltest.isnan(nodata), ('expected nan, got %f' % nodata)
###############################################################################
# Test statistics computation when nodata = +/- inf
@@ -318,7 +260,7 @@ def stats_nodata_inf_progress_cbk(value, string, extra):
extra[0] = value
-def stats_nodata_inf():
+def test_stats_nodata_inf():
ds = gdal.GetDriverByName('HFA').Create('/vsimem/stats_nodata_inf.img', 3, 1, 1, gdal.GDT_Float32)
ds.GetRasterBand(1).SetNoDataValue(gdaltest.neginf())
@@ -329,20 +271,12 @@ def stats_nodata_inf():
ds.GetRasterBand(1).Checksum()
user_data = [0]
stats = ds.GetRasterBand(1).ComputeStatistics(False, stats_nodata_inf_progress_cbk, user_data)
- if user_data[0] != 1.0:
- gdaltest.post_reason('did not get expected pct')
- print(user_data[0])
- return 'fail'
+ assert user_data[0] == 1.0, 'did not get expected pct'
ds = None
gdal.GetDriverByName('HFA').Delete('/vsimem/stats_nodata_inf.img')
- if stats != [-2.0, 1.0, -0.5, 1.5]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
-
- return 'success'
+ assert stats == [-2.0, 1.0, -0.5, 1.5], 'did not get expected stats'
###############################################################################
@@ -353,34 +287,29 @@ def stats_nodata_check(filename, expected_nodata):
nodata = ds.GetRasterBand(1).GetNoDataValue()
ds = None
- if nodata != expected_nodata:
- gdaltest.post_reason('did not get expected nodata value')
- print(nodata)
- return 'fail'
+ assert nodata == expected_nodata, 'did not get expected nodata value'
- return 'success'
-
-def stats_nodata_neginf_linux():
+def test_stats_nodata_neginf_linux():
return stats_nodata_check('data/stats_nodata_neginf.tif', gdaltest.neginf())
-def stats_nodata_neginf_msvc():
+def test_stats_nodata_neginf_msvc():
return stats_nodata_check('data/stats_nodata_neginf_msvc.tif', gdaltest.neginf())
-def stats_nodata_posinf_linux():
+def test_stats_nodata_posinf_linux():
return stats_nodata_check('data/stats_nodata_posinf.tif', gdaltest.posinf())
-def stats_nodata_posinf_msvc():
+def test_stats_nodata_posinf_msvc():
return stats_nodata_check('data/stats_nodata_posinf_msvc.tif', gdaltest.posinf())
###############################################################################
# Test standard deviation computation on huge values
-def stats_stddev_huge_values():
+def test_stats_stddev_huge_values():
gdal.FileFromMemBuffer('/vsimem/stats_stddev_huge_values.asc',
"""ncols 4
@@ -394,21 +323,17 @@ def stats_stddev_huge_values():
100000000 100000002 100000000 100000002""")
ds = gdal.Open('/vsimem/stats_stddev_huge_values.asc')
stats = ds.GetRasterBand(1).ComputeStatistics(0)
- if stats != [100000000.0, 100000002.0, 100000001.0, 1.0]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
+ assert stats == [100000000.0, 100000002.0, 100000001.0, 1.0], \
+ 'did not get expected stats'
ds = None
gdal.GetDriverByName('AAIGRID').Delete('/vsimem/stats_stddev_huge_values.asc')
- return 'success'
-
###############################################################################
# Test approximate statistics computation on a square shaped raster whose first column
# of blocks is nodata only
-def stats_square_shape():
+def test_stats_square_shape():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/stats_square_shape.tif', 32, 32, options=['TILED=YES', 'BLOCKXSIZE=16', 'BLOCKYSIZE=16'])
ds.GetRasterBand(1).SetNoDataValue(0)
@@ -420,26 +345,18 @@ def stats_square_shape():
gdal.GetDriverByName('GTiff').Delete('/vsimem/stats_square_shape.tif')
- if stats != [255, 255, 255, 0]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
- if hist[255] != 16 * 16:
- gdaltest.post_reason('did not get expected histogram')
- print(hist)
- return 'fail'
+ assert stats == [255, 255, 255, 0], 'did not get expected stats'
+ assert hist[255] == 16 * 16, 'did not get expected histogram'
if minmax != (255, 255):
- gdaltest.post_reason('did not get expected minmax')
print(hist)
- return 'fail'
-
- return 'success'
+ pytest.fail('did not get expected minmax')
+
###############################################################################
# Test when nodata = FLT_MIN (#6578)
-def stats_flt_min():
+def test_stats_flt_min():
shutil.copyfile('data/flt_min.tif', 'tmp/flt_min.tif')
try:
@@ -461,28 +378,20 @@ def stats_flt_min():
os.remove('tmp/flt_min.tif')
if nodata != 1.17549435082228751e-38:
- gdaltest.post_reason('did not get expected nodata')
print("%.18g" % nodata)
- return 'fail'
-
- if stats != [0.0, 1.0, 0.33333333333333337, 0.47140452079103168] and \
- stats != [0.0, 1.0, 0.33333333333333331, 0.47140452079103168]: # 32 bit
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
+ pytest.fail('did not get expected nodata')
- if minmax != (0.0, 1.0):
- gdaltest.post_reason('did not get expected minmax')
- print(minmax)
- return 'fail'
+ assert (stats == [0.0, 1.0, 0.33333333333333337, 0.47140452079103168] or \
+ stats == [0.0, 1.0, 0.33333333333333331, 0.47140452079103168]), \
+ 'did not get expected stats'
- return 'success'
+ assert minmax == (0.0, 1.0), 'did not get expected minmax'
###############################################################################
# Test when nodata = DBL_MIN (#6578)
-def stats_dbl_min():
+def test_stats_dbl_min():
shutil.copyfile('data/dbl_min.tif', 'tmp/dbl_min.tif')
try:
@@ -504,28 +413,20 @@ def stats_dbl_min():
os.remove('tmp/dbl_min.tif')
if nodata != 2.22507385850720138e-308:
- gdaltest.post_reason('did not get expected nodata')
print("%.18g" % nodata)
- return 'fail'
-
- if stats != [0.0, 1.0, 0.33333333333333337, 0.47140452079103168] and \
- stats != [0.0, 1.0, 0.33333333333333331, 0.47140452079103168]: # 32 bit
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
+ pytest.fail('did not get expected nodata')
- if minmax != (0.0, 1.0):
- gdaltest.post_reason('did not get expected minmax')
- print(minmax)
- return 'fail'
+ assert (stats == [0.0, 1.0, 0.33333333333333337, 0.47140452079103168] or \
+ stats == [0.0, 1.0, 0.33333333333333331, 0.47140452079103168]), \
+ 'did not get expected stats'
- return 'success'
+ assert minmax == (0.0, 1.0), 'did not get expected minmax'
###############################################################################
# Test stats on a tiled Byte with partial tiles
-def stats_byte_partial_tiles():
+def test_stats_byte_partial_tiles():
ds = gdal.Translate('/vsimem/stats_byte_tiled.tif', '../gdrivers/data/small_world.tif',
creationOptions=['TILED=YES', 'BLOCKXSIZE=64', 'BLOCKYSIZE=64'])
@@ -535,11 +436,7 @@ def stats_byte_partial_tiles():
gdal.GetDriverByName('GTiff').Delete('/vsimem/stats_byte_tiled.tif')
expected_stats = [0.0, 255.0, 50.22115, 67.119029288849973]
- if stats != expected_stats:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert stats == expected_stats, 'did not get expected stats'
# Same but with nodata set
ds = gdal.Translate('/vsimem/stats_byte_tiled.tif', '../gdrivers/data/small_world.tif',
@@ -552,11 +449,8 @@ def stats_byte_partial_tiles():
expected_stats = [1.0, 255.0, 50.311081057390084, 67.14541389488096]
expected_stats_32bit = [1.0, 255.0, 50.311081057390084, 67.145413894880946]
- if stats != expected_stats and stats != expected_stats_32bit:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert stats == expected_stats or stats == expected_stats_32bit, \
+ 'did not get expected stats'
# Same but with nodata set but untiled and with non power of 16 block size
ds = gdal.Translate('/vsimem/stats_byte_untiled.tif', '../gdrivers/data/small_world.tif',
@@ -568,11 +462,7 @@ def stats_byte_partial_tiles():
gdal.GetDriverByName('GTiff').Delete('/vsimem/stats_byte_untiled.tif')
expected_stats = [1.0, 255.0, 50.378183963744554, 67.184793517649453]
- if stats != expected_stats:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert stats == expected_stats, 'did not get expected stats'
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/stats_byte_tiled.tif', 1000, 512,
options=['TILED=YES', 'BLOCKXSIZE=512', 'BLOCKYSIZE=512'])
@@ -582,11 +472,8 @@ def stats_byte_partial_tiles():
gdal.Unlink('/vsimem/stats_byte_tiled.tif')
expected_stats = [255.0, 255.0, 255.0, 0.0]
- if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert max([abs(stats[i] - expected_stats[i]) for i in range(4)]) <= 1e-15, \
+ 'did not get expected stats'
# Non optimized code path
ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
@@ -595,11 +482,8 @@ def stats_byte_partial_tiles():
ds = None
expected_stats = [1.0, 1.0, 1.0, 0.0]
- if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert max([abs(stats[i] - expected_stats[i]) for i in range(4)]) <= 1e-15, \
+ 'did not get expected stats'
ds = gdal.GetDriverByName('MEM').Create('', 3, 5)
ds.GetRasterBand(1).WriteRaster(0, 0, 3, 1, struct.pack('B' * 3, 20, 30, 50))
@@ -611,11 +495,8 @@ def stats_byte_partial_tiles():
ds = None
expected_stats = [0.0, 255.0, 35.333333333333336, 60.785597709398971]
- if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert max([abs(stats[i] - expected_stats[i]) for i in range(4)]) <= 1e-15, \
+ 'did not get expected stats'
ds = gdal.GetDriverByName('MEM').Create('', 32 + 2, 2)
ds.GetRasterBand(1).Fill(1)
@@ -624,11 +505,8 @@ def stats_byte_partial_tiles():
ds = None
expected_stats = [0.0, 255.0, 4.7205882352941178, 30.576733555893391]
- if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert max([abs(stats[i] - expected_stats[i]) for i in range(4)]) <= 1e-15, \
+ 'did not get expected stats'
ds = gdal.GetDriverByName('MEM').Create('', 32 + 2, 2)
ds.GetRasterBand(1).Fill(1)
@@ -638,19 +516,14 @@ def stats_byte_partial_tiles():
ds = None
expected_stats = [0.0, 255.0, 4.7205882352941178, 30.576733555893391]
- if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
-
- return 'success'
+ assert max([abs(stats[i] - expected_stats[i]) for i in range(4)]) <= 1e-15, \
+ 'did not get expected stats'
###############################################################################
# Test stats on uint16
-def stats_uint16():
+def test_stats_uint16():
ds = gdal.Translate('/vsimem/stats_uint16_tiled.tif', '../gdrivers/data/small_world.tif',
outputType=gdal.GDT_UInt16,
@@ -662,11 +535,7 @@ def stats_uint16():
gdal.GetDriverByName('GTiff').Delete('/vsimem/stats_uint16_tiled.tif')
expected_stats = [0.0, 65535.0, 50.22115 * 65535 / 255, 67.119029288849973 * 65535 / 255]
- if stats != expected_stats:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert stats == expected_stats, 'did not get expected stats'
ds = gdal.Translate('/vsimem/stats_uint16_untiled.tif', '../gdrivers/data/small_world.tif',
options='-srcwin 0 0 399 200 -scale 0 255 0 65535 -ot UInt16')
@@ -676,11 +545,7 @@ def stats_uint16():
gdal.GetDriverByName('GTiff').Delete('/vsimem/stats_uint16_untiled.tif')
expected_stats = [0.0, 65535.0, 12923.9921679198, 17259.703026841547]
- if stats != expected_stats:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert stats == expected_stats, 'did not get expected stats'
# Same but with nodata set but untiled and with non power of 16 block size
ds = gdal.Translate('/vsimem/stats_uint16_untiled.tif', '../gdrivers/data/small_world.tif',
@@ -692,11 +557,7 @@ def stats_uint16():
gdal.GetDriverByName('GTiff').Delete('/vsimem/stats_uint16_untiled.tif')
expected_stats = [257.0, 65535.0, 50.378183963744554 * 65535 / 255, 67.184793517649453 * 65535 / 255]
- if stats != expected_stats:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert stats == expected_stats, 'did not get expected stats'
for fill_val in [0, 1, 32767, 32768, 65535]:
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/stats_uint16_tiled.tif', 1000, 512, 1, gdal.GDT_UInt16,
@@ -708,11 +569,8 @@ def stats_uint16():
expected_stats = [fill_val, fill_val, fill_val, 0.0]
if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
print(fill_val)
- print(expected_stats)
- return 'fail'
+ pytest.fail('did not get expected stats')
# Test remaining pixels after multiple of 32
ds = gdal.GetDriverByName('MEM').Create('', 32 + 2, 1, 1, gdal.GDT_UInt16)
@@ -722,11 +580,8 @@ def stats_uint16():
ds = None
expected_stats = [0.0, 65535.0, 1928.4411764705883, 11072.48066469611]
- if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert max([abs(stats[i] - expected_stats[i]) for i in range(4)]) <= 1e-15, \
+ 'did not get expected stats'
# Non optimized code path
for fill_val in [0, 1, 32767, 32768, 65535]:
@@ -737,11 +592,8 @@ def stats_uint16():
expected_stats = [fill_val, fill_val, fill_val, 0.0]
if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
print(fill_val)
- print(expected_stats)
- return 'fail'
+ pytest.fail('did not get expected stats')
ds = gdal.GetDriverByName('MEM').Create('', 3, 5, 1, gdal.GDT_UInt16)
ds.GetRasterBand(1).WriteRaster(0, 0, 3, 1, struct.pack('H' * 3, 20, 30, 50))
@@ -753,11 +605,8 @@ def stats_uint16():
ds = None
expected_stats = [0.0, 65535.0, 4387.333333333333, 16342.408927558861]
- if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- print(expected_stats)
- return 'fail'
+ assert max([abs(stats[i] - expected_stats[i]) for i in range(4)]) <= 1e-15, \
+ 'did not get expected stats'
ds = gdal.GetDriverByName('MEM').Create('', 2, 2, 1, gdal.GDT_UInt16)
ds.GetRasterBand(1).WriteRaster(0, 0, 2, 1, struct.pack('H' * 2, 0, 65535))
@@ -766,50 +615,35 @@ def stats_uint16():
ds = None
expected_stats = [0.0, 65535.0, 32767.5, 32767.000003814814]
- if max([abs(stats[i] - expected_stats[i]) for i in range(4)]) > 1e-15:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
-
- return 'success'
+ assert max([abs(stats[i] - expected_stats[i]) for i in range(4)]) <= 1e-15, \
+ 'did not get expected stats'
###############################################################################
# Test a case where the nodata value is almost the maximum value of float32
-def stats_nodata_almost_max_float32():
+def test_stats_nodata_almost_max_float32():
gdal.FileFromMemBuffer('/vsimem/float32_almost_nodata_max_float32.tif',
open('data/float32_almost_nodata_max_float32.tif', 'rb').read())
ds = gdal.Open('/vsimem/float32_almost_nodata_max_float32.tif')
minmax = ds.GetRasterBand(1).ComputeRasterMinMax()
- if minmax != (0, 0):
- gdaltest.post_reason('did not get expected minmax')
- print(minmax)
- return 'fail'
+ assert minmax == (0, 0), 'did not get expected minmax'
stats = ds.GetRasterBand(1).ComputeStatistics(False)
- if stats != [0, 0, 0, 0]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
+ assert stats == [0, 0, 0, 0], 'did not get expected stats'
hist = ds.GetRasterBand(1).GetHistogram(approx_ok=0)
- if hist[0] != 3:
- gdaltest.post_reason('did not get expected hist')
- print(hist)
- return 'fail'
+ assert hist[0] == 3, 'did not get expected hist'
ds = None
gdal.GetDriverByName('GTiff').Delete('/vsimem/float32_almost_nodata_max_float32.tif')
- return 'success'
-
###############################################################################
# Test STATISTICS_APPROXIMATE
-def stats_approx_stats_flag(dt=gdal.GDT_Byte, struct_frmt='B'):
+def test_stats_approx_stats_flag(dt=gdal.GDT_Byte, struct_frmt='B'):
ds = gdal.GetDriverByName('MEM').Create('', 2000, 2000, 1, dt)
ds.GetRasterBand(1).WriteRaster(1000, 1000, 1, 1, struct.pack(struct_frmt * 1, 20))
@@ -817,45 +651,29 @@ def stats_approx_stats_flag(dt=gdal.GDT_Byte, struct_frmt='B'):
approx_ok = 1
force = 1
stats = ds.GetRasterBand(1).GetStatistics(approx_ok, force)
- if stats != [0.0, 0.0, 0.0, 0.0]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
+ assert stats == [0.0, 0.0, 0.0, 0.0], 'did not get expected stats'
md = ds.GetRasterBand(1).GetMetadata()
- if md != {'STATISTICS_MEAN': '0', 'STATISTICS_MAXIMUM': '0', 'STATISTICS_MINIMUM': '0', 'STATISTICS_APPROXIMATE': 'YES', 'STATISTICS_STDDEV': '0', 'STATISTICS_VALID_PERCENT': '100'}:
- gdaltest.post_reason('did not get expected metadata')
- print(md)
- return 'fail'
+ assert md == {'STATISTICS_MEAN': '0', 'STATISTICS_MAXIMUM': '0', 'STATISTICS_MINIMUM': '0', 'STATISTICS_APPROXIMATE': 'YES', 'STATISTICS_STDDEV': '0', 'STATISTICS_VALID_PERCENT': '100'}, \
+ 'did not get expected metadata'
approx_ok = 0
force = 0
stats = ds.GetRasterBand(1).GetStatistics(approx_ok, force)
- if stats != [0.0, 0.0, 0.0, -1.0]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
+ assert stats == [0.0, 0.0, 0.0, -1.0], 'did not get expected stats'
approx_ok = 0
force = 1
stats = ds.GetRasterBand(1).GetStatistics(approx_ok, force)
- if stats[1] != 20.0:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
+ assert stats[1] == 20.0, 'did not get expected stats'
md = ds.GetRasterBand(1).GetMetadata()
- if 'STATISTICS_APPROXIMATE' in md:
- gdaltest.post_reason('did not get expected metadata')
- print(md)
- return 'fail'
-
- return 'success'
+ assert 'STATISTICS_APPROXIMATE' not in md, 'did not get expected metadata'
-def stats_approx_stats_flag_float():
- return stats_approx_stats_flag(dt=gdal.GDT_Float32, struct_frmt='f')
+def test_stats_approx_stats_flag_float():
+ return test_stats_approx_stats_flag(dt=gdal.GDT_Float32, struct_frmt='f')
-def stats_all_nodata():
+def test_stats_all_nodata():
ds = gdal.GetDriverByName('MEM').Create('', 2000, 2000)
ds.GetRasterBand(1).SetNoDataValue(0)
@@ -863,10 +681,7 @@ def stats_all_nodata():
force = 1
with gdaltest.error_handler():
stats = ds.GetRasterBand(1).GetStatistics(approx_ok, force)
- if stats != [0.0, 0.0, 0.0, 0.0]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
+ assert stats == [0.0, 0.0, 0.0, 0.0], 'did not get expected stats'
ds = gdal.GetDriverByName('MEM').Create('', 2000, 2000, 1,
gdal.GDT_Float32)
@@ -875,64 +690,19 @@ def stats_all_nodata():
force = 1
with gdaltest.error_handler():
stats = ds.GetRasterBand(1).GetStatistics(approx_ok, force)
- if stats != [0.0, 0.0, 0.0, 0.0]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
-
- return 'success'
+ assert stats == [0.0, 0.0, 0.0, 0.0], 'did not get expected stats'
-def stats_float32_with_nodata_slightly_above_float_max():
+def test_stats_float32_with_nodata_slightly_above_float_max():
ds = gdal.Open('data/float32_with_nodata_slightly_above_float_max.tif')
my_min, my_max = ds.GetRasterBand(1).ComputeRasterMinMax()
- if (my_min, my_max) != (-1.0989999771118164, 0.703338623046875):
- gdaltest.post_reason('did not get expected stats')
- print(my_min, my_max)
- return 'fail'
-
- return 'success'
+ assert (my_min, my_max) == (-1.0989999771118164, 0.703338623046875), \
+ 'did not get expected stats'
###############################################################################
# Run tests
-gdaltest_list = [
- stats_nan_1,
- stats_nan_2,
- stats_signedbyte,
- stats_dont_force,
- stats_approx_nodata,
- stats_nan_3,
- stats_nan_4,
- stats_nan_5,
- stats_nan_6,
- stats_nan_7,
- stats_nan_8,
- stats_nodata_inf,
- stats_nodata_neginf_linux,
- stats_nodata_neginf_msvc,
- stats_nodata_posinf_linux,
- stats_nodata_posinf_msvc,
- stats_stddev_huge_values,
- stats_square_shape,
- stats_flt_min,
- stats_dbl_min,
- stats_byte_partial_tiles,
- stats_uint16,
- stats_nodata_almost_max_float32,
- stats_approx_stats_flag,
- stats_approx_stats_flag_float,
- stats_all_nodata,
- stats_float32_with_nodata_slightly_above_float_max,
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('gdal_stats')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+
diff --git a/autotest/gcore/geoloc.py b/autotest/gcore/geoloc.py
index 221d016dbd9c..94991b0f34d4 100755
--- a/autotest/gcore/geoloc.py
+++ b/autotest/gcore/geoloc.py
@@ -29,9 +29,7 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
import gdaltest
@@ -39,19 +37,10 @@
# Verify warped result.
-def geoloc_1():
+def test_geoloc_1():
tst = gdaltest.GDALTest('VRT', 'warpsst.vrt', 1, 61818)
return tst.testOpen(check_filelist=False)
-gdaltest_list = [
- geoloc_1]
-if __name__ == '__main__':
-
- gdaltest.setup_run('geoloc')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/gtiff_write.py b/autotest/gcore/gtiff_write.py
index 14e202385509..bf7f7a887229 100755
--- a/autotest/gcore/gtiff_write.py
+++ b/autotest/gcore/gtiff_write.py
@@ -25,48 +25,52 @@
# Boston, MA 02111-1307, USA.
###############################################################################
-import sys
-
-sys.path.append('../pymod')
+import pytest
import gdaltest
init_list = [
- ('byte.tif', 1, 4672, None),
- ('int16.tif', 1, 4672, None),
- ('uint16.tif', 1, 4672, None),
- ('int32.tif', 1, 4672, None),
- ('uint32.tif', 1, 4672, None),
- ('float32.tif', 1, 4672, None),
- ('float64.tif', 1, 4672, None),
- ('cint16.tif', 1, 5028, None),
- ('cint32.tif', 1, 5028, None),
- ('cfloat32.tif', 1, 5028, None),
- ('cfloat64.tif', 1, 5028, None)]
+ ('byte.tif', 4672),
+ ('int16.tif', 4672),
+ ('uint16.tif', 4672),
+ ('int32.tif', 4672),
+ ('uint32.tif', 4672),
+ ('float32.tif', 4672),
+ ('float64.tif', 4672),
+ ('cint16.tif', 5028),
+ ('cint32.tif', 5028),
+ ('cfloat32.tif', 5028),
+ ('cfloat64.tif', 5028)]
-gdaltest_list = []
# Some tests we don't need to do for each type.
-item = init_list[0]
-ut = gdaltest.GDALTest('GTiff', item[0], item[1], item[2])
-gdaltest_list.append((ut.testSetGeoTransform, item[0]))
-gdaltest_list.append((ut.testSetProjection, item[0]))
-gdaltest_list.append((ut.testSetMetadata, item[0]))
-
-# Others we do for each pixel type.
-for item in init_list:
- ut = gdaltest.GDALTest('GTiff', item[0], item[1], item[2])
- if ut is None:
- print('GTiff tests skipped')
- gdaltest_list.append((ut.testCreateCopy, item[0]))
- gdaltest_list.append((ut.testCreate, item[0]))
- gdaltest_list.append((ut.testSetNoDataValue, item[0]))
-
+@pytest.mark.parametrize(
+ 'testfunction', [
+ 'testSetGeoTransform',
+ 'testSetProjection',
+ 'testSetMetadata',
+ ]
+)
+@pytest.mark.require_driver('GTiff')
+def test_gtiff_set(testfunction):
+ ut = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672)
+ getattr(ut, testfunction)()
-if __name__ == '__main__':
- gdaltest.setup_run('gtiff_write')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+# Others we do for each pixel type.
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.parametrize(
+ 'testfunction', [
+ 'testCreateCopy',
+ 'testCreate',
+ 'testSetNoDataValue',
+ ]
+)
+@pytest.mark.require_driver('GTiff')
+def test_gtiff_create(filename, checksum, testfunction):
+ ut = gdaltest.GDALTest('GTiff', filename, 1, checksum)
+ getattr(ut, testfunction)()
diff --git a/autotest/gcore/hdf4_read.py b/autotest/gcore/hdf4_read.py
index b93989d8fcc2..8dfa67bc6723 100755
--- a/autotest/gcore/hdf4_read.py
+++ b/autotest/gcore/hdf4_read.py
@@ -26,49 +26,56 @@
# Boston, MA 02111-1307, USA.
###############################################################################
-import sys
-sys.path.append('../pymod')
+import pytest
import gdaltest
from osgeo import gdal
-###############################################################################
-# When imported build a list of units based on the files available.
-
-gdaltest_list = []
init_list = [
- ('byte_3.hdf', 1, 4672, None),
- ('int16_3.hdf', 1, 4672, None),
- ('uint16_3.hdf', 1, 4672, None),
- ('int32_3.hdf', 1, 4672, None),
- ('uint32_3.hdf', 1, 4672, None),
- ('float32_3.hdf', 1, 4672, None),
- ('float64_3.hdf', 1, 4672, None),
- ('utmsmall_3.hdf', 1, 50054, None),
- ('byte_2.hdf', 1, 4672, None),
- ('int16_2.hdf', 1, 4672, None),
- ('uint16_2.hdf', 1, 4672, None),
- ('int32_2.hdf', 1, 4672, None),
- ('uint32_2.hdf', 1, 4672, None),
- ('float32_2.hdf', 1, 4672, None),
- ('float64_2.hdf', 1, 4672, None),
- ('utmsmall_2.hdf', 1, 50054, None)]
+ ('byte_3.hdf', 4672),
+ ('int16_3.hdf', 4672),
+ ('uint16_3.hdf', 4672),
+ ('int32_3.hdf', 4672),
+ ('uint32_3.hdf', 4672),
+ ('float32_3.hdf', 4672),
+ ('float64_3.hdf', 4672),
+ ('utmsmall_3.hdf', 50054),
+ ('byte_2.hdf', 4672),
+ ('int16_2.hdf', 4672),
+ ('uint16_2.hdf', 4672),
+ ('int32_2.hdf', 4672),
+ ('uint32_2.hdf', 4672),
+ ('float32_2.hdf', 4672),
+ ('float64_2.hdf', 4672),
+ ('utmsmall_2.hdf', 50054)]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.require_driver('HDF4Image')
+def test_hdf4_open(filename, checksum):
+ ut = gdaltest.GDALTest('HDF4Image', filename, 1, checksum)
+ ut.testOpen()
+
###############################################################################
# Test HDF4_SDS with single subdataset
-def hdf4_read_online_1():
+def test_hdf4_read_online_1():
gdaltest.hdf4_drv = gdal.GetDriverByName('HDF4')
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
if not gdaltest.download_file('http://download.osgeo.org/gdal/data/hdf4/A2004259075000.L2_LAC_SST.hdf', 'A2004259075000.L2_LAC_SST.hdf'):
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('HDF4Image', 'tmp/cache/A2004259075000.L2_LAC_SST.hdf', 1, 28189, filename_absolute=1)
@@ -78,242 +85,192 @@ def hdf4_read_online_1():
# Test HDF4_SDS with GEOLOCATION info
-def hdf4_read_online_2():
+def test_hdf4_read_online_2():
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
if not gdaltest.download_file('http://download.osgeo.org/gdal/data/hdf4/A2006005182000.L2_LAC_SST.x.hdf', 'A2006005182000.L2_LAC_SST.x.hdf'):
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('HDF4Image', 'HDF4_SDS:UNKNOWN:"tmp/cache/A2006005182000.L2_LAC_SST.x.hdf":13', 1, 13209, filename_absolute=1)
- ret = tst.testOpen()
- if ret != 'success':
- return ret
+ tst.testOpen()
ds = gdal.Open('HDF4_SDS:UNKNOWN:"tmp/cache/A2006005182000.L2_LAC_SST.x.hdf":13')
md = ds.GetMetadata('GEOLOCATION')
ds = None
- if md['X_DATASET'] != 'HDF4_SDS:UNKNOWN:"tmp/cache/A2006005182000.L2_LAC_SST.x.hdf":11':
- gdaltest.post_reason('Did not get expected X_DATASET')
- return 'fail'
-
- return 'success'
+ assert md['X_DATASET'] == 'HDF4_SDS:UNKNOWN:"tmp/cache/A2006005182000.L2_LAC_SST.x.hdf":11', \
+ 'Did not get expected X_DATASET'
###############################################################################
# Test HDF4_EOS:EOS_GRID
-def hdf4_read_online_3():
+def test_hdf4_read_online_3():
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
if not gdaltest.download_file('http://download.osgeo.org/gdal/data/hdf4/MO36MW14.chlor_MODIS.ADD2001089.004.2002186190207.hdf', 'MO36MW14.chlor_MODIS.ADD2001089.004.2002186190207.hdf'):
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('HDF4Image', 'tmp/cache/MO36MW14.chlor_MODIS.ADD2001089.004.2002186190207.hdf', 1, 34723, filename_absolute=1)
- ret = tst.testOpen()
- if ret != 'success':
- return ret
+ tst.testOpen()
ds = gdal.Open('tmp/cache/MO36MW14.chlor_MODIS.ADD2001089.004.2002186190207.hdf')
gt = ds.GetGeoTransform()
expected_gt = [-180.0, 0.3515625, 0.0, 90.0, 0.0, -0.3515625]
for i in range(6):
- if abs(gt[i] - expected_gt[i]) > 1e-8:
- print(gt)
- gdaltest.post_reason('did not get expected gt')
- return 'fail'
+ assert abs(gt[i] - expected_gt[i]) <= 1e-8, 'did not get expected gt'
srs = ds.GetProjectionRef()
- if srs.find('Clarke') == -1:
- gdaltest.post_reason('did not get expected projection')
- return 'fail'
+ assert srs.find('Clarke') != -1, 'did not get expected projection'
ds = None
- return 'success'
-
###############################################################################
# Test HDF4_SDS:SEAWIFS_L1A
-def hdf4_read_online_4():
+def test_hdf4_read_online_4():
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
if not gdaltest.download_file('http://download.osgeo.org/gdal/data/hdf4/S2002196124536.L1A_HDUN.BartonBendish.extract.hdf', 'S2002196124536.L1A_HDUN.BartonBendish.extract.hdf'):
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('HDF4Image', 'tmp/cache/S2002196124536.L1A_HDUN.BartonBendish.extract.hdf', 1, 33112, filename_absolute=1)
- ret = tst.testOpen()
- if ret != 'success':
- return ret
+ tst.testOpen()
ds = gdal.Open('tmp/cache/S2002196124536.L1A_HDUN.BartonBendish.extract.hdf')
- if ds.RasterCount != 8:
- gdaltest.post_reason('did not get expected band number')
- return 'fail'
+ assert ds.RasterCount == 8, 'did not get expected band number'
ds = None
- return 'success'
-
###############################################################################
# Test fix for #2208
-def hdf4_read_online_5():
+def test_hdf4_read_online_5():
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
# 13 MB
if not gdaltest.download_file('ftp://data.nodc.noaa.gov/pub/data.nodc/pathfinder/Version5.0/Monthly/1991/199101.s04m1pfv50-sst-16b.hdf', '199101.s04m1pfv50-sst-16b.hdf'):
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('HDF4Image', 'tmp/cache/199101.s04m1pfv50-sst-16b.hdf', 1, 41173, filename_absolute=1)
- ret = tst.testOpen()
- if ret != 'success':
- return ret
-
- return 'success'
+ tst.testOpen()
###############################################################################
# Test fix for #3386 where block size is dataset size
-def hdf4_read_online_6():
+def test_hdf4_read_online_6():
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
# 1 MB
if not gdaltest.download_file('http://download.osgeo.org/gdal/data/hdf4/MOD09Q1G_EVI.A2006233.h07v03.005.2008338190308.hdf', 'MOD09Q1G_EVI.A2006233.h07v03.005.2008338190308.hdf'):
- return 'skip'
+ pytest.skip()
# Test with quoting of components
tst = gdaltest.GDALTest('HDF4Image', 'HDF4_EOS:EOS_GRID:"tmp/cache/MOD09Q1G_EVI.A2006233.h07v03.005.2008338190308.hdf":"MODIS_NACP_EVI":"MODIS_EVI"', 1, 12197, filename_absolute=1)
- ret = tst.testOpen()
- if ret != 'success':
- return ret
+ tst.testOpen()
ds = gdal.Open('HDF4_EOS:EOS_GRID:tmp/cache/MOD09Q1G_EVI.A2006233.h07v03.005.2008338190308.hdf:MODIS_NACP_EVI:MODIS_EVI')
if 'GetBlockSize' in dir(gdal.Band):
(blockx, blocky) = ds.GetRasterBand(1).GetBlockSize()
- if blockx != 4800 or blocky != 4800:
- gdaltest.post_reason("Did not get expected block size")
- return 'fail'
+ assert blockx == 4800 and blocky == 4800, "Did not get expected block size"
cs = ds.GetRasterBand(1).Checksum()
- if cs != 12197:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == 12197, 'did not get expected checksum'
ds = None
- return 'success'
-
###############################################################################
# Test fix for #3386 where block size is smaller than dataset size
-def hdf4_read_online_7():
+def test_hdf4_read_online_7():
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
# 4 MB
if not gdaltest.download_file('http://download.osgeo.org/gdal/data/hdf4/MOD09A1.A2010041.h06v03.005.2010051001103.hdf', 'MOD09A1.A2010041.h06v03.005.2010051001103.hdf'):
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('HDF4Image', 'HDF4_EOS:EOS_GRID:tmp/cache/MOD09A1.A2010041.h06v03.005.2010051001103.hdf:MOD_Grid_500m_Surface_Reflectance:sur_refl_b01', 1, 54894, filename_absolute=1)
- ret = tst.testOpen()
- if ret != 'success':
- return ret
+ tst.testOpen()
ds = gdal.Open('HDF4_EOS:EOS_GRID:tmp/cache/MOD09A1.A2010041.h06v03.005.2010051001103.hdf:MOD_Grid_500m_Surface_Reflectance:sur_refl_b01')
if 'GetBlockSize' in dir(gdal.Band):
(blockx, blocky) = ds.GetRasterBand(1).GetBlockSize()
- if blockx != 2400 or blocky != 32:
- gdaltest.post_reason("Did not get expected block size")
- return 'fail'
+ assert blockx == 2400 and blocky == 32, "Did not get expected block size"
cs = ds.GetRasterBand(1).Checksum()
- if cs != 54894:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == 54894, 'did not get expected checksum'
ds = None
- return 'success'
-
###############################################################################
# Test reading a HDF4_EOS:EOS_GRID where preferred block height reported would be 1
# but that will lead to very poor performance (#3386)
-def hdf4_read_online_8():
+def test_hdf4_read_online_8():
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
# 5 MB
if not gdaltest.download_file('ftp://e4ftl01u.ecs.nasa.gov/MODIS_Composites/MOLT/MOD13Q1.005/2006.06.10/MOD13Q1.A2006161.h21v13.005.2008234103220.hdf', 'MOD13Q1.A2006161.h21v13.005.2008234103220.hdf'):
- return 'skip'
+ pytest.skip()
tst = gdaltest.GDALTest('HDF4Image', 'HDF4_EOS:EOS_GRID:tmp/cache/MOD13Q1.A2006161.h21v13.005.2008234103220.hdf:MODIS_Grid_16DAY_250m_500m_VI:250m 16 days NDVI', 1, 53837, filename_absolute=1)
- ret = tst.testOpen()
- if ret != 'success':
- return ret
+ tst.testOpen()
ds = gdal.Open('HDF4_EOS:EOS_GRID:tmp/cache/MOD13Q1.A2006161.h21v13.005.2008234103220.hdf:MODIS_Grid_16DAY_250m_500m_VI:250m 16 days NDVI')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 53837:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == 53837, 'did not get expected checksum'
if 'GetBlockSize' in dir(gdal.Band):
(blockx, blocky) = ds.GetRasterBand(1).GetBlockSize()
if blockx != 4800 or blocky == 1:
print('blockx=%d, blocky=%d' % (blockx, blocky))
- gdaltest.post_reason("Did not get expected block size")
- return 'fail'
+ pytest.fail("Did not get expected block size")
ds = None
- return 'success'
-
###############################################################################
# Test reading L1G MTL metadata metadata
-def hdf4_read_online_9():
+def test_hdf4_read_online_9():
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
if not gdaltest.download_file('http://www.geogratis.cgdi.gc.ca/download/landsat_7/hdf/L71002025_02520010722/L71002025_02520010722_MTL.L1G', 'L71002025_02520010722_MTL.L1G'):
- return 'skip'
+ pytest.skip()
if not gdaltest.download_file('http://www.geogratis.cgdi.gc.ca/download/landsat_7/hdf/L71002025_02520010722/L71002025_02520010722_HDF.L1G', 'L71002025_02520010722_HDF.L1G'):
- return 'skip'
+ pytest.skip()
f = open('tmp/cache/L71002025_02520010722_B10.L1G', 'wb')
f.close()
@@ -322,66 +279,30 @@ def hdf4_read_online_9():
gcp_count = ds.GetGCPCount()
ds = None
- if gcp_count != 4:
- gdaltest.post_reason('did not get expected gcp count')
- print(gcp_count)
- return 'fail'
-
- return 'success'
+ assert gcp_count == 4, 'did not get expected gcp count'
###############################################################################
# Test that non-tiled access works (#4672)
-def hdf4_read_online_10():
+def test_hdf4_read_online_10():
if gdaltest.hdf4_drv is None:
- return 'skip'
+ pytest.skip()
if not gdaltest.download_file('http://trac.osgeo.org/gdal/raw-attachment/ticket/4672/MOD16A2.A2000M01.h14v02.105.2010357183410.hdf', 'MOD16A2.A2000M01.h14v02.105.2010357183410.hdf'):
- return 'skip'
+ pytest.skip()
ds = gdal.Open('HDF4_EOS:EOS_GRID:"tmp/cache/MOD16A2.A2000M01.h14v02.105.2010357183410.hdf":MOD_Grid_MOD16A2:ET_1km')
if 'GetBlockSize' in dir(gdal.Band):
(blockx, blocky) = ds.GetRasterBand(1).GetBlockSize()
- if blockx != 1200 or blocky != 833:
- gdaltest.post_reason("Did not get expected block size")
- return 'fail'
+ assert blockx == 1200 and blocky == 833, "Did not get expected block size"
cs = ds.GetRasterBand(1).Checksum()
- if cs != 20976:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == 20976, 'did not get expected checksum'
ds = None
- return 'success'
-
-
-for item in init_list:
- ut = gdaltest.GDALTest('HDF4Image', item[0], item[1], item[2])
- if ut is None:
- print('HDF4 tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testOpen, item[0]))
-
-gdaltest_list.append(hdf4_read_online_1)
-gdaltest_list.append(hdf4_read_online_2)
-gdaltest_list.append(hdf4_read_online_3)
-gdaltest_list.append(hdf4_read_online_4)
-gdaltest_list.append(hdf4_read_online_5)
-gdaltest_list.append(hdf4_read_online_6)
-gdaltest_list.append(hdf4_read_online_7)
-gdaltest_list.append(hdf4_read_online_8)
-gdaltest_list.append(hdf4_read_online_9)
-gdaltest_list.append(hdf4_read_online_10)
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('hdf4_read')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/hdf4_write.py b/autotest/gcore/hdf4_write.py
index 7aa13e9571c1..e46cfdc2bf8e 100755
--- a/autotest/gcore/hdf4_write.py
+++ b/autotest/gcore/hdf4_write.py
@@ -25,51 +25,39 @@
# Boston, MA 02111-1307, USA.
###############################################################################
-import sys
-
-sys.path.append('../pymod')
-
+import pytest
import gdaltest
init_list = [
- ('byte.tif', 1, 4672, None),
- ('int16.tif', 1, 4672, None),
- ('uint16.tif', 1, 4672, None),
- ('int32.tif', 1, 4672, None),
- ('uint32.tif', 1, 4672, None),
- ('float32.tif', 1, 4672, None),
- ('float64.tif', 1, 4672, None),
- ('utmsmall.tif', 1, 50054, None)]
-
-gdaltest_list = []
-
-for item in init_list:
- ut = gdaltest.GDALTest('HDF4Image', item[0], item[1], item[2],
- options=['RANK=3'])
- if ut is None:
- print('HDF4 tests skipped')
- gdaltest_list.append((ut.testCreateCopy, item[0] + " rank=3"))
- gdaltest_list.append((ut.testCreate, item[0] + " rank=3"))
- gdaltest_list.append((ut.testSetGeoTransform, item[0] + " rank=3"))
- gdaltest_list.append((ut.testSetProjection, item[0] + " rank=3"))
- gdaltest_list.append((ut.testSetMetadata, item[0] + " rank=3"))
- gdaltest_list.append((ut.testSetNoDataValue, item[0] + " rank=3"))
- gdaltest_list.append((ut.testSetDescription, item[0] + " rank=3"))
- ut = gdaltest.GDALTest('HDF4Image', item[0], item[1], item[2],
- options=['RANK=2'])
- if ut is None:
- print('HDF4 tests skipped')
- gdaltest_list.append((ut.testCreateCopy, item[0] + " rank=2"))
- gdaltest_list.append((ut.testSetGeoTransform, item[0] + " rank=2"))
- gdaltest_list.append((ut.testSetProjection, item[0] + " rank=2"))
- gdaltest_list.append((ut.testSetMetadata, item[0] + " rank=2"))
- gdaltest_list.append((ut.testSetNoDataValue, item[0] + " rank=2"))
- gdaltest_list.append((ut.testSetDescription, item[0] + " rank=2"))
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('hdf_write')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ ('byte.tif', 4672),
+ ('int16.tif', 4672),
+ ('uint16.tif', 4672),
+ ('int32.tif', 4672),
+ ('uint32.tif', 4672),
+ ('float32.tif', 4672),
+ ('float64.tif', 4672),
+ ('utmsmall.tif', 50054)
+]
+
+
+@pytest.mark.parametrize(
+ 'rank', [2, 3], ids=lambda x: 'rank%d' % x
+)
+@pytest.mark.parametrize(
+ 'filename,checksum', init_list, ids=[arg[0].split('.')[0] for arg in init_list]
+)
+@pytest.mark.parametrize(
+ 'testfunction', [
+ 'testCreateCopy',
+ 'testCreate',
+ 'testSetGeoTransform',
+ 'testSetProjection',
+ 'testSetMetadata',
+ 'testSetNoDataValue',
+ 'testSetDescription',
+ ]
+)
+@pytest.mark.require_driver('HDF4Image')
+def test_hdf4_write(filename, checksum, testfunction, rank):
+ ut = gdaltest.GDALTest('HDF4Image', filename, 1, checksum, options=['RANK=%d' % rank])
+ getattr(ut, testfunction)()
diff --git a/autotest/gcore/hfa_read.py b/autotest/gcore/hfa_read.py
index aa49e1a57bd4..2d0a2454fef1 100755
--- a/autotest/gcore/hfa_read.py
+++ b/autotest/gcore/hfa_read.py
@@ -28,54 +28,42 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
+import pytest
from osgeo import gdal
import gdaltest
-###############################################################################
-# When imported build a list of units based on the files available.
-
-gdaltest_list = []
init_list = [
- ('byte.img', 1, 4672, None),
- ('int16.img', 1, 4672, None),
- ('uint16.img', 1, 4672, None),
- ('int32.img', 1, 4672, None),
- ('uint32.img', 1, 4672, None),
- ('float32.img', 1, 4672, None),
- ('float64.img', 1, 4672, None),
- ('utmsmall.img', 1, 50054, None),
- ('2bit_compressed.img', 1, 11918, None)]
-
+ ('byte.img', 4672),
+ ('int16.img', 4672),
+ ('uint16.img', 4672),
+ ('int32.img', 4672),
+ ('uint32.img', 4672),
+ ('float32.img', 4672),
+ ('float64.img', 4672),
+ ('utmsmall.img', 50054),
+ ('2bit_compressed.img', 11918)]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.require_driver('HFA')
+def test_hfa_open(filename, checksum):
+ ut = gdaltest.GDALTest('HFA', filename, 1, checksum)
+ ut.testOpen()
###############################################################################
# Test bugfix for https://oss-fuzz.com/v2/testcase-detail/6053338875428864
-def hfa_read_completedefn_recursion():
+def test_hfa_read_completedefn_recursion():
with gdaltest.error_handler():
gdal.Open('data/hfa_completedefn_recursion.img')
- return 'success'
-
-
-for item in init_list:
- ut = gdaltest.GDALTest('HFA', item[0], item[1], item[2])
- if ut is None:
- print('HFA tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testOpen, item[0]))
-
-
-gdaltest_list.append((hfa_read_completedefn_recursion))
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('hfa_read')
+
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/hfa_rfc40.py b/autotest/gcore/hfa_rfc40.py
index a4cf03ee3027..223c993ea9b1 100755
--- a/autotest/gcore/hfa_rfc40.py
+++ b/autotest/gcore/hfa_rfc40.py
@@ -30,25 +30,32 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-import numpy
from osgeo import gdal
-sys.path.append('../pymod')
+import pytest
-import gdaltest
-INT_DATA = numpy.array([197, 83, 46, 29, 1, 78, 23, 90, 12, 45])
-DOUBLE_DATA = numpy.array([0.1, 43.2, 78.1, 9.9, 23.0, 0.92, 82.5, 0.0, 1.0, 99.0])
-STRING_DATA = numpy.array(["sddf", "wess", "grbgr", "dewd", "ddww", "qwsqw",
- "gbfgbf", "wwqw3", "e", ""])
-STRING_DATA_INTS = numpy.array(["197", "83", "46", "29", "1", "78",
- "23", "90", "12", "45"])
-STRING_DATA_DOUBLES = numpy.array(["0.1", "43.2", "78.1", "9.9", "23.0", "0.92",
- "82.5", "0.0", "1.0", "99.0"])
-LONG_STRING_DATA = numpy.array(["sdfsdfsdfs", "sdweddw", "sdewdweee", "3423dedd",
- "jkejjjdjd", "edcdcdcdc", "fcdkmk4m534m", "edwededdd",
- "dedwedew", "wdedefrfrfrf"])
+try:
+ import numpy
+ array = numpy.array
+except ImportError:
+ numpy = None
+ array = list
+
+pytestmark = pytest.mark.skipif(numpy is None, reason="numpy not available")
+
+
+INT_DATA = array([197, 83, 46, 29, 1, 78, 23, 90, 12, 45])
+DOUBLE_DATA = array([0.1, 43.2, 78.1, 9.9, 23.0, 0.92, 82.5, 0.0, 1.0, 99.0])
+STRING_DATA = array(["sddf", "wess", "grbgr", "dewd", "ddww", "qwsqw",
+ "gbfgbf", "wwqw3", "e", ""])
+STRING_DATA_INTS = array(["197", "83", "46", "29", "1", "78",
+ "23", "90", "12", "45"])
+STRING_DATA_DOUBLES = array(["0.1", "43.2", "78.1", "9.9", "23.0", "0.92",
+ "82.5", "0.0", "1.0", "99.0"])
+LONG_STRING_DATA = array(["sdfsdfsdfs", "sdweddw", "sdewdweee", "3423dedd",
+ "jkejjjdjd", "edcdcdcdc", "fcdkmk4m534m", "edwededdd",
+ "dedwedew", "wdedefrfrfrf"])
class HFATestError(Exception):
@@ -162,8 +169,6 @@ def CreateAndWriteRAT(fname):
# ds.FlushCache()
ds = None
- return 'success'
-
def ReadAndCheckValues(fname, numrows):
ds = gdal.Open(fname)
@@ -215,8 +220,6 @@ def ReadAndCheckValues(fname, numrows):
# print('succeeded reading')
ds = None
- return 'success'
-
def CheckSetGetValues(fname):
# check the 'legacy' get and set value calls
@@ -258,8 +261,6 @@ def CheckSetGetValues(fname):
# ds.FlushCache()
ds = None
- return 'success'
-
def ExtendAndWrite(fname):
# write more data to the end of the RAT - will extend it
@@ -285,8 +286,6 @@ def ExtendAndWrite(fname):
# ds.FlushCache()
ds = None
- return 'success'
-
def CheckExtension(fname):
ds = gdal.Open(fname)
@@ -308,8 +307,6 @@ def CheckExtension(fname):
# print('extension data ok')
ds = None
- return 'success'
-
def WriteLongStrings(fname):
# this will force the string column to be re-written to accommodate
@@ -325,8 +322,6 @@ def WriteLongStrings(fname):
# ds.FlushCache()
ds = None
- return 'success'
-
def CheckLongStrings(fname):
ds = gdal.Open(fname)
@@ -340,8 +335,6 @@ def CheckLongStrings(fname):
# print("checked long strings ok")
ds = None
- return 'success'
-
def SetLinearBinning(fname):
ds = gdal.Open(fname, gdal.GA_Update)
@@ -355,8 +348,6 @@ def SetLinearBinning(fname):
# ds.FlushCache()
ds = None
- return 'success'
-
def CheckLinearBinning(fname):
ds = gdal.Open(fname)
@@ -376,8 +367,6 @@ def CheckLinearBinning(fname):
# print('linear binning ok')
ds = None
- return 'success'
-
def CheckClone(fname):
ds = gdal.Open(fname)
@@ -398,114 +387,88 @@ def CheckClone(fname):
# print("cloned ok")
ds = None
- return 'success'
-
# basic tests
-def hfa_rfc40_1():
+def test_hfa_rfc40_1():
return CreateAndWriteRAT("tmp/test.img")
-def hfa_rfc40_2():
+def test_hfa_rfc40_2():
return ReadAndCheckValues("tmp/test.img", 10)
# the older interface
-def hfa_rfc40_3():
+def test_hfa_rfc40_3():
return CheckSetGetValues("tmp/test.img")
# make sure original data not changed
-def hfa_rfc40_4():
+def test_hfa_rfc40_4():
return ReadAndCheckValues("tmp/test.img", 10)
# make it longer - data will be re-written
-def hfa_rfc40_5():
+def test_hfa_rfc40_5():
return ExtendAndWrite("tmp/test.img")
# make sure old data not changed
-def hfa_rfc40_6():
+def test_hfa_rfc40_6():
return ReadAndCheckValues("tmp/test.img", 20)
# new data at the end ok?
-def hfa_rfc40_7():
+def test_hfa_rfc40_7():
return CheckExtension("tmp/test.img")
# write some longer strings - string column will
# have to be re-written
-def hfa_rfc40_8():
+def test_hfa_rfc40_8():
return WriteLongStrings("tmp/test.img")
# make sure old data not changed
-def hfa_rfc40_9():
+def test_hfa_rfc40_9():
return ReadAndCheckValues("tmp/test.img", 20)
# check new data ok
-def hfa_rfc40_10():
+def test_hfa_rfc40_10():
return CheckLongStrings("tmp/test.img")
# linear binning
-def hfa_rfc40_11():
+def test_hfa_rfc40_11():
return SetLinearBinning("tmp/test.img")
# linear binning
-def hfa_rfc40_12():
+def test_hfa_rfc40_12():
return CheckLinearBinning("tmp/test.img")
# clone
-def hfa_rfc40_13():
+def test_hfa_rfc40_13():
return CheckClone("tmp/test.img")
# serialize not available from Python...
-def hfa_rfc40_cleanup():
+def test_hfa_rfc40_cleanup():
gdal.GetDriverByName('HFA').Delete("tmp/test.img")
- return 'success'
-
-
-gdaltest_list = [
- hfa_rfc40_1,
- hfa_rfc40_2,
- hfa_rfc40_3,
- hfa_rfc40_4,
- hfa_rfc40_5,
- hfa_rfc40_6,
- hfa_rfc40_7,
- hfa_rfc40_8,
- hfa_rfc40_9,
- hfa_rfc40_10,
- hfa_rfc40_11,
- hfa_rfc40_12,
- hfa_rfc40_13,
- hfa_rfc40_cleanup,
-]
-
-if __name__ == '__main__':
- gdaltest.setup_run('hfa_rfc40')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/hfa_srs.py b/autotest/gcore/hfa_srs.py
index 6140d3d33eb7..49ba42295436 100755
--- a/autotest/gcore/hfa_srs.py
+++ b/autotest/gcore/hfa_srs.py
@@ -28,107 +28,70 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
+
+import pytest
from osgeo import gdal
from osgeo import osr
-sys.path.append('../pymod')
-
-import gdaltest
-
###############################################################################
# Write a HFA/Imagine and read it back to check its SRS
-
-class TestHFASRS(object):
- def __init__(self, epsg_code, use_epsg_code, expected_fail):
- self.epsg_code = epsg_code
- self.use_epsg_code = use_epsg_code
- self.expected_fail = expected_fail
-
- def test(self):
- sr = osr.SpatialReference()
- sr.ImportFromEPSG(self.epsg_code)
- if self.use_epsg_code == 0:
- proj4str = sr.ExportToProj4()
- # print(proj4str)
- sr.SetFromUserInput(proj4str)
-
- ds = gdal.GetDriverByName('HFA').Create('/vsimem/TestHFASRS.img', 1, 1)
- ds.SetProjection(sr.ExportToWkt())
- ds = None
-
- ds = gdal.Open('/vsimem/TestHFASRS.img')
- wkt = ds.GetProjectionRef()
- sr2 = osr.SpatialReference()
- sr2.SetFromUserInput(wkt)
- ds = None
-
- gdal.Unlink('/vsimem/TestHFASRS.img')
-
- # For EPSG:2065. Those 2 datums are translated into D_S_JTSK in ESRI WKT... So for the purpose of
- # comparison, substitute one for another
- if sr.ExportToWkt().find('"System_Jednotne_Trigonometricke_Site_Katastralni_Ferro"') != -1 and \
- sr2.ExportToWkt().find('"System_Jednotne_Trigonometricke_Site_Katastralni"') != -1:
- wkt2 = sr2.ExportToWkt().replace('"System_Jednotne_Trigonometricke_Site_Katastralni"', '"System_Jednotne_Trigonometricke_Site_Katastralni_Ferro"')
- sr2.SetFromUserInput(wkt2)
-
- if (self.epsg_code == 4326 and sr2.GetAuthorityCode(None) != '4326') or sr.IsSame(sr2) != 1:
- if self.expected_fail:
- print('did not get expected SRS. known to be broken currently. FIXME!')
- # print(sr)
- # print(sr2)
- return 'expected_fail'
-
- gdaltest.post_reason('did not get expected SRS')
- print(sr)
- print(sr2)
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = []
-
-hfa_srs_list = [2758, # tmerc
- [2036, True], # sterea # failure caused by revert done in r22803
- 2046, # tmerc
- [3031, True], # stere
- [32661, True], # stere
- 3035, # laea
- 2062, # lcc
- 2065, # krovak
- 2066, # cass
- 2964, # aea
- [3410, True], # cea
- [3786, True], # eqc
- [2934, True], # merc
- 27200, # nzmg
- [2057, True], # omerc
- 29100, # poly
- 2056, # somerc
- 2027, # utm
- 4326, # longlat
- ]
-
-for item in hfa_srs_list:
- try:
- epsg_code = item[0]
- epsg_broken = item[1]
- except TypeError:
- epsg_code = item
- epsg_broken = False
-
- ut = TestHFASRS(epsg_code, 1, epsg_broken)
- gdaltest_list.append((ut.test, "hfa_srs_epsg_%d" % epsg_code))
- # ut = TestHFASRS( epsg_code, 0, epsg_proj4_broken )
- # gdaltest_list.append( (ut.test, "hfa_srs_proj4_of_epsg_%d" % epsg_code) )
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('hfa_srs')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+epsg_list = [
+ [2758, False], # tmerc
+ [2036, True], # sterea # failure caused by revert done in r22803
+ [2046, False], # tmerc
+ [3031, True], # stere
+ [32661, True], # stere
+ [3035, False], # laea
+ [2062, False], # lcc
+ [2065, False], # krovak
+ [2066, False], # cass
+ [2964, False], # aea
+ [3410, True], # cea
+ [3786, True], # eqc
+ [2934, True], # merc
+ [27200, False], # nzmg
+ [2057, True], # omerc
+ [29100, False], # poly
+ [2056, False], # somerc
+ [2027, False], # utm
+ [4326, False], # longlat
+]
+
+
+@pytest.mark.parametrize(
+ 'epsg_code,epsg_broken',
+ epsg_list,
+ ids=[str(r[0]) for r in epsg_list],
+)
+def test_hfa_srs(epsg_code, epsg_broken):
+ sr = osr.SpatialReference()
+ sr.ImportFromEPSG(epsg_code)
+
+ ds = gdal.GetDriverByName('HFA').Create('/vsimem/TestHFASRS.img', 1, 1)
+ ds.SetProjection(sr.ExportToWkt())
+ ds = None
+
+ ds = gdal.Open('/vsimem/TestHFASRS.img')
+ wkt = ds.GetProjectionRef()
+ sr2 = osr.SpatialReference()
+ sr2.SetFromUserInput(wkt)
+ ds = None
+
+ gdal.Unlink('/vsimem/TestHFASRS.img')
+
+ # For EPSG:2065. Those 2 datums are translated into D_S_JTSK in ESRI WKT... So for the purpose of
+ # comparison, substitute one for another
+ if sr.ExportToWkt().find('"System_Jednotne_Trigonometricke_Site_Katastralni_Ferro"') != -1 and \
+ sr2.ExportToWkt().find('"System_Jednotne_Trigonometricke_Site_Katastralni"') != -1:
+ wkt2 = sr2.ExportToWkt().replace('"System_Jednotne_Trigonometricke_Site_Katastralni"', '"System_Jednotne_Trigonometricke_Site_Katastralni_Ferro"')
+ sr2.SetFromUserInput(wkt2)
+
+ if (epsg_code == 4326 and sr2.GetAuthorityCode(None) != '4326') or sr.IsSame(sr2) != 1:
+ if epsg_broken:
+ pytest.xfail('did not get expected SRS. known to be broken currently. FIXME!')
+
+ print(sr)
+ print(sr2)
+ assert False, 'did not get expected SRS'
diff --git a/autotest/gcore/hfa_write.py b/autotest/gcore/hfa_write.py
index 134a6a60d521..fccc657e2a7d 100755
--- a/autotest/gcore/hfa_write.py
+++ b/autotest/gcore/hfa_write.py
@@ -31,11 +31,11 @@
###############################################################################
import os
-import sys
import shutil
-from osgeo import gdal
-sys.path.append('../pymod')
+import pytest
+
+from osgeo import gdal
import gdaltest
@@ -43,7 +43,7 @@
# test that we can write a small file with a custom layer name.
-def hfa_write_desc():
+def test_hfa_write_desc():
src_ds = gdal.Open('data/byte.tif')
@@ -59,22 +59,18 @@ def hfa_write_desc():
new_ds = gdal.Open('tmp/test_desc.img')
bnd = new_ds.GetRasterBand(1)
- if bnd.GetDescription() != 'CustomBandName':
- gdaltest.post_reason('Didnt get custom band name.')
- return 'fail'
+ assert bnd.GetDescription() == 'CustomBandName', 'Didnt get custom band name.'
bnd = None
new_ds = None
gdal.GetDriverByName('HFA').Delete('tmp/test_desc.img')
- return 'success'
-
###############################################################################
# test writing 4 bit files.
-def hfa_write_4bit():
+def test_hfa_write_4bit():
drv = gdal.GetDriverByName('HFA')
src_ds = gdal.Open('data/byte.tif')
ds = drv.CreateCopy('tmp/4bit.img', src_ds, options=['NBITS=1'])
@@ -84,22 +80,17 @@ def hfa_write_4bit():
ds = gdal.Open('tmp/4bit.img')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 252:
- gdaltest.post_reason('Got wrong checksum on 4bit image.')
- print(cs)
- return 'fail'
+ assert cs == 252, 'Got wrong checksum on 4bit image.'
ds = None
drv.Delete('tmp/4bit.img')
- return 'success'
-
###############################################################################
# test writing 4 bit files compressed.
-def hfa_write_4bit_compressed():
+def test_hfa_write_4bit_compressed():
drv = gdal.GetDriverByName('HFA')
src_ds = gdal.Open('data/byte.tif')
ds = drv.CreateCopy('tmp/4bitc.img', src_ds,
@@ -110,23 +101,18 @@ def hfa_write_4bit_compressed():
ds = gdal.Open('tmp/4bitc.img')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 252:
- gdaltest.post_reason('Got wrong checksum on 4bit image.')
- print(cs)
- return 'fail'
+ assert cs == 252, 'Got wrong checksum on 4bit image.'
ds = None
drv.Delete('tmp/4bitc.img')
- return 'success'
-
###############################################################################
# Test creating a file with a nodata value, and fetching otherwise unread
# blocks and verifying they are the nodata value. (#2427)
-def hfa_write_nd_invalid():
+def test_hfa_write_nd_invalid():
drv = gdal.GetDriverByName('HFA')
ds = drv.Create('tmp/ndinvalid.img', 512, 512, 1, gdal.GDT_Byte, [])
@@ -136,22 +122,17 @@ def hfa_write_nd_invalid():
ds = gdal.Open('tmp/ndinvalid.img')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 29754:
- gdaltest.post_reason('Got wrong checksum on invalid image.')
- print(cs)
- return 'fail'
+ assert cs == 29754, 'Got wrong checksum on invalid image.'
ds = None
drv.Delete('tmp/ndinvalid.img')
- return 'success'
-
###############################################################################
# Test updating .rrd overviews in place (#2524).
-def hfa_update_overviews():
+def test_hfa_update_overviews():
shutil.copyfile('data/small_ov.img', 'tmp/small.img')
shutil.copyfile('data/small_ov.rrd', 'tmp/small.rrd')
@@ -159,54 +140,38 @@ def hfa_update_overviews():
ds = gdal.Open('tmp/small.img', gdal.GA_Update)
result = ds.BuildOverviews(overviewlist=[2])
- if result != 0:
- print(result)
- gdaltest.post_reason('BuildOverviews() failed.')
- return 'fail'
+ assert result == 0, 'BuildOverviews() failed.'
ds = None
- return 'success'
-
###############################################################################
# Test cleaning external overviews.
-def hfa_clean_external_overviews():
+def test_hfa_clean_external_overviews():
ds = gdal.Open('tmp/small.img', gdal.GA_Update)
result = ds.BuildOverviews(overviewlist=[])
- if result != 0:
- gdaltest.post_reason('BuildOverviews() failed.')
- return 'fail'
+ assert result == 0, 'BuildOverviews() failed.'
- if ds.GetRasterBand(1).GetOverviewCount() != 0:
- gdaltest.post_reason('Overviews still exist.')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 0, 'Overviews still exist.'
ds = None
ds = gdal.Open('tmp/small.img')
- if ds.GetRasterBand(1).GetOverviewCount() != 0:
- gdaltest.post_reason('Overviews still exist.')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 0, 'Overviews still exist.'
ds = None
- try:
+ with pytest.raises(OSError, message='small.rrd still present.'):
os.stat('tmp/small.rrd')
- gdaltest.post_reason('small.rrd still present.')
- return 'fail'
- except OSError:
- pass
+
gdal.GetDriverByName('HFA').Delete('tmp/small.img')
- return 'success'
-
###############################################################################
# Test writing high frequency data (#2525).
-def hfa_bug_2525():
+def test_hfa_bug_2525():
drv = gdal.GetDriverByName('HFA')
ds = drv.Create('tmp/test_hfa.img', 64, 64, 1, gdal.GDT_UInt16, options=['COMPRESSED=YES'])
import struct
@@ -217,13 +182,11 @@ def hfa_bug_2525():
drv.Delete('tmp/test_hfa.img')
- return 'success'
-
###############################################################################
# Test building external overviews with HFA_USE_RRD=YES
-def hfa_use_rrd():
+def test_hfa_use_rrd():
shutil.copyfile('data/small_ov.img', 'tmp/small.img')
@@ -233,35 +196,27 @@ def hfa_use_rrd():
result = ds.BuildOverviews(overviewlist=[2])
gdal.SetConfigOption('HFA_USE_RRD', old_value)
- if result != 0:
- print(result)
- gdaltest.post_reason('BuildOverviews() failed.')
- return 'fail'
+ assert result == 0, 'BuildOverviews() failed.'
ds = None
try:
os.stat('tmp/small.rrd')
except OSError:
- gdaltest.post_reason('small.rrd not present.')
- return 'fail'
+ pytest.fail('small.rrd not present.')
ds = gdal.Open('tmp/small.img')
- if ds.GetRasterBand(1).GetOverview(0).Checksum() != 26148:
- print(ds.GetRasterBand(1).GetOverview(0).Checksum())
- gdaltest.post_reason('Unexpected checksum.')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverview(0).Checksum() == 26148, \
+ 'Unexpected checksum.'
ds = None
gdal.GetDriverByName('HFA').Delete('tmp/small.img')
- return 'success'
-
###############################################################################
# Test fix for #4831
-def hfa_update_existing_aux_overviews():
+def test_hfa_update_existing_aux_overviews():
gdal.SetConfigOption('USE_RRD', 'YES')
@@ -288,13 +243,11 @@ def hfa_update_existing_aux_overviews():
new_cs_ovr0 = ds.GetRasterBand(1).GetOverview(0).Checksum()
new_cs_ovr1 = ds.GetRasterBand(1).GetOverview(1).Checksum()
if cs_ovr0 != new_cs_ovr0:
- gdaltest.post_reason('fail')
gdal.SetConfigOption('USE_RRD', None)
- return 'fail'
+ pytest.fail()
if cs_ovr1 != new_cs_ovr1:
- gdaltest.post_reason('fail')
gdal.SetConfigOption('USE_RRD', None)
- return 'fail'
+ pytest.fail()
# and regenerate them twice in a row
ds.BuildOverviews('NEAR', overviewlist=[2, 4])
@@ -306,13 +259,11 @@ def hfa_update_existing_aux_overviews():
new_cs_ovr0 = ds.GetRasterBand(1).GetOverview(0).Checksum()
new_cs_ovr1 = ds.GetRasterBand(1).GetOverview(1).Checksum()
if cs_ovr0 != new_cs_ovr0:
- gdaltest.post_reason('fail')
gdal.SetConfigOption('USE_RRD', None)
- return 'fail'
+ pytest.fail()
if cs_ovr1 != new_cs_ovr1:
- gdaltest.post_reason('fail')
gdal.SetConfigOption('USE_RRD', None)
- return 'fail'
+ pytest.fail()
# and regenerate them with an extra overview level
ds.BuildOverviews('NEAR', overviewlist=[8])
@@ -323,26 +274,22 @@ def hfa_update_existing_aux_overviews():
new_cs_ovr0 = ds.GetRasterBand(1).GetOverview(0).Checksum()
new_cs_ovr1 = ds.GetRasterBand(1).GetOverview(1).Checksum()
if cs_ovr0 != new_cs_ovr0:
- gdaltest.post_reason('fail')
gdal.SetConfigOption('USE_RRD', None)
- return 'fail'
+ pytest.fail()
if cs_ovr1 != new_cs_ovr1:
- gdaltest.post_reason('fail')
gdal.SetConfigOption('USE_RRD', None)
- return 'fail'
+ pytest.fail()
ds = None
gdal.GetDriverByName('BMP').Delete('tmp/hfa_update_existing_aux_overviews.bmp')
gdal.SetConfigOption('USE_RRD', None)
- return 'success'
-
###############################################################################
# Test writing invalid WKT (#5258)
-def hfa_write_invalid_wkt():
+def test_hfa_write_invalid_wkt():
# No GEOGCS
ds = gdal.GetDriverByName('HFA').Create('/vsimem/hfa_write_invalid_wkt.img', 1, 1)
@@ -396,72 +343,82 @@ def hfa_write_invalid_wkt():
gdal.GetDriverByName('HFA').Delete('/vsimem/hfa_write_invalid_wkt.img')
- return 'success'
-
###############################################################################
# Get the driver, and verify a few things about it.
init_list = [
- ('byte.tif', 1, 4672, None),
- ('int16.tif', 1, 4672, None),
- ('uint16.tif', 1, 4672, None),
- ('int32.tif', 1, 4672, None),
- ('uint32.tif', 1, 4672, None),
- ('float32.tif', 1, 4672, None),
- ('float64.tif', 1, 4672, None),
- ('cfloat32.tif', 1, 5028, None),
- ('cfloat64.tif', 1, 5028, None),
- ('utmsmall.tif', 1, 50054, None)]
-
-gdaltest_list = [hfa_write_desc,
- hfa_write_4bit,
- hfa_write_4bit_compressed,
- hfa_write_nd_invalid,
- hfa_update_overviews,
- hfa_clean_external_overviews,
- hfa_bug_2525,
- hfa_use_rrd,
- hfa_update_existing_aux_overviews,
- hfa_write_invalid_wkt]
+ ('byte.tif', 4672),
+ ('int16.tif', 4672),
+ ('uint16.tif', 4672),
+ ('int32.tif', 4672),
+ ('uint32.tif', 4672),
+ ('float32.tif', 4672),
+ ('float64.tif', 4672),
+ ('cfloat32.tif', 5028),
+ ('cfloat64.tif', 5028),
+ ('utmsmall.tif', 50054)]
# full set of tests for normal mode.
-for item in init_list:
- ut1 = gdaltest.GDALTest('HFA', item[0], item[1], item[2])
- if ut1 is None:
- print('HFA tests skipped')
- gdaltest_list.append((ut1.testCreateCopy, item[0]))
- gdaltest_list.append((ut1.testCreate, item[0]))
- gdaltest_list.append((ut1.testSetGeoTransform, item[0]))
- gdaltest_list.append((ut1.testSetMetadata, item[0]))
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.parametrize(
+ 'testfunction', [
+ 'testCreateCopy',
+ 'testCreate',
+ 'testSetGeoTransform',
+ 'testSetMetadata',
+ ]
+)
+@pytest.mark.require_driver('HFA')
+def test_hfa_create_normal(filename, checksum, testfunction):
+ ut = gdaltest.GDALTest('HFA', filename, 1, checksum)
+ getattr(ut, testfunction)()
+
# Just a few for spill file, and compressed support.
short_list = [
- ('byte.tif', 1, 4672, None),
- ('uint16.tif', 1, 4672, None),
- ('float64.tif', 1, 4672, None)]
-
-for item in short_list:
- ut2 = gdaltest.GDALTest('HFA', item[0], item[1], item[2],
- options=['USE_SPILL=YES'])
- if ut2 is None:
- print('HFA tests skipped')
- gdaltest_list.append((ut2.testCreateCopy, item[0] + ' (spill)'))
- gdaltest_list.append((ut2.testCreate, item[0] + ' (spill)'))
-
- ut2 = gdaltest.GDALTest('HFA', item[0], item[1], item[2],
- options=['COMPRESS=YES'])
- if ut2 is None:
- print('HFA tests skipped')
-# gdaltest_list.append( (ut2.testCreateCopy, item[0] + ' (compressed)') )
- gdaltest_list.append((ut2.testCreate, item[0] + ' (compressed)'))
-
+ ('byte.tif', 4672),
+ ('uint16.tif', 4672),
+ ('float64.tif', 4672)]
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ short_list,
+ ids=[tup[0].split('.')[0] for tup in short_list],
+)
+@pytest.mark.parametrize(
+ 'testfunction', [
+ 'testCreateCopy',
+ 'testCreate',
+ ]
+)
+@pytest.mark.require_driver('HFA')
+def test_hfa_create_spill(filename, checksum, testfunction):
+ ut = gdaltest.GDALTest('HFA', filename, 1, checksum, options=['USE_SPILL=YES'])
+ getattr(ut, testfunction)()
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ short_list,
+ ids=[tup[0].split('.')[0] for tup in short_list],
+)
+@pytest.mark.parametrize(
+ 'testfunction', [
+ # 'testCreateCopy',
+ 'testCreate',
+ ]
+)
+@pytest.mark.require_driver('HFA')
+def test_hfa_create_compress(filename, checksum, testfunction):
+ ut = gdaltest.GDALTest('HFA', filename, 1, checksum, options=['COMPRESS=YES'])
+ getattr(ut, testfunction)()
-if __name__ == '__main__':
- gdaltest.setup_run('hfa_write')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/histogram.py b/autotest/gcore/histogram.py
index 21705be9d839..d4c6293db7c7 100755
--- a/autotest/gcore/histogram.py
+++ b/autotest/gcore/histogram.py
@@ -30,56 +30,43 @@
###############################################################################
import os
-import sys
import shutil
-sys.path.append('../pymod')
from osgeo import gdal
-import gdaltest
###############################################################################
# Fetch simple histogram.
-def histogram_1():
+def test_histogram_1():
ds = gdal.Open('data/utmsmall.tif')
hist = ds.GetRasterBand(1).GetHistogram()
exp_hist = [2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 99, 0, 0, 0, 0, 0, 0, 0, 0, 120, 0, 0, 0, 0, 0, 0, 0, 178, 0, 0, 0, 0, 0, 0, 0, 193, 0, 0, 0, 0, 0, 0, 0, 212, 0, 0, 0, 0, 0, 0, 0, 281, 0, 0, 0, 0, 0, 0, 0, 0, 365, 0, 0, 0, 0, 0, 0, 0, 460, 0, 0, 0, 0, 0, 0, 0, 533, 0, 0, 0, 0, 0, 0, 0, 544, 0, 0, 0, 0, 0, 0, 0, 0, 626, 0, 0, 0, 0, 0, 0, 0, 653, 0, 0, 0, 0, 0, 0, 0, 673, 0, 0, 0, 0, 0, 0, 0, 629, 0, 0, 0, 0, 0, 0, 0, 0, 586, 0, 0, 0, 0, 0, 0, 0, 541, 0, 0, 0, 0, 0, 0, 0, 435, 0, 0, 0, 0, 0, 0, 0, 348, 0, 0, 0, 0, 0, 0, 0, 341, 0, 0, 0, 0, 0, 0, 0, 0, 284, 0, 0, 0, 0, 0, 0, 0, 225, 0, 0, 0, 0, 0, 0, 0, 237, 0, 0, 0, 0, 0, 0, 0, 172, 0, 0, 0, 0, 0, 0, 0, 0, 159, 0, 0, 0, 0, 0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 824]
- if hist != exp_hist:
- gdaltest.post_reason('did not get expected histogram.')
- print(hist)
- return 'fail'
-
- return 'success'
+ assert hist == exp_hist, 'did not get expected histogram.'
###############################################################################
# Fetch histogram with specified sampling, using keywords.
-def histogram_2():
+def test_histogram_2():
ds = gdal.Open('data/utmsmall.tif')
hist = ds.GetRasterBand(1).GetHistogram(buckets=16, max=255.5, min=-0.5)
exp_hist = [10, 52, 115, 219, 371, 493, 825, 1077, 1279, 1302, 1127, 783, 625, 462, 331, 929]
- if hist != exp_hist:
- gdaltest.post_reason('did not get expected histogram.')
- print(hist)
- return 'fail'
-
- return 'success'
+ assert hist == exp_hist, 'did not get expected histogram.'
###############################################################################
# try on a different data type with out of range values included.
-def histogram_3():
+def test_histogram_3():
ds = gdal.Open('data/int32_withneg.grd')
hist = ds.GetRasterBand(1).GetHistogram(buckets=21, max=100, min=-100,
@@ -88,18 +75,13 @@ def histogram_3():
exp_hist = [0, 0, 0, 0, 0, 1, 0, 1, 1, 3, 3, 2, 0, 5, 3, 4, 0, 1, 1, 2, 3]
- if hist != exp_hist:
- gdaltest.post_reason('did not get expected histogram.')
- print(hist)
- return 'fail'
-
- return 'success'
+ assert hist == exp_hist, 'did not get expected histogram.'
###############################################################################
# try on a different data type without out of range values included.
-def histogram_4():
+def test_histogram_4():
ds = gdal.Open('data/int32_withneg.grd')
hist = ds.GetRasterBand(1).GetHistogram(buckets=21, max=100, min=-100,
@@ -108,71 +90,41 @@ def histogram_4():
exp_hist = [0, 0, 0, 0, 0, 1, 0, 1, 1, 3, 3, 2, 0, 5, 3, 4, 0, 1, 1, 2, 0]
- if hist != exp_hist:
- gdaltest.post_reason('did not get expected histogram.')
- print(hist)
- return 'fail'
+ assert hist == exp_hist, 'did not get expected histogram.'
ds = None
gdal.Unlink('data/int32_withneg.grd.aux.xml')
- return 'success'
-
###############################################################################
# Test GetDefaultHistogram() on the file.
-def histogram_5():
+def test_histogram_5():
ds = gdal.Open('data/utmsmall.tif')
hist = ds.GetRasterBand(1).GetDefaultHistogram(force=1)
exp_hist = (-0.5, 255.5, 256, [2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 0, 69, 0, 0, 0, 0, 0, 0, 0, 99, 0, 0, 0, 0, 0, 0, 0, 0, 120, 0, 0, 0, 0, 0, 0, 0, 178, 0, 0, 0, 0, 0, 0, 0, 193, 0, 0, 0, 0, 0, 0, 0, 212, 0, 0, 0, 0, 0, 0, 0, 281, 0, 0, 0, 0, 0, 0, 0, 0, 365, 0, 0, 0, 0, 0, 0, 0, 460, 0, 0, 0, 0, 0, 0, 0, 533, 0, 0, 0, 0, 0, 0, 0, 544, 0, 0, 0, 0, 0, 0, 0, 0, 626, 0, 0, 0, 0, 0, 0, 0, 653, 0, 0, 0, 0, 0, 0, 0, 673, 0, 0, 0, 0, 0, 0, 0, 629, 0, 0, 0, 0, 0, 0, 0, 0, 586, 0, 0, 0, 0, 0, 0, 0, 541, 0, 0, 0, 0, 0, 0, 0, 435, 0, 0, 0, 0, 0, 0, 0, 348, 0, 0, 0, 0, 0, 0, 0, 341, 0, 0, 0, 0, 0, 0, 0, 0, 284, 0, 0, 0, 0, 0, 0, 0, 225, 0, 0, 0, 0, 0, 0, 0, 237, 0, 0, 0, 0, 0, 0, 0, 172, 0, 0, 0, 0, 0, 0, 0, 0, 159, 0, 0, 0, 0, 0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 824])
- if hist != exp_hist:
- gdaltest.post_reason('did not get expected histogram.')
- print(hist)
- return 'fail'
+ assert hist == exp_hist, 'did not get expected histogram.'
ds = None
gdal.Unlink('data/utmsmall.tif.aux.xml')
- return 'success'
-
###############################################################################
# Test GetDefaultHistogram( force = 0 ) on a JPG file (#3304)
-def histogram_6():
+def test_histogram_6():
shutil.copy('../gdrivers/data/albania.jpg', 'tmp/albania.jpg')
ds = gdal.Open('tmp/albania.jpg')
hist = ds.GetRasterBand(1).GetDefaultHistogram(force=0)
- if hist is not None:
- gdaltest.post_reason('did not get expected histogram.')
- print(hist)
- return 'fail'
+ assert hist is None, 'did not get expected histogram.'
ds = None
os.unlink('tmp/albania.jpg')
- return 'success'
-
-
-gdaltest_list = [
- histogram_1,
- histogram_2,
- histogram_3,
- histogram_4,
- histogram_5,
- histogram_6
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('histogram')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/identify.py b/autotest/gcore/identify.py
index b2b2ee56f8d0..6557097d9356 100755
--- a/autotest/gcore/identify.py
+++ b/autotest/gcore/identify.py
@@ -28,105 +28,67 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
###############################################################################
# Simple try of identify driver on a tiff file.
-def identify_1():
+def test_identify_1():
file_list = gdal.ReadDir('data')
dr = gdal.IdentifyDriver('data/byte.tif', file_list)
- if dr is None or dr.GetDescription() != 'GTiff':
- gdaltest.post_reason('Got wrong driver for byte.tif')
- return 'fail'
-
- return 'success'
+ assert dr is not None and dr.GetDescription() == 'GTiff', \
+ 'Got wrong driver for byte.tif'
###############################################################################
# Test a file that won't be recognised.
-def identify_2():
+def test_identify_2():
file_list = gdal.ReadDir('data')
dr = gdal.IdentifyDriver('data/byte.pnm.aux.xml', file_list)
- if dr is not None:
- gdaltest.post_reason('Got a driver for byte.pnm.aux.xml!')
- return 'fail'
-
- return 'success'
+ assert dr is None, 'Got a driver for byte.pnm.aux.xml!'
###############################################################################
# Try identify on a directory.
-def identify_3():
+def test_identify_3():
dr = gdal.IdentifyDriver('data')
- if dr is not None:
- gdaltest.post_reason('Got a driver for data directory!')
- return 'fail'
-
- return 'success'
+ assert dr is None, 'Got a driver for data directory!'
###############################################################################
# Try IdentifyDriverEx
-def identify_4():
+def test_identify_4():
dr = gdal.IdentifyDriverEx('data/byte.tif')
- if dr is None or dr.GetDescription() != 'GTiff':
- gdaltest.post_reason('Got wrong driver for byte.tif')
- return 'fail'
+ assert dr is not None and dr.GetDescription() == 'GTiff', \
+ 'Got wrong driver for byte.tif'
dr = gdal.IdentifyDriverEx('data/byte.tif', gdal.OF_RASTER)
- if dr is None or dr.GetDescription() != 'GTiff':
- gdaltest.post_reason('Got wrong driver for byte.tif')
- return 'fail'
+ assert dr is not None and dr.GetDescription() == 'GTiff', \
+ 'Got wrong driver for byte.tif'
dr = gdal.IdentifyDriverEx('data/byte.tif', gdal.OF_VECTOR)
- if dr is not None:
- gdaltest.post_reason('Got wrong driver for byte.tif')
- return 'fail'
+ assert dr is None, 'Got wrong driver for byte.tif'
dr = gdal.IdentifyDriverEx('data/byte.tif', allowed_drivers=['HFA'])
- if dr is not None:
- gdaltest.post_reason('Got wrong driver for byte.tif')
- return 'fail'
+ assert dr is None, 'Got wrong driver for byte.tif'
dr = gdal.IdentifyDriverEx('../gdrivers/data/aea.dat', sibling_files=['aea.dat'])
- if dr is not None:
- gdaltest.post_reason('Got a driver, which was not expected!')
- return 'fail'
+ assert dr is None, 'Got a driver, which was not expected!'
dr = gdal.IdentifyDriverEx('../gdrivers/data/aea.dat', sibling_files=['aea.dat', 'aea.hdr'])
- if dr is None:
- gdaltest.post_reason('Did not get a driver!')
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = [
- identify_1,
- identify_2,
- identify_3,
- identify_4]
-
-if __name__ == '__main__':
+ assert dr is not None, 'Did not get a driver!'
- gdaltest.setup_run('identify')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/mask.py b/autotest/gcore/mask.py
index d7abdf9581a1..bd47f9b81eb7 100755
--- a/autotest/gcore/mask.py
+++ b/autotest/gcore/mask.py
@@ -30,96 +30,68 @@
###############################################################################
import os
-import sys
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Verify the checksum and flags for "all valid" case.
-def mask_1():
+def test_mask_1():
ds = gdal.Open('data/byte.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
band = ds.GetRasterBand(1)
- if band.GetMaskFlags() != gdal.GMF_ALL_VALID:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_ALL_VALID, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 4873:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
+ assert cs == 4873, 'Got wrong mask checksum'
my_min, my_max, mean, stddev = band.GetMaskBand().ComputeStatistics(0)
- if (my_min, my_max, mean, stddev) != (255, 255, 255, 0):
- gdaltest.post_reason('Got wrong mask stats')
- print(my_min, my_max, mean, stddev)
- return 'fail'
-
- return 'success'
+ assert (my_min, my_max, mean, stddev) == (255, 255, 255, 0), 'Got wrong mask stats'
###############################################################################
# Verify the checksum and flags for "nodata" case.
-def mask_2():
+def test_mask_2():
ds = gdal.Open('data/byte.vrt')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
band = ds.GetRasterBand(1)
- if band.GetMaskFlags() != gdal.GMF_NODATA:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_NODATA, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 4209:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4209, 'Got wrong mask checksum'
###############################################################################
# Verify the checksum and flags for "alpha" case.
-def mask_3():
+def test_mask_3():
ds = gdal.Open('data/stefan_full_rgba.png')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
# Test first mask.
band = ds.GetRasterBand(1)
- if band.GetMaskFlags() != gdal.GMF_ALPHA + gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_ALPHA + gdal.GMF_PER_DATASET, \
+ 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 10807:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
+ assert cs == 10807, 'Got wrong mask checksum'
# Verify second and third same as first.
@@ -129,36 +101,26 @@ def mask_3():
# We have commented the following tests as SWIG >= 1.3.37 is buggy !
# or str(band_2.GetMaskBand()) != str(band.GetMaskBand()) \
# or str(band_3.GetMaskBand()) != str(band.GetMaskBand())
- if band_2.GetMaskFlags() != band.GetMaskFlags() \
- or band_3.GetMaskFlags() != band.GetMaskFlags():
- gdaltest.post_reason('Band 2 or 3 does not seem to match first mask')
- return 'fail'
+ assert band_2.GetMaskFlags() == band.GetMaskFlags() and band_3.GetMaskFlags() == band.GetMaskFlags(), \
+ 'Band 2 or 3 does not seem to match first mask'
# Verify alpha has no mask.
band = ds.GetRasterBand(4)
- if band.GetMaskFlags() != gdal.GMF_ALL_VALID:
- gdaltest.post_reason('Did not get expected mask for alpha.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_ALL_VALID, \
+ 'Did not get expected mask for alpha.'
cs = band.GetMaskBand().Checksum()
- if cs != 36074:
- gdaltest.post_reason('Got wrong alpha mask checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 36074, 'Got wrong alpha mask checksum'
###############################################################################
# Copy a *real* masked dataset, and confirm masks copied properly.
-def mask_4():
+def test_mask_4():
src_ds = gdal.Open('../gdrivers/data/masked.jpg')
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
# NOTE: for now we copy to PNM since it does everything (overviews too)
# externally. Should eventually test with gtiff, hfa.
@@ -167,42 +129,33 @@ def mask_4():
src_ds = None
# confirm we got the custom mask on the copied dataset.
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('did not get expected mask flags')
- print(ds.GetRasterBand(1).GetMaskFlags())
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_PER_DATASET, \
+ 'did not get expected mask flags'
msk = ds.GetRasterBand(1).GetMaskBand()
cs = msk.Checksum()
expected_cs = 770
- if cs != expected_cs:
- gdaltest.post_reason('Did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == expected_cs, 'Did not get expected checksum'
msk = None
ds = None
- return 'success'
-
###############################################################################
# Create overviews for masked file, and verify the overviews have proper
# masks built for them.
-def mask_5():
+def test_mask_5():
# This crashes with libtiff 3.8.2, so skip it
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('tmp/mask_4.pnm', gdal.GA_Update)
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
# So that we instantiate the mask band before.
ds.GetRasterBand(1).GetMaskFlags()
@@ -212,19 +165,13 @@ def mask_5():
# confirm mask flags on overview.
ovr = ds.GetRasterBand(1).GetOverview(1)
- if ovr.GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('did not get expected mask flags')
- print(ovr.GetMaskFlags())
- return 'fail'
+ assert ovr.GetMaskFlags() == gdal.GMF_PER_DATASET, 'did not get expected mask flags'
msk = ovr.GetMaskBand()
cs = msk.Checksum()
expected_cs = 20505
- if cs != expected_cs:
- gdaltest.post_reason('Did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == expected_cs, 'Did not get expected checksum'
ovr = None
msk = None
ds = None
@@ -235,19 +182,13 @@ def mask_5():
# confirm mask flags on overview.
ovr = ds.GetRasterBand(1).GetOverview(1)
- if ovr.GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('did not get expected mask flags')
- print(ovr.GetMaskFlags())
- return 'fail'
+ assert ovr.GetMaskFlags() == gdal.GMF_PER_DATASET, 'did not get expected mask flags'
msk = ovr.GetMaskBand()
cs = msk.Checksum()
expected_cs = 20505
- if cs != expected_cs:
- gdaltest.post_reason('Did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == expected_cs, 'Did not get expected checksum'
ovr = None
msk = None
@@ -255,280 +196,193 @@ def mask_5():
gdal.GetDriverByName('PNM').Delete('tmp/mask_4.pnm')
- return 'success'
-
###############################################################################
# Test a TIFF file with 1 band and an embedded mask of 1 bit
-def mask_6():
+def test_mask_6():
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'FALSE')
ds = gdal.Open('data/test_with_mask_1bit.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
band = ds.GetRasterBand(1)
- if band.GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_PER_DATASET, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 100:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
+ assert cs == 100, 'Got wrong mask checksum'
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'TRUE')
- return 'success'
-
###############################################################################
# Test a TIFF file with 3 bands and an embedded mask of 1 band of 1 bit
-def mask_7():
+def test_mask_7():
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'FALSE')
ds = gdal.Open('data/test3_with_1mask_1bit.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
for i in (1, 2, 3):
band = ds.GetRasterBand(i)
- if band.GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_PER_DATASET, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 100:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
+ assert cs == 100, 'Got wrong mask checksum'
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'TRUE')
- return 'success'
-
###############################################################################
# Test a TIFF file with 1 band and an embedded mask of 8 bit.
# Note : The TIFF6 specification, page 37, only allows 1 BitsPerSample && 1 SamplesPerPixel,
-def mask_8():
+def test_mask_8():
ds = gdal.Open('data/test_with_mask_8bit.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
band = ds.GetRasterBand(1)
- if band.GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_PER_DATASET, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 1222:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 1222, 'Got wrong mask checksum'
###############################################################################
# Test a TIFF file with 3 bands with an embedded mask of 1 bit with 3 bands.
# Note : The TIFF6 specification, page 37, only allows 1 BitsPerSample && 1 SamplesPerPixel,
-def mask_9():
+def test_mask_9():
ds = gdal.Open('data/test3_with_mask_1bit.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
for i in (1, 2, 3):
band = ds.GetRasterBand(i)
- if band.GetMaskFlags() != 0:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == 0, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 100:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 100, 'Got wrong mask checksum'
+
###############################################################################
# Test a TIFF file with 3 bands with an embedded mask of 8 bit with 3 bands.
# Note : The TIFF6 specification, page 37, only allows 1 BitsPerSample && 1 SamplesPerPixel,
-def mask_10():
+def test_mask_10():
ds = gdal.Open('data/test3_with_mask_8bit.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
for i in (1, 2, 3):
band = ds.GetRasterBand(i)
- if band.GetMaskFlags() != 0:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == 0, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 1222:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 1222, 'Got wrong mask checksum'
+
###############################################################################
# Test a TIFF file with an overview, an embedded mask of 1 bit, and an embedded
# mask for the overview
-def mask_11():
+def test_mask_11():
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'FALSE')
ds = gdal.Open('data/test_with_mask_1bit_and_ovr.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
band = ds.GetRasterBand(1)
# Let's fetch the mask
- if band.GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_PER_DATASET, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 100:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
+ assert cs == 100, 'Got wrong mask checksum'
# Let's fetch the overview
band = ds.GetRasterBand(1).GetOverview(0)
cs = band.Checksum()
- if cs != 1126:
- gdaltest.post_reason('Got wrong overview checksum')
- print(cs)
- return 'fail'
+ assert cs == 1126, 'Got wrong overview checksum'
# Let's fetch the mask of the overview
- if band.GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_PER_DATASET, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 25:
- gdaltest.post_reason('Got wrong checksum for the mask of the overview')
- print(cs)
- return 'fail'
+ assert cs == 25, 'Got wrong checksum for the mask of the overview'
# Let's fetch the overview of the mask == the mask of the overview
band = ds.GetRasterBand(1).GetMaskBand().GetOverview(0)
cs = band.Checksum()
- if cs != 25:
- gdaltest.post_reason('Got wrong checksum for the overview of the mask')
- print(cs)
- return 'fail'
+ assert cs == 25, 'Got wrong checksum for the overview of the mask'
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'TRUE')
- return 'success'
-
###############################################################################
# Test a TIFF file with 3 bands, an overview, an embedded mask of 1 bit, and an embedded
# mask for the overview
-def mask_12():
+def test_mask_12():
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'FALSE')
ds = gdal.Open('data/test3_with_mask_1bit_and_ovr.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
for i in (1, 2, 3):
band = ds.GetRasterBand(i)
# Let's fetch the mask
- if band.GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_PER_DATASET, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 100:
- gdaltest.post_reason('Got wrong mask checksum')
- print(cs)
- return 'fail'
+ assert cs == 100, 'Got wrong mask checksum'
# Let's fetch the overview
band = ds.GetRasterBand(i).GetOverview(0)
cs = band.Checksum()
- if cs != 1126:
- gdaltest.post_reason('Got wrong overview checksum')
- print(cs)
- return 'fail'
+ assert cs == 1126, 'Got wrong overview checksum'
# Let's fetch the mask of the overview
- if band.GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert band.GetMaskFlags() == gdal.GMF_PER_DATASET, 'Did not get expected mask.'
cs = band.GetMaskBand().Checksum()
- if cs != 25:
- gdaltest.post_reason('Got wrong checksum for the mask of the overview')
- print(cs)
- return 'fail'
+ assert cs == 25, 'Got wrong checksum for the mask of the overview'
# Let's fetch the overview of the mask == the mask of the overview
band = ds.GetRasterBand(i).GetMaskBand().GetOverview(0)
cs = band.Checksum()
- if cs != 25:
- gdaltest.post_reason('Got wrong checksum for the overview of the mask')
- print(cs)
- return 'fail'
+ assert cs == 25, 'Got wrong checksum for the overview of the mask'
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'TRUE')
- return 'success'
-
###############################################################################
# Test creation of external TIFF mask band
-def mask_13():
+def test_mask_13():
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK', 'NO')
src_ds = gdal.Open('data/byte.tif')
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
drv = gdal.GetDriverByName('GTiff')
ds = drv.CreateCopy('tmp/byte_with_mask.tif', src_ds)
@@ -537,63 +391,46 @@ def mask_13():
ds.CreateMaskBand(gdal.GMF_PER_DATASET)
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 0:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask')
- return 'fail'
+ assert cs == 0, 'Got wrong checksum for the mask'
ds.GetRasterBand(1).GetMaskBand().Fill(1)
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 400:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask')
- return 'fail'
+ assert cs == 400, 'Got wrong checksum for the mask'
ds = None
try:
os.stat('tmp/byte_with_mask.tif.msk')
except OSError:
- gdaltest.post_reason('tmp/byte_with_mask.tif.msk is absent')
- return 'fail'
+ pytest.fail('tmp/byte_with_mask.tif.msk is absent')
ds = gdal.Open('tmp/byte_with_mask.tif')
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('wrong mask flags')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_PER_DATASET, \
+ 'wrong mask flags'
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 400:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask')
- return 'fail'
+ assert cs == 400, 'Got wrong checksum for the mask'
ds = None
drv.Delete('tmp/byte_with_mask.tif')
- try:
+ with pytest.raises(OSError, message='tmp/byte_with_mask.tif.msk is still there'):
os.stat('tmp/byte_with_mask.tif.msk')
- gdaltest.post_reason('tmp/byte_with_mask.tif.msk is still there')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Test creation of internal TIFF mask band
-def mask_14():
+def test_mask_14():
src_ds = gdal.Open('data/byte.tif')
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
drv = gdal.GetDriverByName('GTiff')
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'FALSE')
@@ -605,69 +442,48 @@ def mask_14():
with gdaltest.error_handler():
with gdaltest.config_option('GDAL_TIFF_INTERNAL_MASK', 'YES'):
ret = ds.CreateMaskBand(0)
- if ret == 0:
- gdaltest.post_reason('Error expected')
- return 'fail'
+ assert ret != 0, 'Error expected'
with gdaltest.config_option('GDAL_TIFF_INTERNAL_MASK', 'YES'):
ret = ds.CreateMaskBand(gdal.GMF_PER_DATASET)
- if ret != 0:
- gdaltest.post_reason('Creation failed')
- return 'fail'
+ assert ret == 0, 'Creation failed'
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 0:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask (1)')
- return 'fail'
+ assert cs == 0, 'Got wrong checksum for the mask (1)'
ds.GetRasterBand(1).GetMaskBand().Fill(1)
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 400:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask (2)')
- return 'fail'
+ assert cs == 400, 'Got wrong checksum for the mask (2)'
# This TIFF dataset has already an internal mask band
with gdaltest.error_handler():
with gdaltest.config_option('GDAL_TIFF_INTERNAL_MASK', 'YES'):
ret = ds.CreateMaskBand(gdal.GMF_PER_DATASET)
- if ret == 0:
- gdaltest.post_reason('Error expected')
- return 'fail'
+ assert ret != 0, 'Error expected'
# This TIFF dataset has already an internal mask band
with gdaltest.error_handler():
with gdaltest.config_option('GDAL_TIFF_INTERNAL_MASK', 'YES'):
ret = ds.GetRasterBand(1).CreateMaskBand(gdal.GMF_PER_DATASET)
- if ret == 0:
- gdaltest.post_reason('Error expected')
- return 'fail'
+ assert ret != 0, 'Error expected'
ds = None
- try:
+ with pytest.raises(OSError, message='tmp/byte_with_mask.tif.msk should not exist'):
os.stat('tmp/byte_with_mask.tif.msk')
- gdaltest.post_reason('tmp/byte_with_mask.tif.msk should not exist')
- return 'fail'
- except OSError:
- pass
+
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'FALSE')
ds = gdal.Open('tmp/byte_with_mask.tif')
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('wrong mask flags')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_PER_DATASET, \
+ 'wrong mask flags'
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'TRUE')
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 400:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask (3)')
- return 'fail'
+ assert cs == 400, 'Got wrong checksum for the mask (3)'
# Test fix for #5884
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK', 'YES')
@@ -676,14 +492,9 @@ def mask_14():
out_ds = drv.CreateCopy('/vsimem/byte_with_mask.tif', ds, options=['COMPRESS=JPEG'])
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK', None)
gdal.SetCacheMax(old_val)
- if out_ds.GetRasterBand(1).Checksum() == 0:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert out_ds.GetRasterBand(1).Checksum() != 0
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 400:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask (4)')
- return 'fail'
+ assert cs == 400, 'Got wrong checksum for the mask (4)'
out_ds = None
drv.Delete('/vsimem/byte_with_mask.tif')
@@ -691,8 +502,6 @@ def mask_14():
drv.Delete('tmp/byte_with_mask.tif')
- return 'success'
-
###############################################################################
# Test creation of internal TIFF overview, mask band and mask band of overview
@@ -701,9 +510,7 @@ def mask_and_ovr(order, method):
src_ds = gdal.Open('data/byte.tif')
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
drv = gdal.GetDriverByName('GTiff')
ds = drv.CreateCopy('tmp/byte_with_ovr_and_mask.tif', src_ds)
@@ -749,114 +556,90 @@ def mask_and_ovr(order, method):
ds = None
- try:
+ with pytest.raises(OSError, message='tmp/byte_with_mask.tif.msk should not exist'):
os.stat('tmp/byte_with_ovr_and_mask.tif.msk')
- gdaltest.post_reason('tmp/byte_with_mask.tif.msk should not exist')
- return 'fail'
- except OSError:
- pass
+
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'FALSE')
ds = gdal.Open('tmp/byte_with_ovr_and_mask.tif')
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('wrong mask flags')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_PER_DATASET, \
+ 'wrong mask flags'
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'TRUE')
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 400:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask')
- return 'fail'
+ assert cs == 400, 'Got wrong checksum for the mask'
cs = ds.GetRasterBand(1).GetOverview(0).GetMaskBand().Checksum()
- if cs != 100:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask of the first overview')
- return 'fail'
+ assert cs == 100, 'Got wrong checksum for the mask of the first overview'
cs = ds.GetRasterBand(1).GetOverview(1).GetMaskBand().Checksum()
- if cs != 25:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask of the second overview')
- return 'fail'
+ assert cs == 25, 'Got wrong checksum for the mask of the second overview'
ds = None
drv.Delete('tmp/byte_with_ovr_and_mask.tif')
- return 'success'
-
-def mask_15():
+def test_mask_15():
return mask_and_ovr(1, 'NEAREST')
-def mask_16():
+def test_mask_16():
return mask_and_ovr(2, 'NEAREST')
-def mask_17():
+def test_mask_17():
return mask_and_ovr(3, 'NEAREST')
-def mask_18():
+def test_mask_18():
return mask_and_ovr(4, 'NEAREST')
-def mask_15_avg():
+def test_mask_15_avg():
return mask_and_ovr(1, 'AVERAGE')
-def mask_16_avg():
+def test_mask_16_avg():
return mask_and_ovr(2, 'AVERAGE')
-def mask_17_avg():
+def test_mask_17_avg():
return mask_and_ovr(3, 'AVERAGE')
-def mask_18_avg():
+def test_mask_18_avg():
return mask_and_ovr(4, 'AVERAGE')
###############################################################################
# Test NODATA_VALUES mask
-def mask_19():
+def test_mask_19():
ds = gdal.Open('data/test_nodatavalues.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_PER_DATASET + gdal.GMF_NODATA:
- gdaltest.post_reason('did not get expected mask flags')
- print(ds.GetRasterBand(1).GetMaskFlags())
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_PER_DATASET + gdal.GMF_NODATA, \
+ 'did not get expected mask flags'
msk = ds.GetRasterBand(1).GetMaskBand()
cs = msk.Checksum()
expected_cs = 11043
- if cs != expected_cs:
- gdaltest.post_reason('Did not get expected checksum')
- print(cs)
- return 'fail'
+ assert cs == expected_cs, 'Did not get expected checksum'
msk = None
ds = None
- return 'success'
-
###############################################################################
# Extensive test of nodata mask for all data types
-def mask_20():
+def test_mask_20():
types = [gdal.GDT_Byte, gdal.GDT_Int16, gdal.GDT_UInt16,
gdal.GDT_Int32, gdal.GDT_UInt32, gdal.GDT_Float32, gdal.GDT_Float64,
@@ -870,26 +653,23 @@ def mask_20():
ds.GetRasterBand(1).Fill(nodatavalue[i])
ds.GetRasterBand(1).SetNoDataValue(nodatavalue[i])
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_NODATA:
- gdaltest.post_reason('did not get expected mask flags for type %s' % gdal.GetDataTypeName(typ))
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_NODATA, \
+ ('did not get expected mask flags for type %s' % gdal.GetDataTypeName(typ))
msk = ds.GetRasterBand(1).GetMaskBand()
- if msk.Checksum() != 0:
- gdaltest.post_reason('did not get expected mask checksum for type %s : %d' % gdal.GetDataTypeName(typ, msk.Checksum()))
- return 'fail'
+ assert msk.Checksum() == 0, \
+ ('did not get expected mask checksum for type %s : %d' % gdal.GetDataTypeName(typ, msk.Checksum()))
msk = None
ds = None
drv.Delete('tmp/mask20.tif')
- return 'success'
-
+
###############################################################################
# Extensive test of NODATA_VALUES mask for all data types
-def mask_21():
+def test_mask_21():
types = [gdal.GDT_Byte, gdal.GDT_Int16, gdal.GDT_UInt16,
gdal.GDT_Int32, gdal.GDT_UInt32, gdal.GDT_Float32, gdal.GDT_Float64,
@@ -907,89 +687,71 @@ def mask_21():
ds.GetRasterBand(2).Fill(nodatavalue[i])
ds.GetRasterBand(3).Fill(nodatavalue[i])
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_PER_DATASET + gdal.GMF_NODATA:
- gdaltest.post_reason('did not get expected mask flags for type %s' % gdal.GetDataTypeName(typ))
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_PER_DATASET + gdal.GMF_NODATA, \
+ ('did not get expected mask flags for type %s' % gdal.GetDataTypeName(typ))
msk = ds.GetRasterBand(1).GetMaskBand()
- if msk.Checksum() != 0:
- gdaltest.post_reason('did not get expected mask checksum for type %s : %d' % gdal.GetDataTypeName(typ, msk.Checksum()))
- return 'fail'
+ assert msk.Checksum() == 0, \
+ ('did not get expected mask checksum for type %s : %d' % gdal.GetDataTypeName(typ, msk.Checksum()))
msk = None
ds = None
drv.Delete('tmp/mask21.tif')
- return 'success'
-
+
###############################################################################
# Test creation of external TIFF mask band just after Create()
-def mask_22():
+def test_mask_22():
drv = gdal.GetDriverByName('GTiff')
ds = drv.Create('tmp/mask_22.tif', 20, 20)
ds.CreateMaskBand(gdal.GMF_PER_DATASET)
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 0:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask')
- return 'fail'
+ assert cs == 0, 'Got wrong checksum for the mask'
ds.GetRasterBand(1).GetMaskBand().Fill(1)
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 400:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask')
- return 'fail'
+ assert cs == 400, 'Got wrong checksum for the mask'
ds = None
try:
os.stat('tmp/mask_22.tif.msk')
except OSError:
- gdaltest.post_reason('tmp/mask_22.tif.msk is absent')
- return 'fail'
+ pytest.fail('tmp/mask_22.tif.msk is absent')
ds = gdal.Open('tmp/mask_22.tif')
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('wrong mask flags')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_PER_DATASET, \
+ 'wrong mask flags'
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 400:
- print(cs)
- gdaltest.post_reason('Got wrong checksum for the mask')
- return 'fail'
+ assert cs == 400, 'Got wrong checksum for the mask'
ds = None
drv.Delete('tmp/mask_22.tif')
- try:
+ with pytest.raises(OSError, message='tmp/mask_22.tif.msk is still there'):
os.stat('tmp/mask_22.tif.msk')
- gdaltest.post_reason('tmp/mask_22.tif.msk is still there')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Test CreateCopy() of a dataset with a mask into a JPEG-compressed TIFF with
# internal mask (#3800)
-def mask_23():
+def test_mask_23():
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
src_ds = drv.Create('tmp/mask_23_src.tif', 3000, 2000, 3, options=['TILED=YES', 'SPARSE_OK=YES'])
src_ds.CreateMaskBand(gdal.GMF_PER_DATASET)
@@ -1010,16 +772,13 @@ def mask_23():
drv.Delete('tmp/mask_23_dst.tif')
# 'ERROR 1: TIFFRewriteDirectory:Error fetching directory count' was triggered before
- if error_msg != '':
- return 'fail'
-
- return 'success'
+ assert error_msg == ''
###############################################################################
# Test on a GDT_UInt16 RGBA (#5692)
-def mask_24():
+def test_mask_24():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/mask_24.tif', 100, 100, 4,
gdal.GDT_UInt16, options=['PHOTOMETRIC=RGB', 'ALPHA=YES'])
@@ -1028,62 +787,43 @@ def mask_24():
ds.GetRasterBand(3).Fill(65565)
ds.GetRasterBand(4).Fill(65565)
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_ALPHA + gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_ALPHA + gdal.GMF_PER_DATASET, \
+ 'Did not get expected mask.'
mask = ds.GetRasterBand(1).GetMaskBand()
# IRasterIO() optimized case
import struct
- if struct.unpack('B', mask.ReadRaster(0, 0, 1, 1))[0] != 255:
- gdaltest.post_reason('fail')
- print(struct.unpack('B', mask.ReadRaster(0, 0, 1, 1))[0])
- return 'fail'
+ assert struct.unpack('B', mask.ReadRaster(0, 0, 1, 1))[0] == 255
# IReadBlock() code path
(blockx, blocky) = mask.GetBlockSize()
- if struct.unpack('B' * blockx * blocky, mask.ReadBlock(0, 0))[0] != 255:
- gdaltest.post_reason('fail')
- print(struct.unpack('B' * blockx * blocky, mask.ReadBlock(0, 0))[0])
- return 'fail'
+ assert struct.unpack('B' * blockx * blocky, mask.ReadBlock(0, 0))[0] == 255
mask.FlushCache()
# Test special case where dynamics is only 0-255
ds.GetRasterBand(4).Fill(255)
- if struct.unpack('B', mask.ReadRaster(0, 0, 1, 1))[0] != 1:
- gdaltest.post_reason('fail')
- print(struct.unpack('B', mask.ReadRaster(0, 0, 1, 1))[0])
- return 'fail'
+ assert struct.unpack('B', mask.ReadRaster(0, 0, 1, 1))[0] == 1
ds = None
gdal.Unlink('/vsimem/mask_24.tif')
- return 'success'
-
###############################################################################
# Test various error conditions
-def mask_25():
+def test_mask_25():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/mask_25.tif', 1, 1)
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_ALL_VALID:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_ALL_VALID
ds = None
# No INTERNAL_MASK_FLAGS_x metadata
gdal.GetDriverByName('GTiff').Create('/vsimem/mask_25.tif.msk', 1, 1)
ds = gdal.Open('/vsimem/mask_25.tif')
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_ALL_VALID:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_ALL_VALID
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 3:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 3
ds = None
gdal.Unlink('/vsimem/mask_25.tif')
gdal.Unlink('/vsimem/mask_25.tif.msk')
@@ -1093,14 +833,9 @@ def mask_25():
ds.GetRasterBand(1).CreateMaskBand(0)
ds = None
ds = gdal.Open('/vsimem/mask_25.tif')
- if ds.GetRasterBand(1).GetMaskFlags() != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == 0
cs = ds.GetRasterBand(1).GetMaskBand().Checksum()
- if cs != 0:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 0
ds = None
gdal.Unlink('/vsimem/mask_25.tif')
gdal.Unlink('/vsimem/mask_25.tif.msk')
@@ -1112,9 +847,7 @@ def mask_25():
ds = None
ds = gdal.Open('/vsimem/mask_25.tif')
with gdaltest.error_handler():
- if ds.GetRasterBand(2).GetMaskFlags() != gdal.GMF_ALL_VALID:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(2).GetMaskFlags() == gdal.GMF_ALL_VALID
ds = None
gdal.Unlink('/vsimem/mask_25.tif')
gdal.Unlink('/vsimem/mask_25.tif.msk')
@@ -1123,9 +856,7 @@ def mask_25():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/mask_25.tif', 1, 1, 2)
ds.GetRasterBand(1).CreateMaskBand(gdal.GMF_PER_DATASET)
with gdaltest.error_handler():
- if ds.GetRasterBand(2).CreateMaskBand(0) == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(2).CreateMaskBand(0) != 0
ds = None
gdal.Unlink('/vsimem/mask_25.tif')
gdal.Unlink('/vsimem/mask_25.tif.msk')
@@ -1135,37 +866,30 @@ def mask_25():
ds = gdal.GetDriverByName('MEM').Create('', 1, 1)
ds.CreateMaskBand(0)
- return 'success'
-
+
###############################################################################
# Test on a GDT_UInt16 1band data
-def mask_26():
+def test_mask_26():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/mask_26.tif', 100, 100, 2,
gdal.GDT_UInt16, options=['ALPHA=YES'])
ds.GetRasterBand(1).Fill(65565)
ds.GetRasterBand(2).Fill(65565)
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_ALPHA + gdal.GMF_PER_DATASET:
- gdaltest.post_reason('Did not get expected mask.')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_ALPHA + gdal.GMF_PER_DATASET, \
+ 'Did not get expected mask.'
mask = ds.GetRasterBand(1).GetMaskBand()
# IRasterIO() optimized case
import struct
- if struct.unpack('B', mask.ReadRaster(0, 0, 1, 1))[0] != 255:
- gdaltest.post_reason('fail')
- print(struct.unpack('B', mask.ReadRaster(0, 0, 1, 1))[0])
- return 'fail'
+ assert struct.unpack('B', mask.ReadRaster(0, 0, 1, 1))[0] == 255
ds = None
gdal.Unlink('/vsimem/mask_26.tif')
- return 'success'
-
###############################################################################
# Cleanup.
@@ -1174,7 +898,7 @@ def mask_26():
# Extensive test of nodata mask for all complex types using real part only
-def mask_27():
+def test_mask_27():
types = [gdal.GDT_CFloat32, gdal.GDT_CFloat64]
@@ -1186,61 +910,19 @@ def mask_27():
ds.GetRasterBand(1).Fill(nodatavalue[i], 10)
ds.GetRasterBand(1).SetNoDataValue(nodatavalue[i])
- if ds.GetRasterBand(1).GetMaskFlags() != gdal.GMF_NODATA:
- gdaltest.post_reason('did not get expected mask flags for type %s' % gdal.GetDataTypeName(typ))
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaskFlags() == gdal.GMF_NODATA, \
+ ('did not get expected mask flags for type %s' % gdal.GetDataTypeName(typ))
msk = ds.GetRasterBand(1).GetMaskBand()
- if msk.Checksum() != 0:
- gdaltest.post_reason('did not get expected mask checksum for type %s : %d' % gdal.GetDataTypeName(typ, msk.Checksum()))
- return 'fail'
+ assert msk.Checksum() == 0, \
+ ('did not get expected mask checksum for type %s : %d' % gdal.GetDataTypeName(typ, msk.Checksum()))
msk = None
ds = None
drv.Delete('tmp/mask27.tif')
- return 'success'
-
+
###############################################################################
# Extensive test of real NODATA_VALUES mask for all complex types
-gdaltest_list = [
- mask_1,
- mask_2,
- mask_3,
- mask_4,
- mask_5,
- mask_6,
- mask_7,
- mask_8,
- mask_9,
- mask_10,
- mask_11,
- mask_12,
- mask_13,
- mask_14,
- mask_15,
- mask_16,
- mask_17,
- mask_18,
- mask_15_avg,
- mask_16_avg,
- mask_17_avg,
- mask_18_avg,
- mask_19,
- mask_20,
- mask_21,
- mask_22,
- mask_23,
- mask_24,
- mask_25,
- mask_26,
- mask_27]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('mask')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+
diff --git a/autotest/gcore/minixml.py b/autotest/gcore/minixml.py
index d3e0880a8471..bcd68f411e6c 100755
--- a/autotest/gcore/minixml.py
+++ b/autotest/gcore/minixml.py
@@ -29,9 +29,7 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal
@@ -40,177 +38,114 @@
# Parse a simple document into a tree of lists.
-def minixml_1():
+def test_minixml_1():
tree = gdal.ParseXMLString('abc')
- if tree[0] != gdal.CXT_Element:
- gdaltest.post_reason('wrong node type.')
- return 'fail'
+ assert tree[0] == gdal.CXT_Element, 'wrong node type.'
- if tree[1] != 'TestDoc':
- gdaltest.post_reason('Wrong element name')
- return 'fail'
+ assert tree[1] == 'TestDoc', 'Wrong element name'
- if len(tree) != 5:
- gdaltest.post_reason('Wrong number of children.')
- return 'fail'
+ assert len(tree) == 5, 'Wrong number of children.'
# Check style attribute
node = tree[2]
- if node[0] != gdal.CXT_Attribute:
- gdaltest.post_reason('wrong node type.')
- return 'fail'
+ assert node[0] == gdal.CXT_Attribute, 'wrong node type.'
- if node[1] != 'style':
- gdaltest.post_reason('Wrong element name')
- return 'fail'
+ assert node[1] == 'style', 'Wrong element name'
- if len(node) != 3:
- gdaltest.post_reason('Wrong number of children.')
- return 'fail'
+ assert len(node) == 3, 'Wrong number of children.'
- if node[2][1] != '123':
- gdaltest.post_reason('Wrong element content.')
- return 'fail'
+ assert node[2][1] == '123', 'Wrong element content.'
# Check element
node = tree[3]
- if node[0] != gdal.CXT_Element:
- gdaltest.post_reason('wrong node type.')
- return 'fail'
+ assert node[0] == gdal.CXT_Element, 'wrong node type.'
- if node[1] != 'sub1':
- gdaltest.post_reason('Wrong element name')
- return 'fail'
+ assert node[1] == 'sub1', 'Wrong element name'
- if len(node) != 2:
- gdaltest.post_reason('Wrong number of children.')
- return 'fail'
+ assert len(node) == 2, 'Wrong number of children.'
# Check element
node = tree[4]
- if node[0] != gdal.CXT_Element:
- gdaltest.post_reason('wrong node type.')
- return 'fail'
+ assert node[0] == gdal.CXT_Element, 'wrong node type.'
- if node[1] != 'sub2':
- gdaltest.post_reason('Wrong element name')
- return 'fail'
+ assert node[1] == 'sub2', 'Wrong element name'
- if len(node) != 3:
- gdaltest.post_reason('Wrong number of children.')
- return 'fail'
+ assert len(node) == 3, 'Wrong number of children.'
- if node[2][1] != 'abc':
- gdaltest.post_reason('Wrong element content.')
- return 'fail'
-
- return 'success'
+ assert node[2][1] == 'abc', 'Wrong element content.'
###############################################################################
# Serialize an XML Tree
-def minixml_2():
+def test_minixml_2():
tree = [0, 'TestDoc', [2, 'style', [1, '123']], [0, 'sub1'], [0, 'sub2', [1, 'abc']]]
doc_target = '\n \n abc\n\n'
doc_got = gdal.SerializeXMLTree(tree)
- if doc_got != doc_target:
- gdaltest.post_reason('serialize xml tree failed.')
- print(doc_got)
- return 'fail'
- return 'success'
+ assert doc_got == doc_target, 'serialize xml tree failed.'
###############################################################################
# Read XML document with complex DOCTYPE element.
-def minixml_3():
+def test_minixml_3():
fp = open('data/doctype.xml', 'r')
text = fp.read()
tree = gdal.ParseXMLString(text)
- if tree[0] != gdal.CXT_Element:
- gdaltest.post_reason('wrong node type.')
- return 'fail'
+ assert tree[0] == gdal.CXT_Element, 'wrong node type.'
# Check element
node = tree[6]
- if node[0] != gdal.CXT_Element:
- gdaltest.post_reason('wrong node type.')
- return 'fail'
+ assert node[0] == gdal.CXT_Element, 'wrong node type.'
- if node[1] != 'chapter':
- gdaltest.post_reason('Wrong element name')
- return 'fail'
+ assert node[1] == 'chapter', 'Wrong element name'
- if len(node) != 7:
- gdaltest.post_reason('Wrong number of children.')
- return 'fail'
+ assert len(node) == 7, 'Wrong number of children.'
# Check subelement
subnode = node[2]
- if subnode[0] != gdal.CXT_Element:
- gdaltest.post_reason('wrong node type.')
- return 'fail'
+ assert subnode[0] == gdal.CXT_Element, 'wrong node type.'
- if subnode[1] != 'title':
- gdaltest.post_reason('Wrong element name')
- return 'fail'
+ assert subnode[1] == 'title', 'Wrong element name'
- if len(subnode) != 3:
- gdaltest.post_reason('Wrong number of children.')
- return 'fail'
+ assert len(subnode) == 3, 'Wrong number of children.'
- if subnode[2][1] != 'Chapter 1':
- gdaltest.post_reason('Wrong element content.')
- return 'fail'
+ assert subnode[2][1] == 'Chapter 1', 'Wrong element content.'
# Check fist subelement
subnode = node[3]
- if subnode[0] != gdal.CXT_Element:
- gdaltest.post_reason('wrong node type.')
- return 'fail'
-
- if subnode[1] != 'para':
- gdaltest.post_reason('Wrong element name')
- return 'fail'
+ assert subnode[0] == gdal.CXT_Element, 'wrong node type.'
- if len(subnode) != 3:
- gdaltest.post_reason('Wrong number of children.')
- return 'fail'
+ assert subnode[1] == 'para', 'Wrong element name'
- return 'success'
+ assert len(subnode) == 3, 'Wrong number of children.'
###############################################################################
# Parse and serialize an XML Tree with a prolog
-def minixml_4():
+def test_minixml_4():
xml = """\n\n"""
got_xml = gdal.SerializeXMLTree(gdal.ParseXMLString(xml))
- if xml != got_xml:
- gdaltest.post_reason('serialize xml tree failed.')
- print(got_xml)
- return 'fail'
-
- return 'success'
+ assert xml == got_xml, 'serialize xml tree failed.'
###############################################################################
# Parse malformed XML. Complains, but still makes a tree.
-def minixml_5():
+def test_minixml_5():
test_pairs = (
('', 'case'),
@@ -222,24 +157,18 @@ def minixml_5():
tree = gdal.ParseXMLString(xml_str)
found = gdal.GetLastErrorMsg()
- if expect not in found:
- gdaltest.post_reason(
- 'Did not find expected error message: "%s" '
+ assert expect in found, ('Did not find expected error message: "%s" '
'Found: "%s" '
'For test string: "%s""' % (expect, found, xml_str))
- return 'fail'
- if tree is None:
- gdaltest.post_reason('Tree is None: "%s"' % tree)
- return 'fail'
-
- return 'success'
+ assert tree is not None, ('Tree is None: "%s"' % tree)
+
###############################################################################
# Parse malformed XML.
-def minixml_6():
+def test_minixml_6():
test_pairs = (
('<', 'element token after open angle bracket'),
@@ -261,24 +190,18 @@ def minixml_6():
tree = gdal.ParseXMLString(xml_str)
found = gdal.GetLastErrorMsg()
- if expect not in found:
- gdaltest.post_reason(
- 'Did not find expected error message: "%s" '
+ assert expect in found, ('Did not find expected error message: "%s" '
'Found: "%s" '
'For test string: "%s""' % (expect, found, xml_str))
- return 'fail'
-
- if tree is not None:
- gdaltest.post_reason('Tree is not None: "%s"' % tree)
- return 'fail'
- return 'success'
+ assert tree is None, ('Tree is not None: "%s"' % tree)
+
###############################################################################
# Parse malformed XML. Pass without warning, but should not pass.
-def minixml_7():
+def test_minixml_7():
test_strings = (
'<1>1>',
@@ -292,21 +215,16 @@ def minixml_7():
tree = gdal.ParseXMLString(xml_str)
found = gdal.GetLastErrorMsg()
- if found != '':
- gdaltest.post_reason('Unexpected msg "%s"' % found)
- return 'fail'
+ assert found == '', ('Unexpected msg "%s"' % found)
- if tree is None:
- gdaltest.post_reason('Tree is None: "%s"' % tree)
- return 'fail'
-
- return 'success'
+ assert tree is not None, ('Tree is None: "%s"' % tree)
+
###############################################################################
# Parse XML with too many nesting
-def minixml_8():
+def test_minixml_8():
xml_str = '' * 10001
xml_str += '' * 10001
@@ -314,37 +232,14 @@ def minixml_8():
gdal.ErrorReset()
with gdaltest.error_handler():
tree = gdal.ParseXMLString(xml_str)
- if tree is not None:
- gdaltest.post_reason('expected None tree')
- return 'fail'
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('expected error message')
- return 'fail'
-
- return 'success'
+ assert tree is None, 'expected None tree'
+ assert gdal.GetLastErrorMsg() != '', 'expected error message'
###############################################################################
# Cleanup
-def minixml_cleanup():
- return 'success'
-
-
-gdaltest_list = [
- minixml_1,
- minixml_2,
- minixml_3,
- minixml_4,
- minixml_5,
- minixml_6,
- minixml_7,
- minixml_8,
- minixml_cleanup]
-
-if __name__ == '__main__':
+def test_minixml_cleanup():
+ pass
- gdaltest.setup_run('minixml')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/misc.py b/autotest/gcore/misc.py
index b05d58eee910..32c5d1a2ff80 100755
--- a/autotest/gcore/misc.py
+++ b/autotest/gcore/misc.py
@@ -29,52 +29,47 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
import os
import shutil
from osgeo import gdal
-sys.path.append('../pymod')
import gdaltest
+import pytest
###############################################################################
# Test that the constructor of GDALDataset() behaves well with a big number of
# opened/created datasets
-def misc_1():
+def test_misc_1():
tab_ds = [None] * 5000
drv = gdal.GetDriverByName('MEM')
for i, _ in enumerate(tab_ds):
name = 'mem_%d' % i
tab_ds[i] = drv.Create(name, 1, 1, 1)
- if tab_ds[i] is None:
- return 'fail'
- return 'success'
-
+ assert tab_ds[i] is not None
+
###############################################################################
# Test that OpenShared() works as expected by opening a big number of times
# the same dataset with it. If it did not work, that would exhaust the system
# limit of maximum file descriptors opened at the same time
-def misc_2():
+def test_misc_2():
tab_ds = [None for i in range(5000)]
for i, _ in enumerate(tab_ds):
tab_ds[i] = gdal.OpenShared('data/byte.tif')
- if tab_ds[i] is None:
- return 'fail'
-
- return 'success'
+ assert tab_ds[i] is not None
+
###############################################################################
# Test OpenShared() with a dataset whose filename != description (#2797)
-def misc_3():
+def test_misc_3():
with gdaltest.error_handler():
ds = gdal.OpenShared('../gdrivers/data/small16.aux')
@@ -92,13 +87,11 @@ def misc_3():
ds = None
ds2 = None
- return 'success'
-
###############################################################################
# Test Create() with invalid arguments
-def misc_4():
+def test_misc_4():
gdal.PushErrorHandler('CPLQuietErrorHandler')
@@ -111,8 +104,6 @@ def misc_4():
gdal.PopErrorHandler()
- return 'success'
-
###############################################################################
def get_filename(drv, dirname):
@@ -196,7 +187,7 @@ def misc_5_internal(drv, datatype, nBands):
return 1
-def misc_5():
+def test_misc_5():
gdal.PushErrorHandler('CPLQuietErrorHandler')
@@ -212,8 +203,7 @@ def misc_5():
os.stat('tmp/tmp')
# Hum the directory already exists... Not expected, but let's try to go on
except OSError:
- gdaltest.post_reason('Cannot create tmp/tmp')
- return 'fail'
+ pytest.fail('Cannot create tmp/tmp')
# This is to speed-up the runtime of tests on EXT4 filesystems
# Do not use this for production environment if you care about data safety
@@ -302,8 +292,7 @@ def misc_6_internal(datatype, nBands, setDriversDone):
# Hum the directory already exists... Not expected, but let's try to go on
except OSError:
reason = 'Cannot create %s before drv = %s, nBands = %d, datatype = %s' % (dirname, drv.ShortName, nBands, gdal.GetDataTypeName(datatype))
- gdaltest.post_reason(reason)
- return 'fail'
+ pytest.fail(reason)
filename = get_filename(drv, dirname)
@@ -320,8 +309,7 @@ def misc_6_internal(datatype, nBands, setDriversDone):
shutil.rmtree(dirname)
except OSError:
reason = 'Cannot remove %s after drv = %s, nBands = %d, datatype = %s' % (dirname, drv.ShortName, nBands, gdal.GetDataTypeName(datatype))
- gdaltest.post_reason(reason)
- return 'fail'
+ pytest.fail(reason)
if has_succeeded and drv.ShortName not in setDriversDone and nBands > 0:
setDriversDone.add(drv.ShortName)
@@ -361,7 +349,6 @@ def misc_6_internal(datatype, nBands, setDriversDone):
if drv.ShortName not in ['ECW', 'JP2ECW', 'VRT', 'XPM', 'JPEG2000', 'FIT', 'RST', 'INGR', 'USGSDEM', 'KMLSUPEROVERLAY', 'GMT']:
dst_ds = drv.CreateCopy(filename, ds, callback=misc_6_interrupt_callback_class().cbk)
if dst_ds is not None:
- gdaltest.post_reason('interruption did not work with drv = %s, nBands = %d, datatype = %s' % (drv.ShortName, nBands, gdal.GetDataTypeName(datatype)))
dst_ds = None
try:
@@ -369,7 +356,7 @@ def misc_6_internal(datatype, nBands, setDriversDone):
except OSError:
pass
- return 'fail'
+ pytest.fail('interruption did not work with drv = %s, nBands = %d, datatype = %s' % (drv.ShortName, nBands, gdal.GetDataTypeName(datatype)))
dst_ds = None
@@ -381,14 +368,11 @@ def misc_6_internal(datatype, nBands, setDriversDone):
os.mkdir(dirname)
except OSError:
reason = 'Cannot create %s before drv = %s, nBands = %d, datatype = %s' % (dirname, drv.ShortName, nBands, gdal.GetDataTypeName(datatype))
- gdaltest.post_reason(reason)
- return 'fail'
+ pytest.fail(reason)
ds = None
- return 'success'
-
-def misc_6():
+def test_misc_6():
gdal.PushErrorHandler('CPLQuietErrorHandler')
@@ -404,8 +388,7 @@ def misc_6():
os.stat('tmp/tmp')
# Hum the directory already exists... Not expected, but let's try to go on
except OSError:
- gdaltest.post_reason('Cannot create tmp/tmp')
- return 'fail'
+ pytest.fail('Cannot create tmp/tmp')
# This is to speed-up the runtime of tests on EXT4 filesystems
# Do not use this for production environment if you care about data safety
@@ -438,70 +421,57 @@ def misc_6():
gdal.PopErrorHandler()
- return 'success'
-
###############################################################################
# Test gdal.InvGeoTransform()
-def misc_7():
+def test_misc_7():
try:
gdal.InvGeoTransform
except AttributeError:
- return 'skip'
+ pytest.skip()
gt = (10, 0.1, 0, 20, 0, -1.0)
res = gdal.InvGeoTransform(gt)
expected_inv_gt = (-100.0, 10.0, 0.0, 20.0, 0.0, -1.0)
for i in range(6):
- if abs(res[i] - expected_inv_gt[i]) > 1e-6:
- print(res)
- return 'fail'
-
- return 'success'
+ assert abs(res[i] - expected_inv_gt[i]) <= 1e-6
+
###############################################################################
# Test gdal.ApplyGeoTransform()
-def misc_8():
+def test_misc_8():
try:
gdal.ApplyGeoTransform
except AttributeError:
- return 'skip'
+ pytest.skip()
gt = (10, 0.1, 0, 20, 0, -1.0)
res = gdal.ApplyGeoTransform(gt, 10, 1)
- if res != [11.0, 19.0]:
- return 'fail'
-
- return 'success'
+ assert res == [11.0, 19.0]
###############################################################################
# Test setting and retrieving > 2 GB values for GDAL max cache (#3689)
-def misc_9():
+def test_misc_9():
old_val = gdal.GetCacheMax()
gdal.SetCacheMax(3000000000)
ret_val = gdal.GetCacheMax()
gdal.SetCacheMax(old_val)
- if ret_val != 3000000000:
- gdaltest.post_reason('did not get expected value')
- print(ret_val)
- return 'fail'
-
- return 'success'
+ assert ret_val == 3000000000, 'did not get expected value'
###############################################################################
# Test VSIBufferedReaderHandle (fix done in r21358)
-def misc_10():
+def test_misc_10():
try:
os.remove('data/byte.tif.gz.properties')
@@ -517,25 +487,23 @@ def misc_10():
import struct
ar = struct.unpack('B' * 4, data)
- if ar != (73, 73, 42, 0):
- return 'fail'
+ assert ar == (73, 73, 42, 0)
try:
os.remove('data/byte.tif.gz.properties')
except OSError:
pass
- return 'success'
-
+
###############################################################################
# Test that we can open a symlink whose pointed filename isn't a real
# file, but a filename that GDAL recognizes
-def misc_11():
+def test_misc_11():
if not gdaltest.support_symlink():
- return 'skip'
+ pytest.skip()
gdal.Unlink('tmp/symlink.tif')
os.symlink('GTIFF_DIR:1:data/byte.tif', 'tmp/symlink.tif')
@@ -543,28 +511,22 @@ def misc_11():
ds = gdal.Open('tmp/symlink.tif')
if ds is None:
os.remove('tmp/symlink.tif')
- return 'fail'
+ pytest.fail()
desc = ds.GetDescription()
ds = None
os.remove('tmp/symlink.tif')
- if desc != 'GTIFF_DIR:1:data/byte.tif':
- gdaltest.post_reason('did not get expected description')
- print(desc)
- return 'fail'
-
- return 'success'
+ assert desc == 'GTIFF_DIR:1:data/byte.tif', 'did not get expected description'
###############################################################################
# Test CreateCopy() with a target filename in a non-existing dir
-def misc_12():
+def test_misc_12():
if int(gdal.VersionInfo('VERSION_NUM')) < 1900:
- gdaltest.post_reason('would crash')
- return 'skip'
+ pytest.skip('would crash')
import test_cli_utilities
gdal_translate_path = test_cli_utilities.get_gdal_translate_path()
@@ -598,10 +560,8 @@ def misc_12():
ds = drv.CreateCopy('/nonexistingpath' + get_filename(drv, ''), src_ds)
gdal.PopErrorHandler()
if ds is None and gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('failure')
- print('CreateCopy() into non existing dir fails without error message for driver %s' % drv.ShortName)
gdal.Unlink('/vsimem/misc_12_src.tif')
- return 'fail'
+ pytest.fail('CreateCopy() into non existing dir fails without error message for driver %s' % drv.ShortName)
ds = None
if gdal_translate_path is not None:
@@ -624,38 +584,31 @@ def misc_12():
gdal.Unlink('/vsimem/misc_12_src.tif')
- return 'success'
-
+
###############################################################################
# Test CreateCopy() with incompatible driver types (#5912)
-def misc_13():
+def test_misc_13():
# Raster-only -> vector-only
ds = gdal.Open('data/byte.tif')
gdal.PushErrorHandler()
out_ds = gdal.GetDriverByName('ESRI Shapefile').CreateCopy('/vsimem/out.shp', ds)
gdal.PopErrorHandler()
- if out_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert out_ds is None
# Raster-only -> vector-only
ds = gdal.OpenEx('../ogr/data/poly.shp', gdal.OF_VECTOR)
gdal.PushErrorHandler()
out_ds = gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/out.tif', ds)
gdal.PopErrorHandler()
- if out_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert out_ds is None
###############################################################################
# Test ConfigureLogging()
-def misc_14():
+def test_misc_14():
import collections
import logging
@@ -678,9 +631,7 @@ def emit(self, record):
try:
gdal.ConfigurePythonLogging(logger_name='gdal_logging_test', enable_debug=True)
- if gdal.GetConfigOption("CPL_DEBUG") != "ON":
- gdaltest.post_reason("should have enabled debug")
- return 'fail'
+ assert gdal.GetConfigOption("CPL_DEBUG") == "ON", "should have enabled debug"
gdal.Debug("test1", "debug1")
gdal.Error(gdal.CE_Debug, gdal.CPLE_FileIO, "debug2")
@@ -695,10 +646,7 @@ def emit(self, record):
'ERROR': ["99999: error1"],
}
- if handler.messages != expected:
- print(handler.messages)
- gdaltest.post_reason("missing log messages")
- return 'fail'
+ assert handler.messages == expected, "missing log messages"
gdal.SetErrorHandler('CPLDefaultErrorHandler')
handler.messages.clear()
@@ -706,31 +654,27 @@ def emit(self, record):
gdal.ConfigurePythonLogging(logger_name='gdal_logging_test')
- if gdal.GetConfigOption("CPL_DEBUG") != "OFF":
- gdaltest.post_reason("shouldn't have enabled debug")
- return 'fail'
+ assert gdal.GetConfigOption("CPL_DEBUG") == "OFF", \
+ "shouldn't have enabled debug"
# these get suppressed by CPL_DEBUG
gdal.Debug("test1", "debug3")
# these don't
gdal.Error(gdal.CE_Debug, gdal.CPLE_None, "debug4")
- if handler.messages['DEBUG'] != ['debug4']:
- gdaltest.post_reason("unexpected log messages")
- return 'fail'
+ assert handler.messages['DEBUG'] == ['debug4'], "unexpected log messages"
finally:
gdal.SetErrorHandler('CPLDefaultErrorHandler')
gdal.SetConfigOption('CPL_DEBUG', prev_debug)
logger.removeHandler(handler)
- return 'success'
-
+
###############################################################################
# Test SetErrorHandler
-def misc_15():
+def test_misc_15():
messages0 = []
def handle0(ecls, ecode, emsg):
messages0.append((ecls, ecode, emsg))
@@ -757,9 +701,7 @@ def handle1(ecls, ecode, emsg):
(gdal.CE_Warning, gdal.CPLE_AssertionFailed, "warning1"),
(gdal.CE_Failure, 99999, "error1"),
]
- if expected0 != messages0:
- gdaltest.post_reason("SetErrorHandler: mismatched log messages")
- return 'fail'
+ assert expected0 == messages0, "SetErrorHandler: mismatched log messages"
messages0[:] = []
# Check Push
@@ -770,12 +712,8 @@ def handle1(ecls, ecode, emsg):
gdal.Error(gdal.CE_Warning, gdal.CPLE_AssertionFailed, "warning1")
gdal.Error(gdal.CE_Failure, 99999, "error1")
- if len(messages0) != 0:
- gdaltest.post_reason("PushErrorHandler: unexpected log messages")
- return 'fail'
- if len(messages1) != 4:
- gdaltest.post_reason("PushErrorHandler: missing log messages")
- return 'fail'
+ assert len(messages0) == 0, "PushErrorHandler: unexpected log messages"
+ assert len(messages1) == 4, "PushErrorHandler: missing log messages"
# and pop restores original behaviour
gdal.PopErrorHandler()
@@ -785,55 +723,20 @@ def handle1(ecls, ecode, emsg):
gdal.Error(gdal.CE_Warning, gdal.CPLE_AssertionFailed, "warning1")
gdal.Error(gdal.CE_Failure, 99999, "error1")
- if len(messages0) != 4:
- gdaltest.post_reason("PopErrorHandler: missing log messages")
- return 'fail'
- if len(messages1) != 0:
- gdaltest.post_reason("PopErrorHandler: unexpected log messages")
- return 'fail'
+ assert len(messages0) == 4, "PopErrorHandler: missing log messages"
+ assert len(messages1) == 0, "PopErrorHandler: unexpected log messages"
finally:
gdal.SetErrorHandler('CPLDefaultErrorHandler')
gdal.SetConfigOption('CPL_DEBUG', prev_debug)
- return 'success'
-
+
###############################################################################
-def misc_cleanup():
+def test_misc_cleanup():
try:
shutil.rmtree('tmp/tmp')
except OSError:
pass
-
- return 'success'
-
-
-gdaltest_list = [misc_1,
- misc_2,
- misc_3,
- misc_4,
- misc_5,
- misc_6,
- misc_7,
- misc_8,
- misc_9,
- misc_10,
- misc_11,
- misc_12,
- misc_13,
- misc_14,
- misc_15,
- misc_cleanup]
-
-# gdaltest_list = [ misc_6 ]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('misc')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/nodatamaskband.py b/autotest/gcore/nodatamaskband.py
index 6a26923eccb4..7436a5c582ea 100755
--- a/autotest/gcore/nodatamaskband.py
+++ b/autotest/gcore/nodatamaskband.py
@@ -30,15 +30,11 @@
###############################################################################
import struct
-import sys
-sys.path.append('../pymod')
-
-import gdaltest
from osgeo import gdal
-def nodatamaskband_1():
+def test_nodatamaskband_1():
for (dt, struct_type, v) in [(gdal.GDT_Byte, 'B', 255),
(gdal.GDT_Int16, 'h', 32767),
@@ -65,63 +61,28 @@ def nodatamaskband_1():
0, 255, 255, 0, 0, 255,
0, 255, 255, 0, 0, 255,
255, 0, 0, 255, 255, 255)
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(dt)
- print(data_ar)
- return 'fail'
+ assert data_ar == expected_ar, dt
data = ds.GetRasterBand(1).GetMaskBand().ReadBlock(0, 0)
data_ar = struct.unpack('B' * 6 * 1, data)
expected_ar = (0, 255, 255, 0, 0, 255)
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(dt)
- print(data_ar)
- return 'fail'
+ assert data_ar == expected_ar, dt
data = ds.GetRasterBand(1).GetMaskBand().ReadBlock(0, 3)
data_ar = struct.unpack('B' * 6 * 1, data)
expected_ar = (255, 0, 0, 255, 255, 255)
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(dt)
- print(data_ar)
- return 'fail'
+ assert data_ar == expected_ar, dt
data = ds.GetRasterBand(1).GetMaskBand().ReadRaster(
buf_xsize=3, buf_ysize=2)
data_ar = struct.unpack('B' * 3 * 2, data)
expected_ar = (255, 0, 255,
0, 255, 255)
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(dt)
- print(data_ar)
- return 'fail'
+ assert data_ar == expected_ar, dt
data = ds.GetRasterBand(1).GetMaskBand().ReadRaster(
buf_type=gdal.GDT_UInt16, buf_xsize=3, buf_ysize=2)
data_ar = struct.unpack('H' * 3 * 2, data)
expected_ar = (255, 0, 255,
0, 255, 255)
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(dt)
- print(data_ar)
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = [
- nodatamaskband_1,
-]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('nodatamaskband')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ assert data_ar == expected_ar, dt
diff --git a/autotest/gcore/numpy_rw.py b/autotest/gcore/numpy_rw.py
index 21e7dddb018d..342560f7c8c7 100755
--- a/autotest/gcore/numpy_rw.py
+++ b/autotest/gcore/numpy_rw.py
@@ -29,159 +29,120 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# verify that we can load Numeric python, and find the Numpy driver.
-def numpy_rw_1():
+def test_numpy_rw_1():
gdaltest.numpy_drv = None
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
except (ImportError, AttributeError):
- return 'skip'
+ pytest.skip()
gdal.AllRegister()
gdaltest.numpy_drv = gdal.GetDriverByName('NUMPY')
- if gdaltest.numpy_drv is None:
- gdaltest.post_reason('NUMPY driver not found!')
- return 'fail'
-
- return 'success'
+ assert gdaltest.numpy_drv is not None, 'NUMPY driver not found!'
###############################################################################
# Load a test file into a memory Numpy array, and verify the checksum.
-def numpy_rw_2():
+def test_numpy_rw_2():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
from osgeo import gdalnumeric
array = gdalnumeric.LoadFile('data/utmsmall.tif')
- if array is None:
- gdaltest.post_reason('Failed to load utmsmall.tif into array')
- return 'fail'
+ assert array is not None, 'Failed to load utmsmall.tif into array'
ds = gdalnumeric.OpenArray(array)
- if ds is None:
- gdaltest.post_reason('Failed to open memory array as dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open memory array as dataset.'
bnd = ds.GetRasterBand(1)
- if bnd.Checksum() != 50054:
- gdaltest.post_reason('Didnt get expected checksum on reopened file')
- return 'fail'
+ assert bnd.Checksum() == 50054, 'Didnt get expected checksum on reopened file'
ds = None
- return 'success'
-
###############################################################################
# Test loading complex data.
-def numpy_rw_3():
+def test_numpy_rw_3():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/cint_sar.tif')
array = ds.ReadAsArray()
- if array[2][3] != 116 - 16j:
- print(array[0][2][3])
- gdaltest.post_reason('complex value read improperly.')
- return 'fail'
-
- return 'success'
+ assert array[2][3] == 116 - 16j, 'complex value read improperly.'
###############################################################################
# Test a band read with downsampling.
-def numpy_rw_4():
+def test_numpy_rw_4():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/byte.tif')
array = ds.GetRasterBand(1).ReadAsArray(0, 0, 20, 20, 5, 5)
- if array[2][3] != 123:
- print(array[2][3])
- gdaltest.post_reason('Read wrong value - perhaps downsampling algorithm has changed subtly?')
- return 'fail'
-
- return 'success'
+ assert array[2][3] == 123, \
+ 'Read wrong value - perhaps downsampling algorithm has changed subtly?'
###############################################################################
# Test reading a multi-band file.
-def numpy_rw_5():
+def test_numpy_rw_5():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
from osgeo import gdalnumeric
array = gdalnumeric.LoadFile('data/rgbsmall.tif', 35, 21, 1, 1)
- if array[0][0][0] != 78:
- print(array)
- gdaltest.post_reason('value read improperly.')
- return 'fail'
+ assert array[0][0][0] == 78, 'value read improperly.'
- if array[1][0][0] != 117:
- print(array)
- gdaltest.post_reason('value read improperly.')
- return 'fail'
+ assert array[1][0][0] == 117, 'value read improperly.'
- if array[2][0][0] != 24:
- print(array)
- gdaltest.post_reason('value read improperly.')
- return 'fail'
+ assert array[2][0][0] == 24, 'value read improperly.'
array = gdalnumeric.LoadFile('data/rgbsmall.tif', buf_xsize=1, buf_ysize=1, resample_alg=gdal.GRIORA_Bilinear)
- if array.shape[0] != 3 or array.shape[1] != 1 or array.shape[2] != 1:
- print(array.shape)
- gdaltest.post_reason('wrong array shape.')
- return 'fail'
- if array[0][0][0] != 70 or array[1][0][0] != 97 or array[2][0][0] != 29:
- print(array)
- gdaltest.post_reason('value read improperly.')
- return 'fail'
+ assert array.shape[0] == 3 and array.shape[1] == 1 and array.shape[2] == 1, \
+ 'wrong array shape.'
+ assert array[0][0][0] == 70 and array[1][0][0] == 97 and array[2][0][0] == 29, \
+ 'value read improperly.'
import numpy
array = numpy.zeros([3, 1, 1], dtype=numpy.uint8)
ds = gdal.Open('data/rgbsmall.tif')
ds.ReadAsArray(buf_obj=array, resample_alg=gdal.GRIORA_Bilinear)
- if array[0][0][0] != 70 or array[1][0][0] != 97 or array[2][0][0] != 29:
- print(array)
- gdaltest.post_reason('value read improperly.')
- return 'fail'
-
- return 'success'
+ assert array[0][0][0] == 70 and array[1][0][0] == 97 and array[2][0][0] == 29, \
+ 'value read improperly.'
###############################################################################
# Check that Band.ReadAsArray() can accept an already allocated array (#2658, #3028)
-def numpy_rw_6():
+def test_numpy_rw_6():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
from osgeo import gdalnumeric
@@ -190,23 +151,19 @@ def numpy_rw_6():
array = numpy.zeros([ds.RasterYSize, ds.RasterXSize], numpy.uint8)
array_res = ds.GetRasterBand(1).ReadAsArray(buf_obj=array)
- if array is not array_res:
- return 'fail'
+ assert array is array_res
ds2 = gdalnumeric.OpenArray(array)
- if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum():
- return 'fail'
-
- return 'success'
+ assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum()
###############################################################################
# Check that Dataset.ReadAsArray() can accept an already allocated array (#2658, #3028)
-def numpy_rw_7():
+def test_numpy_rw_7():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
from osgeo import gdalnumeric
@@ -215,46 +172,38 @@ def numpy_rw_7():
array = numpy.zeros([1, ds.RasterYSize, ds.RasterXSize], numpy.uint8)
array_res = ds.ReadAsArray(buf_obj=array)
- if array is not array_res:
- return 'fail'
+ assert array is array_res
ds2 = gdalnumeric.OpenArray(array)
- if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum():
- return 'fail'
+ assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum()
# Try again with a 2D array
array = numpy.zeros([ds.RasterYSize, ds.RasterXSize], numpy.uint8)
array_res = ds.ReadAsArray(buf_obj=array)
- if array is not array_res:
- return 'fail'
+ assert array is array_res
ds2 = gdalnumeric.OpenArray(array)
- if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum():
- return 'fail'
+ assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum()
# With a multi band file
ds = gdal.Open('data/rgbsmall.tif')
array = numpy.zeros([ds.RasterCount, ds.RasterYSize, ds.RasterXSize], numpy.uint8)
array_res = ds.ReadAsArray(buf_obj=array)
- if array is not array_res:
- return 'fail'
+ assert array is array_res
ds2 = gdalnumeric.OpenArray(array)
- if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum():
- return 'fail'
-
- return 'success'
+ assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum()
###############################################################################
# Check that Dataset.ReadAsArray() with multi-band data
-def numpy_rw_8():
+def test_numpy_rw_8():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
from osgeo import gdalnumeric
@@ -265,19 +214,17 @@ def numpy_rw_8():
ds2 = gdalnumeric.OpenArray(array)
for i in range(1, ds.RasterCount):
- if ds2.GetRasterBand(i).Checksum() != ds.GetRasterBand(i).Checksum():
- return 'fail'
-
- return 'success'
+ assert ds2.GetRasterBand(i).Checksum() == ds.GetRasterBand(i).Checksum()
+
###############################################################################
# Test Band.WriteArray()
-def numpy_rw_9():
+def test_numpy_rw_9():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/byte.tif')
array = ds.ReadAsArray()
@@ -288,21 +235,16 @@ def numpy_rw_9():
out_ds = None
ds = None
- if cs != 4672:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4672, 'did not get expected checksum'
###############################################################################
# Test signed byte handling
-def numpy_rw_10():
+def test_numpy_rw_10():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
@@ -321,26 +263,18 @@ def numpy_rw_10():
gdal.Unlink('/vsimem/signed8.tif')
- if ar2[0][0] != -128 or ar2[0][1] != 127:
- gdaltest.post_reason('did not get expected result (1)')
- print(ar2)
- return 'fail'
+ assert ar2[0][0] == -128 and ar2[0][1] == 127, 'did not get expected result (1)'
- if ar3[0][0] != -128 or ar3[0][1] != 127:
- gdaltest.post_reason('did not get expected result (2)')
- print(ar3)
- return 'fail'
-
- return 'success'
+ assert ar3[0][0] == -128 and ar3[0][1] == 127, 'did not get expected result (2)'
###############################################################################
# Test all datatypes
-def numpy_rw_11():
+def test_numpy_rw_11():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
from osgeo import gdal_array
@@ -360,10 +294,7 @@ def numpy_rw_11():
for type_tuple in type_tuples:
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/' + type_tuple[0], 1, 1, 1, type_tuple[1])
tmp = ds.ReadAsArray()
- if tmp.dtype != type_tuple[2]:
- gdaltest.post_reason('did not get expected numpy type')
- print(type_tuple)
- return 'fail'
+ assert tmp.dtype == type_tuple[2], 'did not get expected numpy type'
ar = numpy.empty([1, 1], dtype=type_tuple[2])
@@ -374,11 +305,8 @@ def numpy_rw_11():
if expected_dt == gdal.GDT_CInt16 or expected_dt == gdal.GDT_CInt32:
expected_dt = gdal.GDT_CFloat32
if got_dt != expected_dt:
- gdaltest.post_reason('did not get expected result (0)')
print(type_tuple[1])
- print(got_dt)
- print(expected_dt)
- return 'fail'
+ pytest.fail('did not get expected result (0)')
ar[0][0] = type_tuple[3]
ds.GetRasterBand(1).WriteArray(ar)
@@ -392,30 +320,23 @@ def numpy_rw_11():
gdal.Unlink('/vsimem/' + type_tuple[0])
- if (type_tuple[0] == 'float32' and abs(ar2[0][0] - type_tuple[3]) > 1e-6) or \
- (type_tuple[0] != 'float32' and ar2[0][0] != type_tuple[3]):
- gdaltest.post_reason('did not get expected result (1)')
- print(ar2)
- print(type_tuple)
- return 'fail'
-
- if (type_tuple[0] == 'float32' and abs(ar3[0][0] - type_tuple[3]) > 1e-6) or \
- (type_tuple[0] != 'float32' and ar3[0][0] != type_tuple[3]):
- gdaltest.post_reason('did not get expected result (2)')
- print(ar3)
- print(type_tuple)
- return 'fail'
+ assert (not (type_tuple[0] == 'float32' and abs(ar2[0][0] - type_tuple[3]) > 1e-6) or \
+ (type_tuple[0] != 'float32' and ar2[0][0] != type_tuple[3])), \
+ 'did not get expected result (1)'
- return 'success'
+ assert (not (type_tuple[0] == 'float32' and abs(ar3[0][0] - type_tuple[3]) > 1e-6) or \
+ (type_tuple[0] != 'float32' and ar3[0][0] != type_tuple[3])), \
+ 'did not get expected result (2)'
+
###############################################################################
# Test array with slices (#3542)
-def numpy_rw_12():
+def test_numpy_rw_12():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
@@ -435,20 +356,16 @@ def numpy_rw_12():
ds.GetRasterBand(1).ReadAsArray(buf_obj=slice_read)
ds = None
- if slice_read[0][0] != 1 or slice_read[1][0] != 3:
- print(slice_read)
- return 'fail'
-
- return 'success'
+ assert slice_read[0][0] == 1 and slice_read[1][0] == 3
###############################################################################
# Test expected errors
-def numpy_rw_13():
+def test_numpy_rw_13():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
@@ -461,88 +378,61 @@ def numpy_rw_13():
# Try reading into unsupported array type
ar = numpy.empty([1, 2], dtype=numpy.int64)
- try:
+ with pytest.raises(Exception, message='expected "ValueError: array does not have '
+ 'corresponding GDAL data type"'):
ds.GetRasterBand(1).ReadAsArray(buf_obj=ar)
- gdaltest.post_reason('expected "ValueError: array does not have '
- 'corresponding GDAL data type"')
- return 'fail'
- except:
- pass
+
# Try call with inconsistent parameters.
ar = numpy.empty([1, 2], dtype=numpy.uint8)
- try:
+ with pytest.raises(Exception, message='expected "Specified buf_ysize not consistent '
+ 'with buffer shape"'):
ds.GetRasterBand(1).ReadAsArray(buf_obj=ar, buf_xsize=2,
buf_ysize=2)
- gdaltest.post_reason('expected "Specified buf_ysize not consistent '
- 'with buffer shape"')
- return 'fail'
- except:
- pass
+
# Same with 3 dimensions
ar = numpy.empty([1, 1, 2], dtype=numpy.uint8)
- try:
+ with pytest.raises(Exception, message='expected "Specified buf_ysize not consistent '
+ 'with buffer shape"'):
ds.GetRasterBand(1).ReadAsArray(buf_obj=ar, buf_xsize=2,
buf_ysize=2)
- gdaltest.post_reason('expected "Specified buf_ysize not consistent '
- 'with buffer shape"')
- return 'fail'
- except:
- pass
+
# Try call with inconsistent parameters.
ar = numpy.empty([1, 2], dtype=numpy.uint8)
- try:
+ with pytest.raises(Exception, message='expected "Specified buf_xsize not consistent '
+ 'with buffer shape"'):
ds.GetRasterBand(1).ReadAsArray(buf_obj=ar, buf_xsize=1,
buf_ysize=1)
- gdaltest.post_reason('expected "Specified buf_xsize not consistent '
- 'with buffer shape"')
- return 'fail'
- except:
- pass
+
# Inconsistent data type
ar = numpy.empty([1, 2], dtype=numpy.uint8)
- try:
+ with pytest.raises(Exception, message='expected "Specified buf_type not consistent '
+ 'with array type"'):
ds.GetRasterBand(1).ReadAsArray(buf_obj=ar,
buf_type=gdal.GDT_Int16)
- gdaltest.post_reason('expected "Specified buf_type not consistent '
- 'with array type"')
- return 'fail'
- except:
- pass
+
# This one should be OK !
ar = numpy.zeros([1, 2], dtype=numpy.uint8)
ds.GetRasterBand(1).ReadAsArray(buf_obj=ar, buf_xsize=2, buf_ysize=1)
- if ar[0][0] != 100 or ar[0][1] != 200:
- gdaltest.post_reason('did not get expected values')
- print(ar)
- return 'fail'
+ assert ar[0][0] == 100 and ar[0][1] == 200, 'did not get expected values'
# This one too
ar = numpy.zeros([1, 1, 2], dtype=numpy.uint8)
ds.GetRasterBand(1).ReadAsArray(buf_obj=ar)
- if ar[0][0][0] != 100 or ar[0][0][1] != 200:
- gdaltest.post_reason('did not get expected values')
- print(ar)
- return 'fail'
+ assert ar[0][0][0] == 100 and ar[0][0][1] == 200, 'did not get expected values'
# This one too
ar = numpy.zeros([1, 1, 2], dtype=numpy.uint8)
ds.ReadAsArray(buf_obj=ar)
- if ar[0][0][0] != 100 or ar[0][0][1] != 200:
- gdaltest.post_reason('did not get expected values')
- print(ar)
- return 'fail'
+ assert ar[0][0][0] == 100 and ar[0][0][1] == 200, 'did not get expected values'
# This one too
ar = ds.ReadAsArray()
- if ar[0][0] != 100 or ar[0][1] != 200:
- gdaltest.post_reason('did not get expected values')
- print(ar)
- return 'fail'
+ assert ar[0][0] == 100 and ar[0][1] == 200, 'did not get expected values'
ds = None
@@ -560,89 +450,63 @@ def numpy_rw_13():
ds.GetRasterBand(i + 1).WriteArray(ar[i])
ar = numpy.empty([3, 1, 2], dtype=numpy.int64)
- try:
+ with pytest.raises(Exception, message='expected "ValueError: array does not have '
+ 'corresponding GDAL data type"'):
ds.ReadAsArray(buf_obj=ar)
- gdaltest.post_reason('expected "ValueError: array does not have '
- 'corresponding GDAL data type"')
- return 'fail'
- except:
- pass
+
# Try call with inconsistent parameters.
ar = numpy.empty([3, 1, 2], dtype=numpy.uint8)
- try:
+ with pytest.raises(Exception, message='expected "Specified buf_ysize not consistent '
+ 'with buffer shape"'):
ds.ReadAsArray(buf_obj=ar, buf_xsize=2, buf_ysize=2)
- gdaltest.post_reason('expected "Specified buf_ysize not consistent '
- 'with buffer shape"')
- return 'fail'
- except:
- pass
+
# With 2 dimensions
ar = numpy.empty([1, 2], dtype=numpy.uint8)
- try:
+ with pytest.raises(Exception, message='expected "ValueError: Array should have 3 '
+ 'dimensions"'):
ds.ReadAsArray(buf_obj=ar)
- gdaltest.post_reason('expected "ValueError: Array should have 3 '
- 'dimensions"')
- return 'fail'
- except:
- pass
+
# Try call with inconsistent parameters
ar = numpy.empty([3, 1, 2], dtype=numpy.uint8)
- try:
+ with pytest.raises(Exception, message='expected "Specified buf_xsize not consistent '
+ 'with buffer shape"'):
ds.ReadAsArray(buf_obj=ar, buf_xsize=1, buf_ysize=1)
- gdaltest.post_reason('expected "Specified buf_xsize not consistent '
- 'with buffer shape"')
- return 'fail'
- except:
- pass
+
# Inconsistent data type
ar = numpy.empty([3, 1, 2], dtype=numpy.uint8)
- try:
+ with pytest.raises(Exception, message='expected "Specified buf_type not consistent with array type"'):
ds.ReadAsArray(buf_obj=ar, buf_type=gdal.GDT_Int16)
- gdaltest.post_reason('expected "Specified buf_type not consistent with array type"')
- return 'fail'
- except:
- pass
+
# Not enough space in first dimension
ar = numpy.empty([2, 1, 2], dtype=numpy.uint8)
- try:
+ with pytest.raises(Exception, message='expected "Array should have space for 3 bands"'):
ds.ReadAsArray(buf_obj=ar)
- gdaltest.post_reason('expected "Array should have space for 3 bands"')
- return 'fail'
- except:
- pass
+
# This one should be OK !
ar = numpy.zeros([3, 1, 2], dtype=numpy.uint8)
ds.ReadAsArray(buf_obj=ar, buf_xsize=2, buf_ysize=1, buf_type=gdal.GDT_Byte)
- if ar[0][0][0] != 100 or ar[0][0][1] != 200 or ar[1][0][0] != 101 or ar[1][0][1] != 201 or ar[2][0][0] != 102 or ar[2][0][1] != 202:
- gdaltest.post_reason('did not get expected values')
- print(ar)
- return 'fail'
+ assert ar[0][0][0] == 100 and ar[0][0][1] == 200 and ar[1][0][0] == 101 and ar[1][0][1] == 201 and ar[2][0][0] == 102 and ar[2][0][1] == 202, \
+ 'did not get expected values'
# This one too
ar = numpy.zeros([3, 1, 2], dtype=numpy.uint8)
ds.ReadAsArray(buf_obj=ar)
- if ar[0][0][0] != 100 or ar[0][0][1] != 200 or ar[1][0][0] != 101 or ar[1][0][1] != 201 or ar[2][0][0] != 102 or ar[2][0][1] != 202:
- gdaltest.post_reason('did not get expected values')
- print(ar)
- return 'fail'
+ assert ar[0][0][0] == 100 and ar[0][0][1] == 200 and ar[1][0][0] == 101 and ar[1][0][1] == 201 and ar[2][0][0] == 102 and ar[2][0][1] == 202, \
+ 'did not get expected values'
# This one too
ar = ds.ReadAsArray()
- if ar[0][0][0] != 100 or ar[0][0][1] != 200 or ar[1][0][0] != 101 or ar[1][0][1] != 201 or ar[2][0][0] != 102 or ar[2][0][1] != 202:
- gdaltest.post_reason('did not get expected values')
- print(ar)
- return 'fail'
+ assert ar[0][0][0] == 100 and ar[0][0][1] == 200 and ar[1][0][0] == 101 and ar[1][0][1] == 201 and ar[2][0][0] == 102 and ar[2][0][1] == 202, \
+ 'did not get expected values'
ds = None
- return 'success'
-
###############################################################################
# Test callback of ReadAsArray()
@@ -673,15 +537,15 @@ def numpy_rw_14_progress_callback_2(pct, message, user_data):
return 1 # 1 to continue, 0 to stop
-def numpy_rw_14():
+def test_numpy_rw_14():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
# Progress not implemented yet
if gdal.GetConfigOption('GTIFF_DIRECT_IO') == 'YES' or \
gdal.GetConfigOption('GTIFF_VIRTUAL_MEM_IO') == 'YES':
- return 'skip'
+ pytest.skip()
import numpy
@@ -692,43 +556,29 @@ def numpy_rw_14():
data = ds.GetRasterBand(1).ReadAsArray(resample_alg=gdal.GRIORA_NearestNeighbour,
callback=numpy_rw_14_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
- if abs(tab[0] - 1.05) > 1e-5 or not tab[1]:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
+ assert abs(tab[0] - 1.05) <= 1e-5 and tab[1]
# Test interruption
tab = [0]
data = ds.GetRasterBand(1).ReadAsArray(callback=numpy_rw_14_progress_interrupt_callback,
callback_data=tab)
- if data is not None:
- gdaltest.post_reason('failure')
- return 'fail'
- if tab[0] < 0.50:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is None
+ assert tab[0] >= 0.50
# Test Dataset.ReadAsArray
tab = [0.05, True]
data = ds.ReadAsArray(resample_alg=gdal.GRIORA_NearestNeighbour,
callback=numpy_rw_14_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
- if abs(tab[0] - 1.05) > 1e-5 or not tab[1]:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
+ assert abs(tab[0] - 1.05) <= 1e-5 and tab[1]
# Same with interruption
tab = [0]
data = ds.ReadAsArray(callback=numpy_rw_14_progress_interrupt_callback,
callback_data=tab)
- if data is not None or tab[0] < 0.50:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is None and tab[0] >= 0.50
# Test Dataset.ReadAsArray on a multi band file
ds = None
@@ -736,9 +586,7 @@ def numpy_rw_14():
last_pct = [0]
data = ds.ReadAsArray(callback=numpy_rw_14_progress_callback_2,
callback_data=last_pct)
- if data is None or abs(last_pct[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert not (data is None or abs(last_pct[0] - 1.0) > 1e-5)
last_pct = [0]
@@ -747,20 +595,16 @@ def numpy_rw_14():
data = ds.ReadAsArray(buf_obj=array,
callback=numpy_rw_14_progress_callback_2,
callback_data=last_pct)
- if data is None or abs(last_pct[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
-
- return 'success'
+ assert not (data is None or abs(last_pct[0] - 1.0) > 1e-5)
###############################################################################
# Test NumPy GetGeoTransform/SetGeoTransform
-def numpy_rw_15():
+def test_numpy_rw_15():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
from osgeo import gdal_array
@@ -768,25 +612,19 @@ def numpy_rw_15():
array = numpy.empty([1, 1, 1], numpy.uint8)
ds = gdal_array.OpenArray(array)
gt = ds.GetGeoTransform(can_return_null=True)
- if gt is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert gt is None
ds.SetGeoTransform([1, 2, 3, 4, 5, -6])
gt = ds.GetGeoTransform()
- if gt != (1, 2, 3, 4, 5, -6):
- gdaltest.post_reason('failure')
- return 'fail'
-
- return 'success'
+ assert gt == (1, 2, 3, 4, 5, -6)
###############################################################################
# Test errors of OpenArray()
-def numpy_rw_16():
+def test_numpy_rw_16():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
from osgeo import gdal_array
@@ -795,36 +633,28 @@ def numpy_rw_16():
array = numpy.empty([1], numpy.uint8)
with gdaltest.error_handler():
ds = gdal_array.OpenArray(array)
- if ds is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds is None
# 4D
array = numpy.empty([1, 1, 1, 1], numpy.uint8)
with gdaltest.error_handler():
ds = gdal_array.OpenArray(array)
- if ds is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds is None
# Unsupported data type
array = numpy.empty([1, 1], numpy.float16)
with gdaltest.error_handler():
ds = gdal_array.OpenArray(array)
- if ds is not None:
- gdaltest.post_reason('failure')
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# Test old deprecated way with gdal_array.GetArrayFilename()
-def numpy_rw_17():
+def test_numpy_rw_17():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
from osgeo import gdal_array
@@ -833,34 +663,26 @@ def numpy_rw_17():
array = numpy.empty([1, 1], numpy.uint8)
with gdaltest.error_handler():
ds = gdal.Open(gdal_array.GetArrayFilename(array))
- if ds is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds is None
gdal.SetConfigOption('GDAL_ARRAY_OPEN_BY_FILENAME', 'TRUE')
ds = gdal.Open(gdal_array.GetArrayFilename(array))
gdal.SetConfigOption('GDAL_ARRAY_OPEN_BY_FILENAME', None)
- if ds is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds is not None
# Invalid value
with gdaltest.error_handler():
ds = gdal.Open('NUMPY:::invalid')
- if ds is not None:
- gdaltest.post_reason('failure')
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# Test the pixel interleave options
-def numpy_rw_18():
+def test_numpy_rw_18():
if gdaltest.numpy_drv is None:
- return 'skip'
+ pytest.skip()
import numpy
import numpy.random
@@ -868,56 +690,21 @@ def numpy_rw_18():
img = numpy.random.randint(0, 255, size=(256, 200, 3)).astype('uint8')
ds = gdal_array.OpenArray(img, interleave='pixel')
- if ds is None:
- gdaltest.post_reason('Failed to open memory array as dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open memory array as dataset.'
bnd1 = ds.GetRasterBand(1).ReadAsArray()
bnd2 = ds.GetRasterBand(2).ReadAsArray()
bnd3 = ds.GetRasterBand(3).ReadAsArray()
res = numpy.dstack((bnd1, bnd2, bnd3))
- if not numpy.all(img == res):
- return 'fail'
+ assert numpy.all(img == res)
res = ds.ReadAsArray(interleave='pixel')
- if not numpy.all(img == res):
- return 'fail'
-
- return 'success'
+ assert numpy.all(img == res)
-def numpy_rw_cleanup():
+def test_numpy_rw_cleanup():
gdaltest.numpy_drv = None
- return 'success'
-
-
-gdaltest_list = [
- numpy_rw_1,
- numpy_rw_2,
- numpy_rw_3,
- numpy_rw_4,
- numpy_rw_5,
- numpy_rw_6,
- numpy_rw_7,
- numpy_rw_8,
- numpy_rw_9,
- numpy_rw_10,
- numpy_rw_11,
- numpy_rw_12,
- numpy_rw_13,
- numpy_rw_14,
- numpy_rw_15,
- numpy_rw_16,
- numpy_rw_17,
- numpy_rw_18,
- numpy_rw_cleanup]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('numpy_rw')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+
+
diff --git a/autotest/gcore/overviewds.py b/autotest/gcore/overviewds.py
index 369fb47ea030..c41456804bea 100755
--- a/autotest/gcore/overviewds.py
+++ b/autotest/gcore/overviewds.py
@@ -30,33 +30,27 @@
###############################################################################
import os
-import sys
import shutil
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Error cases
-def overviewds_1():
+def test_overviewds_1():
ds = gdal.OpenEx('data/byte.tif', open_options=['OVERVIEW_LEVEL=-1'])
- if ds is not None:
- return 'fail'
+ assert ds is None
ds = gdal.OpenEx('data/byte.tif', open_options=['OVERVIEW_LEVEL=0'])
- if ds is not None:
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# Nominal cases
-def overviewds_2():
+def test_overviewds_2():
shutil.copy('data/byte.tif', 'tmp')
ds = gdal.Open('tmp/byte.tif')
@@ -64,74 +58,41 @@ def overviewds_2():
ds = None
ds = gdal.OpenEx('tmp/byte.tif', open_options=['OVERVIEW_LEVEL=0only'])
- if ds.GetRasterBand(1).GetOverviewCount() != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 0
ds = None
src_ds = gdal.Open('tmp/byte.tif')
ds = gdal.OpenEx('tmp/byte.tif', open_options=['OVERVIEW_LEVEL=0'])
- if ds is None:
- return 'fail'
- if ds.RasterXSize != 10 or ds.RasterYSize != 10 or ds.RasterCount != 1:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetProjectionRef() != src_ds.GetProjectionRef():
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is not None
+ assert ds.RasterXSize == 10 and ds.RasterYSize == 10 and ds.RasterCount == 1
+ assert ds.GetProjectionRef() == src_ds.GetProjectionRef()
src_gt = src_ds.GetGeoTransform()
expected_gt = (src_gt[0], src_gt[1] * 2, src_gt[2], src_gt[3], src_gt[4], src_gt[5] * 2)
gt = ds.GetGeoTransform()
for i in range(6):
- if abs(expected_gt[i] - gt[i]) > 1e-5:
- gdaltest.post_reason('fail')
- print(expected_gt)
- print(gt)
- return 'fail'
- if ds.GetGCPCount() != 0 or ds.GetGCPProjection() != src_ds.GetGCPProjection() or ds.GetGCPs():
- gdaltest.post_reason('fail')
- return 'fail'
+ assert abs(expected_gt[i] - gt[i]) <= 1e-5
+ assert ds.GetGCPCount() == 0 and ds.GetGCPProjection() == src_ds.GetGCPProjection() and not ds.GetGCPs()
expected_data = src_ds.ReadRaster(0, 0, 20, 20, 10, 10)
got_data = ds.ReadRaster(0, 0, 10, 10)
- if expected_data != got_data:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert expected_data == got_data
got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 10, 10)
- if expected_data != got_data:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetOverviewCount() != 1:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert expected_data == got_data
+ assert ds.GetRasterBand(1).GetOverviewCount() == 1
expected_data = src_ds.ReadRaster(0, 0, 20, 20, 5, 5)
got_data = ds.GetRasterBand(1).GetOverview(0).ReadRaster(0, 0, 5, 5)
- if expected_data != got_data:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadata() != src_ds.GetMetadata():
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('AREA_OR_POINT') != src_ds.GetMetadataItem('AREA_OR_POINT'):
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadata('RPC'):
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadata('GEOLOCATION'):
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('RPC', 'FOO') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert expected_data == got_data
+ assert ds.GetMetadata() == src_ds.GetMetadata()
+ assert ds.GetMetadataItem('AREA_OR_POINT') == src_ds.GetMetadataItem('AREA_OR_POINT')
+ assert not ds.GetMetadata('RPC')
+ assert not ds.GetMetadata('GEOLOCATION')
+ assert ds.GetMetadataItem('RPC', 'FOO') is None
ds = None
- return 'success'
-
###############################################################################
# Test GCP
-def overviewds_3():
+def test_overviewds_3():
src_ds = gdal.Open('data/byte.tif')
ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/byte.tif', src_ds)
@@ -163,25 +124,17 @@ def overviewds_3():
ds = gdal.OpenEx('tmp/byte.tif', open_options=['OVERVIEW_LEVEL=0'])
gcps = ds.GetGCPs()
for i in range(3):
- if gcps[i].GCPPixel != src_gcps[i].GCPPixel / 2 or gcps[i].GCPLine != src_gcps[i].GCPLine / 2 or \
- gcps[i].GCPX != src_gcps[i].GCPX or gcps[i].GCPY != src_gcps[i].GCPY:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert (gcps[i].GCPPixel == src_gcps[i].GCPPixel / 2 and gcps[i].GCPLine == src_gcps[i].GCPLine / 2 and \
+ gcps[i].GCPX == src_gcps[i].GCPX and gcps[i].GCPY == src_gcps[i].GCPY)
# Really check that the transformer works
tr = gdal.Transformer(ds, None, ['METHOD=GCP_POLYNOMIAL'])
(_, pnt) = tr.TransformPoint(0, 20 / 2.0, 10 / 2.0)
for i in range(3):
- if abs(ref_pnt[i] - pnt[i]) > 1e-5:
- gdaltest.post_reason('fail')
- print(ref_pnt)
- print(pnt)
- return 'fail'
+ assert abs(ref_pnt[i] - pnt[i]) <= 1e-5
ds = None
- return 'success'
-
###############################################################################
# Test RPC
@@ -193,7 +146,7 @@ def myfloat(s):
return float(s)
-def overviewds_4():
+def test_overviewds_4():
shutil.copy('data/byte.tif', 'tmp/byte.tif')
shutil.copy('data/test_rpc.txt', 'tmp/byte_rpc.txt')
@@ -210,33 +163,20 @@ def overviewds_4():
got_md = ds.GetMetadata('RPC')
for key in rpc_md:
- if ds.GetMetadataItem(key, 'RPC') != got_md[key]:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem(key, 'RPC') == got_md[key]
if key == 'LINE_SCALE' or key == 'SAMP_SCALE' or key == 'LINE_OFF' or key == 'SAMP_OFF':
- if float(got_md[key]) != myfloat(rpc_md[key]) / 2:
- gdaltest.post_reason('fail')
- print(key)
- print(got_md[key])
- print(rpc_md[key])
- return 'fail'
+ assert float(got_md[key]) == myfloat(rpc_md[key]) / 2
elif got_md[key] != rpc_md[key]:
- gdaltest.post_reason('fail')
- print(key)
print(got_md[key])
print(rpc_md[key])
- return 'fail'
+ pytest.fail(key)
# Really check that the transformer works
tr = gdal.Transformer(ds, None, ['METHOD=RPC'])
(_, pnt) = tr.TransformPoint(0, 20 / 2.0, 10 / 2.0)
for i in range(3):
- if abs(ref_pnt[i] - pnt[i]) > 1e-5:
- gdaltest.post_reason('fail')
- print(ref_pnt)
- print(pnt)
- return 'fail'
+ assert abs(ref_pnt[i] - pnt[i]) <= 1e-5
ds = None
@@ -245,13 +185,12 @@ def overviewds_4():
except OSError:
pass
- return 'success'
-
+
###############################################################################
# Test GEOLOCATION
-def overviewds_5():
+def test_overviewds_5():
shutil.copy('data/sstgeo.tif', 'tmp/sstgeo.tif')
shutil.copy('data/sstgeo.vrt', 'tmp/sstgeo.vrt')
@@ -269,29 +208,15 @@ def overviewds_5():
got_md = ds.GetMetadata('GEOLOCATION')
for key in geoloc_md:
- if ds.GetMetadataItem(key, 'GEOLOCATION') != got_md[key]:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem(key, 'GEOLOCATION') == got_md[key]
if key == 'PIXEL_OFFSET' or key == 'LINE_OFFSET':
- if abs(float(got_md[key]) - myfloat(geoloc_md[key]) * 2) > 1e-1:
- gdaltest.post_reason('fail')
- print(key)
- print(got_md[key])
- print(geoloc_md[key])
- return 'fail'
+ assert abs(float(got_md[key]) - myfloat(geoloc_md[key]) * 2) <= 1e-1
elif key == 'PIXEL_STEP' or key == 'LINE_STEP':
- if abs(float(got_md[key]) - myfloat(geoloc_md[key]) / 2) > 1e-1:
- gdaltest.post_reason('fail')
- print(key)
- print(got_md[key])
- print(geoloc_md[key])
- return 'fail'
+ assert abs(float(got_md[key]) - myfloat(geoloc_md[key]) / 2) <= 1e-1
elif got_md[key] != geoloc_md[key]:
- gdaltest.post_reason('fail')
- print(key)
print(got_md[key])
print(geoloc_md[key])
- return 'fail'
+ pytest.fail(key)
# Really check that the transformer works
tr = gdal.Transformer(ds, None, ['METHOD=GEOLOC_ARRAY'])
@@ -299,20 +224,14 @@ def overviewds_5():
(_, pnt) = tr.TransformPoint(1, ref_pnt[0], ref_pnt[1])
for i in range(3):
- if abs(pnt[i] - expected_xyz[i]) > 0.5:
- gdaltest.post_reason('fail')
- print(pnt)
- print(expected_xyz)
- return 'fail'
+ assert abs(pnt[i] - expected_xyz[i]) <= 0.5
ds = None
- return 'success'
-
###############################################################################
# Test VRT
-def overviewds_6():
+def test_overviewds_6():
shutil.copy('data/byte.tif', 'tmp')
ds = gdal.Open('tmp/byte.tif')
@@ -326,22 +245,16 @@ def overviewds_6():
src_ds = None
ds = gdal.Open('tmp/byte.vrt')
- if ds.RasterXSize != 10 or ds.RasterYSize != 10 or ds.RasterCount != 1:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.RasterXSize == 10 and ds.RasterYSize == 10 and ds.RasterCount == 1
got_cs = ds.GetRasterBand(1).Checksum()
- if got_cs != expected_cs:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_cs == expected_cs
ds = None
- return 'success'
-
###############################################################################
# Cleanup
-def overviewds_cleanup():
+def test_overviewds_cleanup():
gdal.GetDriverByName('GTiff').Delete('tmp/byte.tif')
try:
@@ -359,21 +272,6 @@ def overviewds_cleanup():
except OSError:
pass
- return 'success'
-
-
-gdaltest_list = [overviewds_1,
- overviewds_2,
- overviewds_3,
- overviewds_4,
- overviewds_5,
- overviewds_6,
- overviewds_cleanup]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('overviewds')
+
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/pam.py b/autotest/gcore/pam.py
index 5f537e4e5795..285a3bca4c41 100755
--- a/autotest/gcore/pam.py
+++ b/autotest/gcore/pam.py
@@ -31,20 +31,19 @@
###############################################################################
import os
-import sys
import shutil
import stat
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Check that we can read PAM metadata for existing PNM file.
-def pam_1():
+def test_pam_1():
gdaltest.pam_setting = gdal.GetConfigOption('GDAL_PAM_ENABLED', "NULL")
gdal.SetConfigOption('GDAL_PAM_ENABLED', 'YES')
@@ -52,37 +51,26 @@ def pam_1():
ds = gdal.Open("data/byte.pnm")
base_md = ds.GetMetadata()
- if len(base_md) != 2 or base_md['other'] != 'red' \
- or base_md['key'] != 'value':
- gdaltest.post_reason('Default domain metadata missing')
- return 'fail'
+ assert len(base_md) == 2 and base_md['other'] == 'red' and base_md['key'] == 'value', \
+ 'Default domain metadata missing'
xml_md = ds.GetMetadata('xml:test')
- if len(xml_md) != 1:
- gdaltest.post_reason('xml:test metadata missing')
- return 'fail'
+ assert len(xml_md) == 1, 'xml:test metadata missing'
- if not isinstance(xml_md, list):
- gdaltest.post_reason('xml:test metadata not returned as list.')
- return 'fail'
+ assert isinstance(xml_md, list), 'xml:test metadata not returned as list.'
expected_xml = """
Value
"""
- if xml_md[0] != expected_xml:
- gdaltest.post_reason('xml does not match')
- print(xml_md)
- return 'fail'
-
- return 'success'
+ assert xml_md[0] == expected_xml, 'xml does not match'
###############################################################################
# Verify that we can write XML to a new file.
-def pam_2():
+def test_pam_2():
driver = gdal.GetDriverByName('PNM')
ds = driver.Create('tmp/pam.pnm', 10, 10)
@@ -100,66 +88,48 @@ def pam_2():
ds = None
- return 'success'
-
###############################################################################
# Check that we can read PAM metadata for existing PNM file.
-def pam_3():
+def test_pam_3():
ds = gdal.Open("tmp/pam.pnm")
band = ds.GetRasterBand(1)
base_md = band.GetMetadata()
- if len(base_md) != 2 or base_md['other'] != 'red' \
- or base_md['key'] != 'value':
- gdaltest.post_reason('Default domain metadata missing')
- return 'fail'
+ assert len(base_md) == 2 and base_md['other'] == 'red' and base_md['key'] == 'value', \
+ 'Default domain metadata missing'
xml_md = band.GetMetadata('xml:test')
- if len(xml_md) != 1:
- gdaltest.post_reason('xml:test metadata missing')
- return 'fail'
+ assert len(xml_md) == 1, 'xml:test metadata missing'
- if not isinstance(xml_md, list):
- gdaltest.post_reason('xml:test metadata not returned as list.')
- return 'fail'
+ assert isinstance(xml_md, list), 'xml:test metadata not returned as list.'
expected_xml = """
Value
"""
- if xml_md[0] != expected_xml:
- gdaltest.post_reason('xml does not match')
- print(xml_md)
- return 'fail'
+ assert xml_md[0] == expected_xml, 'xml does not match'
- if band.GetNoDataValue() != 100:
- gdaltest.post_reason('nodata not saved via pam')
- return 'fail'
+ assert band.GetNoDataValue() == 100, 'nodata not saved via pam'
ds = None
ds = gdal.Open('tmp/pam.pnm', gdal.GA_Update)
- if ds.GetRasterBand(1).DeleteNoDataValue() != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).DeleteNoDataValue() == 0
ds = None
ds = gdal.Open('tmp/pam.pnm')
- if ds.GetRasterBand(1).GetNoDataValue() is not None:
- gdaltest.post_reason('got nodata value whereas none was expected')
- return 'fail'
-
- return 'success'
+ assert ds.GetRasterBand(1).GetNoDataValue() is None, \
+ 'got nodata value whereas none was expected'
###############################################################################
# Check that PAM binary encoded nodata values work properly.
#
-def pam_4():
+def test_pam_4():
# Copy test dataset to tmp directory so that the .aux.xml file
# won't be rewritten with the statistics in the master dataset.
@@ -170,12 +140,8 @@ def pam_4():
ds = gdal.Open('tmp/mfftest.hdr')
stats = ds.GetRasterBand(1).GetStatistics(0, 1)
- if stats[0] != 0 or stats[1] != 4:
- gdaltest.post_reason('Got wrong min/max, likely nodata not working?')
- print(stats)
- return 'fail'
-
- return 'success'
+ assert stats[0] == 0 and stats[1] == 4, \
+ 'Got wrong min/max, likely nodata not working?'
###############################################################################
# Verify that .aux files that don't match the configuration of the
@@ -183,45 +149,35 @@ def pam_4():
#
-def pam_5():
+def test_pam_5():
ds = gdal.Open('data/sasha.tif')
filelist = ds.GetFileList()
ds = None
- if len(filelist) != 1:
- print(filelist)
-
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
-
- return 'success'
+ assert len(filelist) == 1, 'did not get expected file list.'
###############################################################################
# Verify we can read nodata values from .aux files (#2505)
#
-def pam_6():
+def test_pam_6():
ds = gdal.Open('data/f2r23.tif')
- if ds.GetRasterBand(1).GetNoDataValue() != 0:
- gdaltest.post_reason('did not get expected .aux sourced nodata.')
- return 'fail'
+ assert ds.GetRasterBand(1).GetNoDataValue() == 0, \
+ 'did not get expected .aux sourced nodata.'
ds = None
- if os.path.exists('data/f2r23.tif.aux.xml'):
- gdaltest.post_reason('did not expect .aux.xml to be created.')
- return 'fail'
-
- return 'success'
+ assert not os.path.exists('data/f2r23.tif.aux.xml'), \
+ 'did not expect .aux.xml to be created.'
###############################################################################
# Verify we can create overviews on PNG with PAM disabled (#3693)
#
-def pam_7():
+def test_pam_7():
gdal.SetConfigOption('GDAL_PAM_ENABLED', 'NO')
@@ -237,17 +193,14 @@ def pam_7():
os.remove('tmp/stefan_full_rgba.png')
os.remove('tmp/stefan_full_rgba.png.ovr')
- if ovr_count != 1:
- return 'fail'
-
- return 'success'
+ assert ovr_count == 1
###############################################################################
# Test that Band.SetDescription() goes through PAM (#3780)
#
-def pam_8():
+def test_pam_8():
gdal.SetConfigOption('GDAL_PAM_ENABLED', 'YES')
@@ -261,18 +214,14 @@ def pam_8():
gdal.GetDriverByName('GTiff').Delete('/vsimem/pam_8.tif')
- if desc != 'foo':
- print(desc)
- return 'fail'
-
- return 'success'
+ assert desc == 'foo'
###############################################################################
# Test that we can retrieve projection from xml:ESRI domain
#
-def pam_9():
+def test_pam_9():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/pam_9.tif', 1, 1, 1)
ds = None
@@ -299,17 +248,13 @@ def pam_9():
expected_wkt = """PROJCS["NAD_1983_UTM_Zone_14N",GEOGCS["GCS_North_American_1983",DATUM["North_American_Datum_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["false_easting",500000.0],PARAMETER["false_northing",0.0],PARAMETER["central_meridian",-99.0],PARAMETER["scale_factor",0.9996],PARAMETER["latitude_of_origin",0.0],UNIT["Meter",1.0]]"""
- if wkt != expected_wkt:
- print(wkt)
- return 'fail'
-
- return 'success'
+ assert wkt == expected_wkt
###############################################################################
# Test serializing and deserializing of various band metadata
-def pam_10():
+def test_pam_10():
src_ds = gdal.Open('data/testserialization.asc')
ds = gdal.GetDriverByName('AAIGRID').CreateCopy('/vsimem/pam_10.asc', src_ds)
@@ -319,80 +264,49 @@ def pam_10():
ds = gdal.Open('/vsimem/pam_10.asc')
gcps = ds.GetGCPs()
- if len(gcps) != 2 or ds.GetGCPCount() != 2:
- return 'fail'
+ assert len(gcps) == 2 and ds.GetGCPCount() == 2
- if ds.GetGCPProjection().find("WGS 84") == -1:
- print(ds.GetGCPProjection())
- return 'fail'
+ assert ds.GetGCPProjection().find("WGS 84") != -1
- if gcps[0].GCPPixel != 0 or gcps[0].GCPLine != 1 or \
- gcps[0].GCPX != 2 or gcps[0].GCPY != 3 or gcps[0].GCPZ != 4:
- print(gcps[0])
- return 'fail'
+ assert (gcps[0].GCPPixel == 0 and gcps[0].GCPLine == 1 and \
+ gcps[0].GCPX == 2 and gcps[0].GCPY == 3 and gcps[0].GCPZ == 4)
- if gcps[1].GCPPixel != 1 or gcps[1].GCPLine != 2 or \
- gcps[1].GCPX != 3 or gcps[1].GCPY != 4 or gcps[1].GCPZ != 5:
- print(gcps[1])
- return 'fail'
+ assert (gcps[1].GCPPixel == 1 and gcps[1].GCPLine == 2 and \
+ gcps[1].GCPX == 3 and gcps[1].GCPY == 4 and gcps[1].GCPZ == 5)
band = ds.GetRasterBand(1)
- if band.GetDescription() != 'MyDescription':
- print(band.GetDescription())
- return 'fail'
+ assert band.GetDescription() == 'MyDescription'
- if band.GetUnitType() != 'MyUnit':
- print(band.GetUnitType())
- return 'fail'
+ assert band.GetUnitType() == 'MyUnit'
- if band.GetOffset() != 1:
- print(band.GetOffset())
- return 'fail'
+ assert band.GetOffset() == 1
- if band.GetScale() != 2:
- print(band.GetScale())
- return 'fail'
+ assert band.GetScale() == 2
- if band.GetRasterColorInterpretation() != gdal.GCI_PaletteIndex:
- print(band.GetRasterColorInterpretation())
- return 'fail'
+ assert band.GetRasterColorInterpretation() == gdal.GCI_PaletteIndex
- if band.GetCategoryNames() != ['Cat1', 'Cat2']:
- print(band.GetCategoryNames())
- return 'fail'
+ assert band.GetCategoryNames() == ['Cat1', 'Cat2']
ct = band.GetColorTable()
- if ct.GetColorEntry(0) != (0, 0, 0, 255):
- print(ct.GetColorEntry(0))
- return 'fail'
- if ct.GetColorEntry(1) != (1, 1, 1, 255):
- print(ct.GetColorEntry(1))
- return 'fail'
+ assert ct.GetColorEntry(0) == (0, 0, 0, 255)
+ assert ct.GetColorEntry(1) == (1, 1, 1, 255)
- if band.GetMaximum() != 0:
- print(band.GetMaximum())
- return 'fail'
+ assert band.GetMaximum() == 0
- if band.GetMinimum() != 2:
- print(band.GetMinimum())
- return 'fail'
+ assert band.GetMinimum() == 2
- if band.GetMetadata() != {'STATISTICS_MEAN': '1', 'STATISTICS_MINIMUM': '2', 'STATISTICS_MAXIMUM': '0', 'STATISTICS_STDDEV': '3'}:
- print(band.GetMetadata())
- return 'fail'
+ assert band.GetMetadata() == {'STATISTICS_MEAN': '1', 'STATISTICS_MINIMUM': '2', 'STATISTICS_MAXIMUM': '0', 'STATISTICS_STDDEV': '3'}
ds = None
gdal.Unlink('/vsimem/pam_10.asc')
gdal.Unlink('/vsimem/pam_10.asc.aux.xml')
- return 'success'
-
###############################################################################
# Test PamProxyDb mechanism
-def pam_11():
+def test_pam_11():
# Create a read-only directory
try:
@@ -412,52 +326,41 @@ def pam_11():
f = open('tmpdirreadonly/test', 'w')
if f is not None:
f.close()
- return 'skip'
+ pytest.skip()
except IOError:
pass
# Compute statistics --> the saving as .aux.xml should fail
ds = gdal.Open('tmpdirreadonly/byte.tif')
stats = ds.GetRasterBand(1).ComputeStatistics(False)
- if stats[0] != 74:
- gdaltest.post_reason('did not get expected minimum')
- return 'fail'
+ assert stats[0] == 74, 'did not get expected minimum'
gdal.ErrorReset()
ds = None
error_msg = gdal.GetLastErrorMsg()
- if error_msg.find('Unable to save auxiliary information') != 0:
- gdaltest.post_reason('warning was expected at that point')
- return 'fail'
+ assert error_msg.find('Unable to save auxiliary information') == 0, \
+ 'warning was expected at that point'
# Check that we actually have no saved statistics
ds = gdal.Open('tmpdirreadonly/byte.tif')
stats = ds.GetRasterBand(1).GetStatistics(False, False)
- if stats[3] != -1:
- gdaltest.post_reason('did not expected to have stats at that point')
- return 'fail'
+ assert stats[3] == -1, 'did not expected to have stats at that point'
ds = None
# This must be run as an external process so we can override GDAL_PAM_PROXY_DIR
# at the beginning of the process
import test_py_scripts
ret = test_py_scripts.run_py_script_as_external_script('.', 'pamproxydb', '-test1')
- if ret.find('success') == -1:
- gdaltest.post_reason('pamproxydb.py -test1 failed %s' % ret)
- return 'fail'
+ assert ret.find('success') != -1, ('pamproxydb.py -test1 failed %s' % ret)
# Test loading an existing proxydb
ret = test_py_scripts.run_py_script_as_external_script('.', 'pamproxydb', '-test2')
- if ret.find('success') == -1:
- gdaltest.post_reason('pamproxydb.py -test2 failed %s' % ret)
- return 'fail'
-
- return 'success'
+ assert ret.find('success') != -1, ('pamproxydb.py -test2 failed %s' % ret)
###############################################################################
# Test histogram with 64bit counts
-def pam_12():
+def test_pam_12():
shutil.copy('data/byte.tif', 'tmp')
open('tmp/byte.tif.aux.xml', 'wt').write("""
@@ -485,28 +388,16 @@ def pam_12():
gdal.Unlink('tmp/byte.tif')
gdal.Unlink('tmp/byte.tif.aux.xml')
- if hist1 != hist2:
- gdaltest.post_reason('fail')
- print(hist1)
- print(hist2)
- return 'fail'
- if hist1[0] != 6000000000:
- gdaltest.post_reason('fail')
- print(hist1)
- return 'fail'
- if aux_xml.find('6000000000|') < 0:
- gdaltest.post_reason('fail')
- print(aux_xml)
- return 'fail'
-
- return 'success'
+ assert hist1 == hist2
+ assert hist1[0] == 6000000000
+ assert aux_xml.find('6000000000|') >= 0
###############################################################################
# Test various stuff with PAM disabled
#
-def pam_13():
+def test_pam_13():
gdal.SetConfigOption('GDAL_PAM_ENABLED', 'NO')
@@ -517,34 +408,26 @@ def pam_13():
gdal.PushErrorHandler()
ret = ds.GetRasterBand(1).SetNoDataValue(0)
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
gdal.PushErrorHandler()
ret = ds.GetRasterBand(1).DeleteNoDataValue()
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
ds = None
- if gdal.VSIStatL('/vsimem/tmp.pnm.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tmp.pnm.aux.xml') is None
gdal.Unlink('/vsimem/tmp.pnm')
gdal.SetConfigOption('GDAL_PAM_ENABLED', 'YES')
- return 'success'
-
###############################################################################
# Cleanup.
-def pam_cleanup():
+def test_pam_cleanup():
gdaltest.clean_tmp()
if gdaltest.pam_setting != 'NULL':
gdal.SetConfigOption('GDAL_PAM_ENABLED', gdaltest.pam_setting)
@@ -561,29 +444,6 @@ def pam_cleanup():
except OSError:
pass
- return 'success'
-
-
-gdaltest_list = [
- pam_1,
- pam_2,
- pam_3,
- pam_4,
- pam_5,
- pam_6,
- pam_7,
- pam_8,
- pam_9,
- pam_10,
- pam_11,
- pam_12,
- pam_13,
- pam_cleanup]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('pam')
+
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/pixfun.py b/autotest/gcore/pixfun.py
index 66d20f8bf882..f7ca48f3be41 100755
--- a/autotest/gcore/pixfun.py
+++ b/autotest/gcore/pixfun.py
@@ -28,7 +28,7 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
+import pytest
try:
import numpy
@@ -38,337 +38,254 @@
from osgeo import gdal
-sys.path.append('../pymod')
-import gdaltest
###############################################################################
# Verify real part extraction from a complex dataset.
-def pixfun_real_c():
+def test_pixfun_real_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_real_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == refdata.real):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata.real)
###############################################################################
# Verify real part extraction from a complex dataset.
-def pixfun_real_r():
+def test_pixfun_real_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_real_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/int32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == refdata.real):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata.real)
###############################################################################
# Verify imaginary part extraction from a complex dataset.
-def pixfun_imag_c():
+def test_pixfun_imag_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_imag_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == refdata.imag):
- gdaltest.post_reason('fail')
- return 'fail'
+ assert numpy.alltrue(data == refdata.imag)
# Test bugfix of #6599
copied_ds = gdal.Translate('', filename, format='MEM')
data_ds = copied_ds.GetRasterBand(1).ReadAsArray()
copied_ds = None
- if not numpy.alltrue(data == data_ds):
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == data_ds)
###############################################################################
# Verify imaginary part extraction from a real dataset.
-def pixfun_imag_r():
+def test_pixfun_imag_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_imag_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == 0):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == 0)
###############################################################################
# Verify imaginary part extraction from a real dataset.
-def pixfun_complex():
+def test_pixfun_complex():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_complex.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/int32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.allclose(data, refdata + 1j * refdata):
- return 'fail'
-
- return 'success'
+ assert numpy.allclose(data, refdata + 1j * refdata)
###############################################################################
# Verify modulus extraction from a complex (float) dataset.
-def pixfun_mod_c():
+def test_pixfun_mod_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_mod_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == numpy.abs(refdata)):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == numpy.abs(refdata))
###############################################################################
# Verify modulus extraction from a real (integer type) dataset.
-def pixfun_mod_r():
+def test_pixfun_mod_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_mod_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/int32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == numpy.abs(refdata)):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == numpy.abs(refdata))
###############################################################################
# Verify phase extraction from a complex dataset.
-def pixfun_phase_c():
+def test_pixfun_phase_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_phase_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
refdata = refdata.astype('complex128')
- if not numpy.allclose(data, numpy.arctan2(refdata.imag, refdata.real)):
- print(data - numpy.arctan2(refdata.imag, refdata.real))
- return 'fail'
-
- return 'success'
+ assert numpy.allclose(data, numpy.arctan2(refdata.imag, refdata.real))
###############################################################################
# Verify phase extraction from a real dataset.
-def pixfun_phase_r():
+def test_pixfun_phase_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_phase_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/pixfun_imag_c.vrt'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == numpy.arctan2(0, refdata)):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == numpy.arctan2(0, refdata))
###############################################################################
# Verify cmplex conjugare computation on a complex dataset.
-def pixfun_conj_c():
+def test_pixfun_conj_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_conj_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == numpy.conj(refdata)):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == numpy.conj(refdata))
###############################################################################
# Verify cmplex conjugare computation on a real dataset.
-def pixfun_conj_r():
+def test_pixfun_conj_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_conj_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/int32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == numpy.conj(refdata)):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == numpy.conj(refdata))
###############################################################################
# Verify the sum of 3 (real) datasets.
-def pixfun_sum_r():
+def test_pixfun_sum_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_sum_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
if numpy_available:
@@ -376,30 +293,24 @@ def pixfun_sum_r():
for reffilename in ('data/uint16.tif', 'data/int32.tif',
'data/float32.tif'):
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata += refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == refdata):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata)
+
###############################################################################
# Verify the sum of 3 (two complex and one real) datasets.
-def pixfun_sum_c():
+def test_pixfun_sum_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_sum_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
if numpy_available:
@@ -407,100 +318,76 @@ def pixfun_sum_c():
for reffilename in ('data/uint16.tif', 'data/cint_sar.tif',
'data/cfloat64.tif'):
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata += refds.GetRasterBand(1).ReadAsArray(0, 0, 5, 6)
- if not numpy.alltrue(data == refdata):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata)
+
###############################################################################
# Verify the difference of 2 (real) datasets.
-def pixfun_diff_r():
+def test_pixfun_diff_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_diff_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/int32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata1 = refds.GetRasterBand(1).ReadAsArray(0, 0, 5, 6)
reffilename = 'data/float32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata2 = refds.GetRasterBand(1).ReadAsArray(10, 10, 5, 6)
- if not numpy.alltrue(data == refdata1 - refdata2):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata1 - refdata2)
###############################################################################
# Verify the difference of 2 (complex) datasets.
-def pixfun_diff_c():
+def test_pixfun_diff_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_diff_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata1 = refds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cfloat64.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata2 = refds.GetRasterBand(1).ReadAsArray(0, 0, 5, 6)
- if not numpy.alltrue(data == refdata1 - refdata2):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata1 - refdata2)
###############################################################################
# Verify the product of 3 (real) datasets.
-def pixfun_mul_r():
+def test_pixfun_mul_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_mul_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
if numpy_available:
@@ -508,460 +395,319 @@ def pixfun_mul_r():
for reffilename in ('data/uint16.tif', 'data/int32.tif',
'data/float32.tif'):
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata *= refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == refdata):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata)
+
###############################################################################
# Verify the product of 2 (complex) datasets.
-def pixfun_mul_c():
+def test_pixfun_mul_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_mul_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == refdata * refdata):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata * refdata)
###############################################################################
# Verify the product with complex conjugate of a complex datasets.
-def pixfun_cmul_c():
+def test_pixfun_cmul_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_cmul_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == refdata * refdata.conj()):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata * refdata.conj())
###############################################################################
# Verify the product with complex conjugate of two real datasets.
-def pixfun_cmul_r():
+def test_pixfun_cmul_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_cmul_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/uint16.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata1 = refds.GetRasterBand(1).ReadAsArray()
refdata1 = refdata1.astype('float64')
reffilename = 'data/int32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata2 = refds.GetRasterBand(1).ReadAsArray()
refdata2 = refdata2.astype('float64')
- if not numpy.alltrue(data == refdata1 * refdata2.conj()):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == refdata1 * refdata2.conj())
###############################################################################
# Verify computation of the inverse of a real datasets.
-def pixfun_inv_r():
+def test_pixfun_inv_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_inv_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/uint16.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
refdata = refdata.astype('float64')
- if not numpy.alltrue(data == 1. / refdata):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == 1. / refdata)
###############################################################################
# Verify computation of the inverse of a complex datasets.
-def pixfun_inv_c():
+def test_pixfun_inv_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_inv_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
refdata = refdata.astype('complex')
delta = data - 1. / refdata
- if not numpy.alltrue(abs(delta.real) < 1e-13):
- return 'fail'
- if not numpy.alltrue(abs(delta.imag) < 1e-13):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(abs(delta.real) < 1e-13)
+ assert numpy.alltrue(abs(delta.imag) < 1e-13)
###############################################################################
# Verify intensity computation of a complex dataset.
-def pixfun_intensity_c():
+def test_pixfun_intensity_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_intensity_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == (refdata * refdata.conj()).real):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == (refdata * refdata.conj()).real)
###############################################################################
# Verify intensity computation of real dataset.
-def pixfun_intensity_r():
+def test_pixfun_intensity_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_intensity_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/float32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == (refdata * refdata.conj()).real):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == (refdata * refdata.conj()).real)
###############################################################################
# Verify square root computation.
-def pixfun_sqrt():
+def test_pixfun_sqrt():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_sqrt.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/float32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == numpy.sqrt(refdata)):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == numpy.sqrt(refdata))
###############################################################################
# Verify logarithm computation of real dataset.
-def pixfun_log10_r():
+def test_pixfun_log10_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_log10_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/float32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.alltrue(data == numpy.log10(refdata)):
- return 'fail'
-
- return 'success'
+ assert numpy.alltrue(data == numpy.log10(refdata))
###############################################################################
# Verify logarithm computation of imag dataset.
-def pixfun_log10_c():
+def test_pixfun_log10_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_log10_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.allclose(data, numpy.log10(numpy.abs(refdata))):
- return 'fail'
-
- return 'success'
+ assert numpy.allclose(data, numpy.log10(numpy.abs(refdata)))
###############################################################################
# Verify dB computation of real dataset.
-def pixfun_dB_r():
+def test_pixfun_dB_r():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_dB_r.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/float32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.allclose(data, 20. * numpy.log10(refdata)):
- return 'fail'
-
- return 'success'
+ assert numpy.allclose(data, 20. * numpy.log10(refdata))
###############################################################################
# Verify dB computation of imag dataset.
-def pixfun_dB_c():
+def test_pixfun_dB_c():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_dB_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
- if not numpy.allclose(data, 20. * numpy.log10(numpy.abs(refdata))):
- return 'fail'
-
- return 'success'
+ assert numpy.allclose(data, 20. * numpy.log10(numpy.abs(refdata)))
###############################################################################
# Verify conversion from dB to amplitude.
-def pixfun_dB2amp():
+def test_pixfun_dB2amp():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_dB2amp.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/float32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
# if not numpy.alltrue(data == 10.**(refdata/20.)):
- if not numpy.allclose(data, 10.**(refdata / 20.)):
- return 'fail'
-
- return 'success'
+ assert numpy.allclose(data, 10.**(refdata / 20.))
###############################################################################
# Verify conversion from dB to power.
-def pixfun_dB2pow():
+def test_pixfun_dB2pow():
if not numpy_available:
- return 'skip'
+ pytest.skip()
filename = 'data/pixfun_dB2pow.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
- return 'fail'
+ assert ds is not None, ('Unable to open "%s" dataset.' % filename)
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/float32.tif'
refds = gdal.Open(reffilename)
- if refds is None:
- gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
- return 'fail'
+ assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
refdata = refds.GetRasterBand(1).ReadAsArray()
refdata = refdata.astype('float64')
- if not numpy.allclose(data, 10.**(refdata / 10.)):
- return 'fail'
-
- return 'success'
-
-
-###############################################################################
-
-gdaltest_list = [
- pixfun_real_c,
- pixfun_real_r,
- pixfun_imag_c,
- pixfun_imag_r,
- pixfun_complex,
- pixfun_mod_c,
- pixfun_mod_r,
- pixfun_phase_c,
- pixfun_phase_r,
- pixfun_conj_c,
- pixfun_conj_r,
- pixfun_sum_r,
- pixfun_sum_c,
- pixfun_diff_r,
- pixfun_diff_c,
- pixfun_mul_r,
- pixfun_mul_c,
- pixfun_cmul_c,
- pixfun_cmul_r,
- pixfun_inv_r,
- pixfun_inv_c,
- pixfun_intensity_c,
- pixfun_intensity_r,
- pixfun_sqrt,
- pixfun_log10_r,
- pixfun_log10_c,
- pixfun_dB_r,
- pixfun_dB_c,
- pixfun_dB2amp,
- pixfun_dB2pow,
-]
-
-
-if __name__ == '__main__':
- gdaltest.setup_run('pixfun')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
+ assert numpy.allclose(data, 10.**(refdata / 10.))
+
+
+###############################################################################
+
+
+
diff --git a/autotest/gcore/pnm_read.py b/autotest/gcore/pnm_read.py
index ffb469312486..c5d8ab41cb24 100755
--- a/autotest/gcore/pnm_read.py
+++ b/autotest/gcore/pnm_read.py
@@ -28,32 +28,24 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-
-sys.path.append('../pymod')
+import pytest
import gdaltest
###############################################################################
# When imported build a list of units based on the files available.
-gdaltest_list = []
-
init_list = [
- ('byte.pnm', 1, 4672, None),
- ('uint16.pnm', 1, 4672, None)]
-
-for item in init_list:
- ut = gdaltest.GDALTest('PNM', item[0], item[1], item[2])
- if ut is None:
- print('PNM tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testOpen, item[0]))
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('pnm_read')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ ('byte.pnm', 4672),
+ ('uint16.pnm', 4672)]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.require_driver('PNM')
+def test_pnm_open(filename, checksum):
+ ut = gdaltest.GDALTest('PNM', filename, 1, checksum)
+ ut.testOpen()
diff --git a/autotest/gcore/pnm_write.py b/autotest/gcore/pnm_write.py
index 38bb96bde533..3f8fb0e01f63 100755
--- a/autotest/gcore/pnm_write.py
+++ b/autotest/gcore/pnm_write.py
@@ -25,29 +25,27 @@
# Boston, MA 02111-1307, USA.
###############################################################################
-import sys
-
-sys.path.append('../pymod')
+import pytest
import gdaltest
init_list = [
- ('byte.tif', 1, 4672, None),
- ('uint16.tif', 1, 4672, None)]
-
-gdaltest_list = []
-
-for item in init_list:
- ut = gdaltest.GDALTest('PNM', item[0], item[1], item[2])
- if ut is None:
- print('PNM tests skipped')
- gdaltest_list.append((ut.testCreateCopy, item[0]))
- gdaltest_list.append((ut.testCreate, item[0]))
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('pnm_write')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ ('byte.tif', 4672),
+ ('uint16.tif', 4672)]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.parametrize(
+ 'testfunction', [
+ 'testCreateCopy',
+ 'testCreate',
+ ]
+)
+@pytest.mark.require_driver('PNM')
+def test_pnm_create(filename, checksum, testfunction):
+ ut = gdaltest.GDALTest('PNM', filename, 1, checksum)
+ getattr(ut, testfunction)()
diff --git a/autotest/gcore/rasterio.py b/autotest/gcore/rasterio.py
index 76e15a805188..e6ee3b191e7c 100755
--- a/autotest/gcore/rasterio.py
+++ b/autotest/gcore/rasterio.py
@@ -32,16 +32,15 @@
import struct
import sys
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Test writing a 1x1 buffer to a 10x6 raster and read it back
-def rasterio_1():
+def test_rasterio_1():
data = 'A'.encode('ascii')
drv = gdal.GetDriverByName('GTiff')
@@ -53,25 +52,19 @@ def rasterio_1():
ds.GetRasterBand(1).Fill(0)
ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data, buf_type=gdal.GDT_Byte, buf_xsize=1, buf_ysize=1)
- if checksum != ds.GetRasterBand(1).Checksum():
- gdaltest.post_reason('Didnt get expected checksum ')
- return 'fail'
+ assert checksum == ds.GetRasterBand(1).Checksum(), 'Didnt get expected checksum '
data2 = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, 1, 1)
- if data2 != data:
- gdaltest.post_reason('Didnt get expected buffer ')
- return 'fail'
+ assert data2 == data, 'Didnt get expected buffer '
ds = None
drv.Delete('tmp/rasterio1.tif')
- return 'success'
-
###############################################################################
# Test writing a 5x4 buffer to a 10x6 raster and read it back
-def rasterio_2():
+def test_rasterio_2():
data = 'AAAAAAAAAAAAAAAAAAAA'.encode('ascii')
drv = gdal.GetDriverByName('GTiff')
@@ -83,25 +76,19 @@ def rasterio_2():
ds.GetRasterBand(1).Fill(0)
ds.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, data, buf_type=gdal.GDT_Byte, buf_xsize=5, buf_ysize=4)
- if checksum != ds.GetRasterBand(1).Checksum():
- gdaltest.post_reason('Didnt get expected checksum ')
- return 'fail'
+ assert checksum == ds.GetRasterBand(1).Checksum(), 'Didnt get expected checksum '
data2 = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, 5, 4)
- if data2 != data:
- gdaltest.post_reason('Didnt get expected buffer ')
- return 'fail'
+ assert data2 == data, 'Didnt get expected buffer '
ds = None
drv.Delete('tmp/rasterio2.tif')
- return 'success'
-
###############################################################################
# Test extensive read & writes into a non tiled raster
-def rasterio_3():
+def test_rasterio_3():
data = [['' for i in range(4)] for i in range(5)]
for xsize in range(5):
@@ -128,9 +115,8 @@ def rasterio_3():
buf_type=gdal.GDT_Byte,
buf_xsize=xsize + 1, buf_ysize=ysize + 1)
data2 = ds.ReadRaster(i, j, k + 1, m + 1, xsize + 1, ysize + 1, gdal.GDT_Byte)
- if data2 != data[xsize][ysize]:
- gdaltest.post_reason('Didnt get expected buffer ')
- return 'fail'
+ assert data2 == data[xsize][ysize], \
+ 'Didnt get expected buffer '
m = m + 1
k = k + 1
j = j + 1
@@ -139,13 +125,11 @@ def rasterio_3():
ds = None
drv.Delete('tmp/rasterio3.tif')
- return 'success'
-
###############################################################################
# Test extensive read & writes into a tiled raster
-def rasterio_4():
+def test_rasterio_4():
data = ['' for i in range(5 * 4)]
for size in range(5 * 4):
@@ -172,11 +156,8 @@ def rasterio_4():
buf_xsize=xsize + 1, buf_ysize=ysize + 1)
data2 = ds.ReadRaster(i, j, k + 1, m + 1, xsize + 1, ysize + 1, gdal.GDT_Byte)
if data2 != data[(xsize + 1) * (ysize + 1) - 1]:
- gdaltest.post_reason('Didnt get expected buffer ')
print(i, j, k, m, xsize, ysize)
- print(data2)
- print(data[(xsize + 1) * (ysize + 1) - 1])
- return 'fail'
+ pytest.fail('Didnt get expected buffer ')
m = m + 1
k = k + 1
if j >= 15:
@@ -191,13 +172,11 @@ def rasterio_4():
ds = None
drv.Delete('tmp/rasterio4.tif')
- return 'success'
-
###############################################################################
# Test error cases of ReadRaster()
-def rasterio_5():
+def test_rasterio_5():
ds = gdal.Open('data/byte.tif')
@@ -211,18 +190,12 @@ def rasterio_5():
res = ds.ReadRaster(0, 0, 1, 1, band_list=[band_number])
gdal.PopErrorHandler()
error_msg = gdal.GetLastErrorMsg()
- if res is not None:
- gdaltest.post_reason('expected None')
- return 'fail'
- if error_msg.find('this band does not exist on dataset') == -1:
- gdaltest.post_reason('did not get expected error msg')
- print(error_msg)
- return 'fail'
+ assert res is None, 'expected None'
+ assert error_msg.find('this band does not exist on dataset') != -1, \
+ 'did not get expected error msg'
res = ds.ReadRaster(0, 0, 1, 1, band_list=[1, 1])
- if res is None:
- gdaltest.post_reason('expected non None')
- return 'fail'
+ assert res is not None, 'expected non None'
for obj in [ds, ds.GetRasterBand(1)]:
gdal.ErrorReset()
@@ -230,13 +203,9 @@ def rasterio_5():
res = obj.ReadRaster(0, 0, 21, 21)
gdal.PopErrorHandler()
error_msg = gdal.GetLastErrorMsg()
- if res is not None:
- gdaltest.post_reason('expected None')
- return 'fail'
- if error_msg.find('Access window out of range in RasterIO()') == -1:
- gdaltest.post_reason('did not get expected error msg (1)')
- print(error_msg)
- return 'fail'
+ assert res is None, 'expected None'
+ assert error_msg.find('Access window out of range in RasterIO()') != -1, \
+ 'did not get expected error msg (1)'
# This should only fail on a 32bit build
try:
@@ -254,100 +223,73 @@ def rasterio_5():
res = obj.ReadRaster(0, 0, 1, 1, 1000000, 1000000)
gdal.PopErrorHandler()
error_msg = gdal.GetLastErrorMsg()
- if res is not None:
- gdaltest.post_reason('expected None')
- return 'fail'
- if error_msg.find('Integer overflow') == -1:
- gdaltest.post_reason('did not get expected error msg (2)')
- print(error_msg)
- return 'fail'
+ assert res is None, 'expected None'
+ assert error_msg.find('Integer overflow') != -1, \
+ 'did not get expected error msg (2)'
gdal.ErrorReset()
gdal.PushErrorHandler('CPLQuietErrorHandler')
res = obj.ReadRaster(0, 0, 0, 1)
gdal.PopErrorHandler()
error_msg = gdal.GetLastErrorMsg()
- if res is not None:
- gdaltest.post_reason('expected None')
- return 'fail'
- if error_msg.find('Illegal values for buffer size') == -1:
- gdaltest.post_reason('did not get expected error msg (3)')
- print(error_msg)
- return 'fail'
+ assert res is None, 'expected None'
+ assert error_msg.find('Illegal values for buffer size') != -1, \
+ 'did not get expected error msg (3)'
ds = None
- return 'success'
-
###############################################################################
# Test error cases of WriteRaster()
-def rasterio_6():
+def test_rasterio_6():
ds = gdal.GetDriverByName('MEM').Create('', 2, 2)
for obj in [ds, ds.GetRasterBand(1)]:
- try:
+ with pytest.raises(Exception, message='expected exception'):
obj.WriteRaster(0, 0, 2, 2, None)
- gdaltest.post_reason('expected exception')
- return 'fail'
- except:
- pass
+
gdal.ErrorReset()
gdal.PushErrorHandler('CPLQuietErrorHandler')
obj.WriteRaster(0, 0, 2, 2, ' ')
gdal.PopErrorHandler()
error_msg = gdal.GetLastErrorMsg()
- if error_msg.find('Buffer too small') == -1:
- gdaltest.post_reason('did not get expected error msg (1)')
- print(error_msg)
- return 'fail'
+ assert error_msg.find('Buffer too small') != -1, \
+ 'did not get expected error msg (1)'
gdal.ErrorReset()
gdal.PushErrorHandler('CPLQuietErrorHandler')
obj.WriteRaster(-1, 0, 1, 1, ' ')
gdal.PopErrorHandler()
error_msg = gdal.GetLastErrorMsg()
- if error_msg.find('Access window out of range in RasterIO()') == -1:
- gdaltest.post_reason('did not get expected error msg (2)')
- print(error_msg)
- return 'fail'
+ assert error_msg.find('Access window out of range in RasterIO()') != -1, \
+ 'did not get expected error msg (2)'
gdal.ErrorReset()
gdal.PushErrorHandler('CPLQuietErrorHandler')
obj.WriteRaster(0, 0, 0, 1, ' ')
gdal.PopErrorHandler()
error_msg = gdal.GetLastErrorMsg()
- if error_msg.find('Illegal values for buffer size') == -1:
- gdaltest.post_reason('did not get expected error msg (3)')
- print(error_msg)
- return 'fail'
+ assert error_msg.find('Illegal values for buffer size') != -1, \
+ 'did not get expected error msg (3)'
ds = None
- return 'success'
-
###############################################################################
# Test that default window reading works via ReadRaster()
-def rasterio_7():
+def test_rasterio_7():
ds = gdal.Open('data/byte.tif')
data = ds.GetRasterBand(1).ReadRaster()
- if len(data) != 400:
- gdaltest.post_reason('did not read expected band data via ReadRaster()')
- return 'fail'
+ assert len(data) == 400, 'did not read expected band data via ReadRaster()'
data = ds.ReadRaster()
- if len(data) != 400:
- gdaltest.post_reason('did not read expected dataset data via ReadRaster()')
- return 'fail'
-
- return 'success'
+ assert len(data) == 400, 'did not read expected dataset data via ReadRaster()'
###############################################################################
# Test callback of ReadRaster()
@@ -379,92 +321,68 @@ def rasterio_8_progress_callback_2(pct, message, user_data):
return 1 # 1 to continue, 0 to stop
-def rasterio_8():
+def test_rasterio_8():
ds = gdal.Open('data/byte.tif')
# Progress not implemented yet
if gdal.GetConfigOption('GTIFF_DIRECT_IO') == 'YES' or \
gdal.GetConfigOption('GTIFF_VIRTUAL_MEM_IO') == 'YES':
- return 'skip'
+ pytest.skip()
# Test RasterBand.ReadRaster
tab = [0, True]
data = ds.GetRasterBand(1).ReadRaster(resample_alg=gdal.GRIORA_NearestNeighbour,
callback=rasterio_8_progress_callback,
callback_data=tab)
- if len(data) != 400:
- gdaltest.post_reason('did not read expected band data via ReadRaster()')
- return 'fail'
- if abs(tab[0] - 1) > 1e-5 or not tab[1]:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert len(data) == 400, 'did not read expected band data via ReadRaster()'
+ assert abs(tab[0] - 1) <= 1e-5 and tab[1]
# Test interruption
tab = [0]
data = ds.GetRasterBand(1).ReadRaster(resample_alg=gdal.GRIORA_NearestNeighbour,
callback=rasterio_8_progress_interrupt_callback,
callback_data=tab)
- if data is not None:
- gdaltest.post_reason('failure')
- return 'fail'
- if tab[0] < 0.50:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is None
+ assert tab[0] >= 0.50
# Test RasterBand.ReadRaster with type change
tab = [0, True]
data = ds.GetRasterBand(1).ReadRaster(buf_type=gdal.GDT_Int16,
callback=rasterio_8_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('did not read expected band data via ReadRaster()')
- return 'fail'
- if abs(tab[0] - 1) > 1e-5 or not tab[1]:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None, 'did not read expected band data via ReadRaster()'
+ assert abs(tab[0] - 1) <= 1e-5 and tab[1]
# Same with interruption
tab = [0]
data = ds.GetRasterBand(1).ReadRaster(buf_type=gdal.GDT_Int16,
callback=rasterio_8_progress_interrupt_callback,
callback_data=tab)
- if data is not None or tab[0] < 0.50:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is None and tab[0] >= 0.50
# Test RasterBand.ReadRaster with resampling
tab = [0, True]
data = ds.GetRasterBand(1).ReadRaster(buf_xsize=40,
callback=rasterio_8_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('did not read expected band data via ReadRaster()')
- return 'fail'
- if abs(tab[0] - 1) > 1e-5 or not tab[1]:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None, 'did not read expected band data via ReadRaster()'
+ assert abs(tab[0] - 1) <= 1e-5 and tab[1]
# Same with interruption
tab = [0]
data = ds.GetRasterBand(1).ReadRaster(buf_xsize=40,
callback=rasterio_8_progress_interrupt_callback,
callback_data=tab)
- if data is not None or tab[0] < 0.50:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is None and tab[0] >= 0.50
# Test Dataset.ReadRaster
tab = [0, True]
data = ds.ReadRaster(resample_alg=gdal.GRIORA_NearestNeighbour,
callback=rasterio_8_progress_callback,
callback_data=tab)
- if len(data) != 400:
- gdaltest.post_reason('did not read expected dataset data via ReadRaster()')
- return 'fail'
- if abs(tab[0] - 1) > 1e-5 or not tab[1]:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert len(data) == 400, 'did not read expected dataset data via ReadRaster()'
+ assert abs(tab[0] - 1) <= 1e-5 and tab[1]
ds = None
@@ -474,17 +392,13 @@ def rasterio_8():
data = ds.ReadRaster(resample_alg=gdal.GRIORA_NearestNeighbour,
callback=rasterio_8_progress_callback_2,
callback_data=last_pct)
- if data is None or abs(last_pct[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert not (data is None or abs(last_pct[0] - 1.0) > 1e-5)
# Same with interruption
tab = [0]
data = ds.ReadRaster(callback=rasterio_8_progress_interrupt_callback,
callback_data=tab)
- if data is not None or tab[0] < 0.50:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is None and tab[0] >= 0.50
ds = None
@@ -494,19 +408,13 @@ def rasterio_8():
data = ds.ReadRaster(resample_alg=gdal.GRIORA_NearestNeighbour,
callback=rasterio_8_progress_callback_2,
callback_data=last_pct)
- if data is None or abs(last_pct[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert not (data is None or abs(last_pct[0] - 1.0) > 1e-5)
# Same with interruption
tab = [0]
data = ds.ReadRaster(callback=rasterio_8_progress_interrupt_callback,
callback_data=tab)
- if data is not None or tab[0] < 0.50:
- gdaltest.post_reason('failure')
- return 'fail'
-
- return 'success'
+ assert data is None and tab[0] >= 0.50
###############################################################################
# Test resampling algorithm of ReadRaster()
@@ -530,7 +438,7 @@ def rasterio_9_checksum(data, buf_xsize, buf_ysize, data_type=gdal.GDT_Byte):
return cs
-def rasterio_9():
+def test_rasterio_9():
ds = gdal.Open('data/byte.tif')
# Test RasterBand.ReadRaster, with Bilinear
@@ -541,19 +449,12 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Bilinear,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
data_ar = struct.unpack('h' * 10 * 10, data)
cs = rasterio_9_checksum(data, 10, 10, data_type=gdal.GDT_Int16)
- if cs != 1211: # checksum of gdal_translate data/byte.tif out.tif -outsize 10 10 -r BILINEAR
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 1211
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert abs(tab[0] - 1.0) <= 1e-5
# Same but query with GDT_Float32. Check that we do not get floating-point
# values, since the band type is Byte
@@ -563,10 +464,7 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Bilinear)
data_float32_ar = struct.unpack('f' * 10 * 10, data)
- if data_ar != data_float32_ar:
- gdaltest.post_reason('failure')
- print(data_float32_ar)
- return 'fail'
+ assert data_ar == data_float32_ar
# Test RasterBand.ReadRaster, with Lanczos
tab = [0, None]
@@ -575,18 +473,11 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Lanczos,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 10, 10)
- if cs != 1154: # checksum of gdal_translate data/byte.tif out.tif -outsize 10 10 -r LANCZOS
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 1154
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert abs(tab[0] - 1.0) <= 1e-5
# Test RasterBand.ReadRaster, with Bilinear and UInt16 data type
src_ds_uint16 = gdal.Open('data/uint16.tif')
@@ -597,18 +488,11 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Bilinear,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 10, 10, data_type=gdal.GDT_UInt16)
- if cs != 1211: # checksum of gdal_translate data/byte.tif out.tif -outsize 10 10 -r BILINEAR
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 1211
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert abs(tab[0] - 1.0) <= 1e-5
# Test RasterBand.ReadRaster, with Bilinear on Complex, thus using warp API
tab = [0, None]
@@ -619,18 +503,11 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Bilinear,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 10, 10, data_type=gdal.GDT_CInt16)
- if cs != 1211: # checksum of gdal_translate data/byte.tif out.tif -outsize 10 10 -r BILINEAR
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 1211
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert abs(tab[0] - 1.0) <= 1e-5
# Test interruption
tab = [0, 0.5]
@@ -641,12 +518,8 @@ def rasterio_9():
callback=rasterio_9_progress_callback,
callback_data=tab)
gdal.PopErrorHandler()
- if data is not None:
- gdaltest.post_reason('failure')
- return 'fail'
- if tab[0] < 0.50:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is None
+ assert tab[0] >= 0.50
# Test RasterBand.ReadRaster, with Gauss, and downsampling
tab = [0, None]
@@ -655,18 +528,11 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Gauss,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 10, 10)
- if cs != 1089: # checksum of gdal_translate data/byte.tif out.tif -outsize 10 10 -r GAUSS
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 1089
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert abs(tab[0] - 1.0) <= 1e-5
# Test RasterBand.ReadRaster, with Cubic, and downsampling
tab = [0, None]
@@ -675,44 +541,27 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Cubic,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 10, 10)
- if cs != 1059: # checksum of gdal_translate data/byte.tif out.tif -outsize 10 10 -r CUBIC
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 1059
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert abs(tab[0] - 1.0) <= 1e-5
# Test RasterBand.ReadRaster, with Cubic, and downsampling with >=8x8 source samples used for a dest sample
data = ds.GetRasterBand(1).ReadRaster(buf_xsize=5,
buf_ysize=5,
resample_alg=gdal.GRIORA_Cubic)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 5, 5)
- if cs != 214: # checksum of gdal_translate data/byte.tif out.tif -outsize 5 5 -r CUBIC
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 214
# Same with UInt16
data = src_ds_uint16.GetRasterBand(1).ReadRaster(buf_xsize=5,
buf_ysize=5,
resample_alg=gdal.GRIORA_Cubic)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 5, 5, data_type=gdal.GDT_UInt16)
- if cs != 214: # checksum of gdal_translate data/byte.tif out.tif -outsize 5 5 -r CUBIC
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 214
# Test RasterBand.ReadRaster, with Cubic and supersampling
tab = [0, None]
@@ -721,18 +570,11 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Cubic,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 40, 40)
- if cs != 19556: # checksum of gdal_translate data/byte.tif out.tif -outsize 40 40 -r CUBIC
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 19556
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert abs(tab[0] - 1.0) <= 1e-5
# Test Dataset.ReadRaster, with Cubic and supersampling
tab = [0, None]
@@ -741,18 +583,11 @@ def rasterio_9():
resample_alg=gdal.GRIORA_CubicSpline,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 40, 40)
- if cs != 19041: # checksum of gdal_translate data/byte.tif out.tif -outsize 40 40 -r CUBICSPLINE
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 19041
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert abs(tab[0] - 1.0) <= 1e-5
# Test Dataset.ReadRaster on a multi band file, with INTERLEAVE=PIXEL
ds = gdal.Open('data/rgbsmall_cmyk.tif')
@@ -762,23 +597,13 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Cubic,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data[0:25 * 25], 25, 25)
- if cs != 5975: # checksum of gdal_translate data/rgbsmall_cmyk.tif out.tif -outsize 25 25 -r CUBIC
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 5975
cs = rasterio_9_checksum(data[25 * 25:2 * 25 * 25], 25, 25)
- if cs != 6248: # checksum of gdal_translate data/rgbsmall_cmyk.tif out.tif -outsize 25 25 -r CUBIC
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
-
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert cs == 6248
+
+ assert abs(tab[0] - 1.0) <= 1e-5
ds = None
# Test Band.ReadRaster on a RGBA with parts fully opaque, and fully transparent and with huge upscaling
@@ -789,65 +614,48 @@ def rasterio_9():
resample_alg=gdal.GRIORA_Cubic,
callback=rasterio_9_progress_callback,
callback_data=tab)
- if data is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is not None
cs = rasterio_9_checksum(data, 162 * 16, 150 * 16)
- if cs != 30836: # checksum of gdal_translate data/stefan_full_rgba.png out.tif -outsize 1600% 1600% -r CUBIC
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
- if abs(tab[0] - 1.0) > 1e-5:
- gdaltest.post_reason('failure')
- return 'fail'
-
- return 'success'
+ assert cs == 30836
+ assert abs(tab[0] - 1.0) <= 1e-5
###############################################################################
# Test error when getting a block
-def rasterio_10():
+def test_rasterio_10():
ds = gdal.Open('data/byte_truncated.tif')
gdal.PushErrorHandler()
data = ds.GetRasterBand(1).ReadRaster()
gdal.PopErrorHandler()
- if data is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is None
# Change buffer type
gdal.PushErrorHandler()
data = ds.GetRasterBand(1).ReadRaster(buf_type=gdal.GDT_Int16)
gdal.PopErrorHandler()
- if data is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data is None
# Resampling case
gdal.PushErrorHandler()
data = ds.GetRasterBand(1).ReadRaster(buf_xsize=10,
buf_ysize=10)
gdal.PopErrorHandler()
- if data is not None:
- gdaltest.post_reason('failure')
- return 'fail'
-
- return 'success'
+ assert data is None
###############################################################################
# Test cubic resampling and nbits
-def rasterio_11():
+def test_rasterio_11():
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
import numpy
except (ImportError, AttributeError):
- return 'skip'
+ pytest.skip()
mem_ds = gdal.GetDriverByName('MEM').Create('', 4, 3)
mem_ds.GetRasterBand(1).WriteArray(numpy.array([[80, 125, 125, 80], [80, 125, 125, 80], [80, 125, 125, 80]]))
@@ -855,21 +663,13 @@ def rasterio_11():
# A bit dummy
mem_ds.GetRasterBand(1).SetMetadataItem('NBITS', '8', 'IMAGE_STRUCTURE')
ar = mem_ds.GetRasterBand(1).ReadAsArray(0, 0, 4, 3, 8, 3, resample_alg=gdal.GRIORA_Cubic)
- if ar.max() != 129:
- gdaltest.post_reason('failure')
- print(ar.max())
- return 'fail'
+ assert ar.max() == 129
# NBITS=7
mem_ds.GetRasterBand(1).SetMetadataItem('NBITS', '7', 'IMAGE_STRUCTURE')
ar = mem_ds.GetRasterBand(1).ReadAsArray(0, 0, 4, 3, 8, 3, resample_alg=gdal.GRIORA_Cubic)
# Would overshoot to 129 if NBITS was ignored
- if ar.max() != 127:
- gdaltest.post_reason('failure')
- print(ar.max())
- return 'fail'
-
- return 'success'
+ assert ar.max() == 127
###############################################################################
# Test cubic resampling on dataset RasterIO with an alpha channel
@@ -883,14 +683,14 @@ def rasterio_12_progress_callback(pct, message, user_data):
return 1 # 1 to continue, 0 to stop
-def rasterio_12():
+def test_rasterio_12():
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
import numpy
except (ImportError, AttributeError):
- return 'skip'
+ pytest.skip()
mem_ds = gdal.GetDriverByName('MEM').Create('', 4, 3, 4)
for i in range(3):
@@ -903,56 +703,35 @@ def rasterio_12():
ar_ds = mem_ds.ReadAsArray(0, 0, 4, 3, buf_xsize=8, buf_ysize=3, resample_alg=gdal.GRIORA_Cubic,
callback=rasterio_12_progress_callback,
callback_data=tab)
- if tab[0] != 1.0:
- gdaltest.post_reason('failure')
- print(tab)
- return 'fail'
+ assert tab[0] == 1.0
ar_ds2 = mem_ds.ReadAsArray(0, 0, 4, 3, buf_xsize=8, buf_ysize=3, resample_alg=gdal.GRIORA_Cubic)
- if not numpy.array_equal(ar_ds, ar_ds2):
- gdaltest.post_reason('failure')
- print(ar_ds)
- print(ar_ds2)
- return 'fail'
+ assert numpy.array_equal(ar_ds, ar_ds2)
ar_bands = [mem_ds.GetRasterBand(i + 1).ReadAsArray(0, 0, 4, 3, buf_xsize=8, buf_ysize=3, resample_alg=gdal.GRIORA_Cubic) for i in range(4)]
# Results of band or dataset RasterIO should be the same
for i in range(4):
- if not numpy.array_equal(ar_ds[i], ar_bands[i]):
- gdaltest.post_reason('failure')
- print(ar_ds)
- print(ar_bands[i])
- return 'fail'
+ assert numpy.array_equal(ar_ds[i], ar_bands[i])
# First, second and third band should have identical content
- if not numpy.array_equal(ar_ds[0], ar_ds[1]):
- gdaltest.post_reason('failure')
- print(ar_ds[0])
- print(ar_ds[1])
- return 'fail'
+ assert numpy.array_equal(ar_ds[0], ar_ds[1])
# Alpha band should be different
- if numpy.array_equal(ar_ds[0], ar_ds[3]):
- gdaltest.post_reason('failure')
- print(ar_ds[0])
- print(ar_ds[3])
- return 'fail'
-
- return 'success'
+ assert not numpy.array_equal(ar_ds[0], ar_ds[3])
###############################################################################
# Test cubic resampling with masking
-def rasterio_13():
+def test_rasterio_13():
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
import numpy
except (ImportError, AttributeError):
- return 'skip'
+ pytest.skip()
for dt in [gdal.GDT_Byte, gdal.GDT_UInt16, gdal.GDT_UInt32]:
@@ -963,20 +742,14 @@ def rasterio_13():
ar_ds = mem_ds.ReadAsArray(0, 0, 4, 3, buf_xsize=8, buf_ysize=3, resample_alg=gdal.GRIORA_Cubic)
expected_ar = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 255, 255, 255, 255, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]])
- if not numpy.array_equal(ar_ds, expected_ar):
- gdaltest.post_reason('failure')
- print(dt)
- print(ar_ds)
- print(expected_ar)
- return 'fail'
-
- return 'success'
+ assert numpy.array_equal(ar_ds, expected_ar), dt
+
###############################################################################
# Test average downsampling by a factor of 2 on exact boundaries
-def rasterio_14():
+def test_rasterio_14():
gdal.FileFromMemBuffer('/vsimem/rasterio_14.asc',
"""ncols 6
@@ -993,11 +766,7 @@ def rasterio_14():
ds = gdal.Translate('/vsimem/rasterio_14_out.asc', '/vsimem/rasterio_14.asc', options='-of AAIGRID -r average -outsize 50% 50%')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 110:
- gdaltest.post_reason('fail')
- print(cs)
- print(ds.ReadAsArray())
- return 'fail'
+ assert cs == 110, ds.ReadAsArray()
gdal.Unlink('/vsimem/rasterio_14.asc')
gdal.Unlink('/vsimem/rasterio_14_out.asc')
@@ -1006,41 +775,27 @@ def rasterio_14():
ds.GetRasterBand(1).WriteRaster(ds.RasterXSize - 1, 0, 1, 1, struct.pack('B' * 1, 100))
data = ds.ReadRaster(buf_xsize=int(ds.RasterXSize / 2), buf_ysize=1, resample_alg=gdal.GRIORA_Average)
data = struct.unpack('B' * int(ds.RasterXSize / 2), data)
- if data[-1:][0] != 50:
- gdaltest.post_reason('fail')
- print(data[-1:][0])
- return 'fail'
+ assert data[-1:][0] == 50
data = ds.ReadRaster(ds.RasterXSize - 2, 0, 2, 1, buf_xsize=1, buf_ysize=1, resample_alg=gdal.GRIORA_Average)
data = struct.unpack('B' * 1, data)
- if data[0] != 50:
- gdaltest.post_reason('fail')
- print(data[0])
- return 'fail'
+ assert data[0] == 50
ds = gdal.GetDriverByName('MEM').Create('', 1, 1000000)
ds.GetRasterBand(1).WriteRaster(0, ds.RasterYSize - 1, 1, 1, struct.pack('B' * 1, 100))
data = ds.ReadRaster(buf_xsize=1, buf_ysize=int(ds.RasterYSize / 2), resample_alg=gdal.GRIORA_Average)
data = struct.unpack('B' * int(ds.RasterYSize / 2), data)
- if data[-1:][0] != 50:
- gdaltest.post_reason('fail')
- print(data[-1:][0])
- return 'fail'
+ assert data[-1:][0] == 50
data = ds.ReadRaster(0, ds.RasterYSize - 2, 1, 2, buf_xsize=1, buf_ysize=1, resample_alg=gdal.GRIORA_Average)
data = struct.unpack('B' * 1, data)
- if data[0] != 50:
- gdaltest.post_reason('fail')
- print(data[0])
- return 'fail'
-
- return 'success'
+ assert data[0] == 50
###############################################################################
# Test average oversampling by an integer factor (should behave like nearest)
-def rasterio_15():
+def test_rasterio_15():
gdal.FileFromMemBuffer('/vsimem/rasterio_15.asc',
"""ncols 2
@@ -1057,22 +812,16 @@ def rasterio_15():
ds = gdal.Translate('/vsimem/rasterio_15_out.asc', '/vsimem/rasterio_15.asc', options='-of AAIGRID -r average -outsize 200% 200%')
data = ds.GetRasterBand(1).ReadRaster()
cs = ds.GetRasterBand(1).Checksum()
- if data != data_ref or cs != 134:
- gdaltest.post_reason('fail')
- print(cs)
- print(ds.ReadAsArray())
- return 'fail'
+ assert data == data_ref and cs == 134, ds.ReadAsArray()
gdal.Unlink('/vsimem/rasterio_15.asc')
gdal.Unlink('/vsimem/rasterio_15_out.asc')
- return 'success'
-
###############################################################################
# Test mode downsampling by a factor of 2 on exact boundaries
-def rasterio_16():
+def test_rasterio_16():
gdal.FileFromMemBuffer('/vsimem/rasterio_16.asc',
"""ncols 6
@@ -1089,21 +838,15 @@ def rasterio_16():
ds = gdal.Translate('/vsimem/rasterio_16_out.asc', '/vsimem/rasterio_16.asc', options='-of AAIGRID -r mode -outsize 50% 50%')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 15:
- gdaltest.post_reason('fail')
- print(cs)
- print(ds.ReadAsArray())
- return 'fail'
+ assert cs == 15, ds.ReadAsArray()
gdal.Unlink('/vsimem/rasterio_16.asc')
gdal.Unlink('/vsimem/rasterio_16_out.asc')
- return 'success'
-
###############################################################################
-def rasterio_lanczos_nodata():
+def test_rasterio_lanczos_nodata():
ds = gdal.Open('data/rasterio_lanczos_nodata.tif')
@@ -1120,17 +863,12 @@ def rasterio_lanczos_nodata():
0, 0, 0, 22481, 22466, 22500, 22534, 22536, 22571,
0, 0, 0, 22460, 22460, 22547, 22538, 22456, 22572,
0, 0, 0, 0, 22504, 22496, 22564, 22563, 22610)
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(data_ar)
- return 'fail'
-
- return 'success'
+ assert data_ar == expected_ar
###############################################################################
-def rasterio_resampled_value_is_nodata():
+def test_rasterio_resampled_value_is_nodata():
gdal.FileFromMemBuffer('/vsimem/in.asc',
"""ncols 4
@@ -1151,20 +889,14 @@ def rasterio_resampled_value_is_nodata():
resample_alg=gdal.GRIORA_Lanczos)
data_ar = struct.unpack('f' * 1, data)
expected_ar = (1.1754943508222875e-38, )
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(data_ar)
- return 'fail'
+ assert data_ar == expected_ar
data = ds.GetRasterBand(1).ReadRaster(buf_xsize=1,
buf_ysize=1,
resample_alg=gdal.GRIORA_Average)
data_ar = struct.unpack('f' * 1, data)
expected_ar = (1.1754943508222875e-38, )
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(data_ar)
- return 'fail'
+ assert data_ar == expected_ar
gdal.Unlink('/vsimem/in.asc')
@@ -1188,52 +920,13 @@ def rasterio_resampled_value_is_nodata():
resample_alg=gdal.GRIORA_Lanczos)
data_ar = struct.unpack('I' * 1, data)
expected_ar = (1, )
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(data_ar)
- return 'fail'
+ assert data_ar == expected_ar
data = ds.GetRasterBand(1).ReadRaster(buf_xsize=1,
buf_ysize=1,
resample_alg=gdal.GRIORA_Average)
data_ar = struct.unpack('I' * 1, data)
expected_ar = (1, )
- if data_ar != expected_ar:
- gdaltest.post_reason('fail')
- print(data_ar)
- return 'fail'
+ assert data_ar == expected_ar
gdal.Unlink('/vsimem/in.asc')
-
- return 'success'
-
-gdaltest_list = [
- rasterio_1,
- rasterio_2,
- rasterio_3,
- rasterio_4,
- rasterio_5,
- rasterio_6,
- rasterio_7,
- rasterio_8,
- rasterio_9,
- rasterio_10,
- rasterio_11,
- rasterio_12,
- rasterio_13,
- rasterio_14,
- rasterio_15,
- rasterio_16,
- rasterio_lanczos_nodata,
- rasterio_resampled_value_is_nodata,
-]
-
-# gdaltest_list = [ rasterio_16 ]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('rasterio')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/rat.py b/autotest/gcore/rat.py
index 0aa3cd020eb1..9ec0499ce279 100755
--- a/autotest/gcore/rat.py
+++ b/autotest/gcore/rat.py
@@ -30,25 +30,24 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Create a raster attribute table.
-def rat_1():
+def test_rat_1():
gdaltest.saved_rat = None
try:
rat = gdal.RasterAttributeTable()
except:
- return 'skip'
+ pytest.skip()
rat.CreateColumn('Value', gdal.GFT_Integer, gdal.GFU_MinMax)
rat.CreateColumn('Count', gdal.GFT_Integer, gdal.GFU_PixelCount)
@@ -63,46 +62,30 @@ def rat_1():
rat2 = rat.Clone()
- if rat2.GetColumnCount() != 2:
- gdaltest.post_reason('wrong column count')
- return 'fail'
+ assert rat2.GetColumnCount() == 2, 'wrong column count'
- if rat2.GetRowCount() != 3:
- gdaltest.post_reason('wrong row count')
- return 'fail'
+ assert rat2.GetRowCount() == 3, 'wrong row count'
- if rat2.GetNameOfCol(1) != 'Count':
- gdaltest.post_reason('wrong column name')
- return 'fail'
+ assert rat2.GetNameOfCol(1) == 'Count', 'wrong column name'
- if rat2.GetUsageOfCol(1) != gdal.GFU_PixelCount:
- gdaltest.post_reason('wrong column usage')
- return 'fail'
+ assert rat2.GetUsageOfCol(1) == gdal.GFU_PixelCount, 'wrong column usage'
- if rat2.GetTypeOfCol(1) != gdal.GFT_Integer:
- gdaltest.post_reason('wrong column type')
- return 'fail'
+ assert rat2.GetTypeOfCol(1) == gdal.GFT_Integer, 'wrong column type'
- if rat2.GetRowOfValue(11.0) != 1:
- gdaltest.post_reason('wrong row for value')
- return 'fail'
+ assert rat2.GetRowOfValue(11.0) == 1, 'wrong row for value'
- if rat2.GetValueAsInt(1, 1) != 200:
- gdaltest.post_reason('wrong field value.')
- return 'fail'
+ assert rat2.GetValueAsInt(1, 1) == 200, 'wrong field value.'
gdaltest.saved_rat = rat
- return 'success'
-
###############################################################################
# Save a RAT in a file, written to .aux.xml, read it back and check it.
-def rat_2():
+def test_rat_2():
if gdaltest.saved_rat is None:
- return 'skip'
+ pytest.skip()
ds = gdal.GetDriverByName('PNM').Create('tmp/rat_2.pnm', 100, 90, 1,
gdal.GDT_Byte)
@@ -113,33 +96,19 @@ def rat_2():
ds = gdal.Open('tmp/rat_2.pnm', gdal.GA_Update)
rat2 = ds.GetRasterBand(1).GetDefaultRAT()
- if rat2.GetColumnCount() != 2:
- gdaltest.post_reason('wrong column count')
- return 'fail'
+ assert rat2.GetColumnCount() == 2, 'wrong column count'
- if rat2.GetRowCount() != 3:
- gdaltest.post_reason('wrong row count')
- return 'fail'
+ assert rat2.GetRowCount() == 3, 'wrong row count'
- if rat2.GetNameOfCol(1) != 'Count':
- gdaltest.post_reason('wrong column name')
- return 'fail'
+ assert rat2.GetNameOfCol(1) == 'Count', 'wrong column name'
- if rat2.GetUsageOfCol(1) != gdal.GFU_PixelCount:
- gdaltest.post_reason('wrong column usage')
- return 'fail'
+ assert rat2.GetUsageOfCol(1) == gdal.GFU_PixelCount, 'wrong column usage'
- if rat2.GetTypeOfCol(1) != gdal.GFT_Integer:
- gdaltest.post_reason('wrong column type')
- return 'fail'
+ assert rat2.GetTypeOfCol(1) == gdal.GFT_Integer, 'wrong column type'
- if rat2.GetRowOfValue(11.0) != 1:
- gdaltest.post_reason('wrong row for value')
- return 'fail'
+ assert rat2.GetRowOfValue(11.0) == 1, 'wrong row for value'
- if rat2.GetValueAsInt(1, 1) != 200:
- gdaltest.post_reason('wrong field value.')
- return 'fail'
+ assert rat2.GetValueAsInt(1, 1) == 200, 'wrong field value.'
# unset the RAT
ds.GetRasterBand(1).SetDefaultRAT(None)
@@ -149,41 +118,24 @@ def rat_2():
ds = gdal.Open('tmp/rat_2.pnm')
rat = ds.GetRasterBand(1).GetDefaultRAT()
ds = None
- if rat is not None:
- gdaltest.post_reason('expected a NULL RAT.')
- return 'fail'
+ assert rat is None, 'expected a NULL RAT.'
gdal.GetDriverByName('PNM').Delete('tmp/rat_2.pnm')
gdaltest.saved_rat = None
- return 'success'
-
###############################################################################
# Save an empty RAT (#5451)
-def rat_3():
+def test_rat_3():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/rat_3.tif', 1, 1)
ds.GetRasterBand(1).SetDefaultRAT(gdal.RasterAttributeTable())
ds = None
gdal.GetDriverByName('GTiff').Delete('/vsimem/rat_3.tif')
-
- return 'success'
##############################################################################
-gdaltest_list = [
- rat_1,
- rat_2,
- rat_3,
- None]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('rat')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/rfc30.py b/autotest/gcore/rfc30.py
index c83d846e20f8..f4b9706a21b6 100755
--- a/autotest/gcore/rfc30.py
+++ b/autotest/gcore/rfc30.py
@@ -29,19 +29,18 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
from sys import version_info
from osgeo import gdal
-sys.path.append('../pymod')
import gdaltest
+import pytest
###############################################################################
# Try opening a file with a Chinese name using the Python UTF-8 string.
-def rfc30_1():
+def test_rfc30_1():
if version_info >= (3, 0, 0):
filename = 'xx\u4E2D\u6587.\u4E2D\u6587'
@@ -51,7 +50,7 @@ def rfc30_1():
filename_escaped = gdaltest.urlescape(filename.encode('utf-8'))
if not gdaltest.download_file('http://download.osgeo.org/gdal/data/gtiff/' + filename_escaped, filename):
- return 'skip'
+ pytest.skip()
filename = 'tmp/cache/' + filename
@@ -59,25 +58,19 @@ def rfc30_1():
file_list = ds.GetFileList()
- if ds is None:
- gdaltest.post_reason('failed to open utf filename.')
- return 'fail'
+ assert ds is not None, 'failed to open utf filename.'
ds = None
ds = gdal.Open(file_list[0])
- if ds is None:
- gdaltest.post_reason('failed to open utf filename (2).')
- return 'fail'
-
- return 'success'
+ assert ds is not None, 'failed to open utf filename (2).'
###############################################################################
# Try creating, then renaming a utf-8 named file.
-def rfc30_2():
+def test_rfc30_2():
if version_info >= (3, 0, 0):
filename = 'tmp/yy\u4E2D\u6587.\u4E2D\u6587'
@@ -87,9 +80,7 @@ def rfc30_2():
# filename = filename.encode( 'utf-8' )
fd = gdal.VSIFOpenL(filename, 'w')
- if fd is None:
- gdaltest.post_reason('failed to create utf-8 named file.')
- return 'fail'
+ assert fd is not None, 'failed to create utf-8 named file.'
gdal.VSIFWriteL('abc', 3, 1, fd)
gdal.VSIFCloseL(fd)
@@ -104,14 +95,10 @@ def rfc30_2():
filename_for_rename = filename.encode('utf-8') # FIXME ? rename should perhaps accept unicode strings
new_filename = new_filename.encode('utf-8') # FIXME ? rename should perhaps accept unicode strings
- if gdal.Rename(filename_for_rename, new_filename) != 0:
- gdaltest.post_reason('utf-8 rename failed.')
- return 'fail'
+ assert gdal.Rename(filename_for_rename, new_filename) == 0, 'utf-8 rename failed.'
fd = gdal.VSIFOpenL(new_filename, 'r')
- if fd is None:
- gdaltest.post_reason('reopen failed with utf8')
- return 'fail'
+ assert fd is not None, 'reopen failed with utf8'
data = gdal.VSIFReadL(3, 1, fd)
gdal.VSIFCloseL(fd)
@@ -120,26 +107,12 @@ def rfc30_2():
ok = eval("data == b'abc'")
else:
ok = data == 'abc'
- if not ok:
- gdaltest.post_reason('did not get expected data.')
- return 'fail'
+ assert ok, 'did not get expected data.'
gdal.Unlink(new_filename)
fd = gdal.VSIFOpenL(new_filename, 'r')
- if fd is not None:
- gdaltest.post_reason('did unlink fail on utf8 filename?')
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = [rfc30_1, rfc30_2]
-
-if __name__ == '__main__':
+ assert fd is None, 'did unlink fail on utf8 filename?'
- gdaltest.setup_run('rfc30')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/testnonboundtoswig.py b/autotest/gcore/testnonboundtoswig.py
index 189466bd314c..2ee689177b73 100755
--- a/autotest/gcore/testnonboundtoswig.py
+++ b/autotest/gcore/testnonboundtoswig.py
@@ -29,11 +29,10 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
from sys import version_info
from osgeo import gdal
+import pytest
-sys.path.append('../pymod')
try:
import ctypes
@@ -57,26 +56,25 @@ def find_libgdal():
# Init
-def testnonboundtoswig_init():
-
+@pytest.fixture(scope='module', autouse=True)
+def setup():
global gdal_handle_init, gdal_handle, gdal_handle_stdcall
if gdal_handle_init:
if gdal_handle is None:
- return 'skip'
- return 'success'
+ pytest.skip()
+ return gdal_handle
gdal_handle_init = True
try:
ctypes.cdll
except ImportError:
- print('cannot find ctypes')
- return 'skip'
+ pytest.skip('cannot find ctypes')
name = find_libgdal()
if name is None:
- return 'skip'
+ pytest.skip()
print('Found libgdal we are running against : %s' % name)
@@ -98,81 +96,53 @@ def testnonboundtoswig_init():
dynamic_version = str(dynamic_version, 'utf-8')
if dynamic_version != static_version:
- gdaltest.post_reason('dynamic version(%s) does not match static version (%s)' % (dynamic_version, static_version))
gdal_handle = None
gdal_handle_stdcall = None
- return 'skip'
+ pytest.skip('dynamic version(%s) does not match static version (%s)' % (dynamic_version, static_version))
- return 'success'
- except:
+ return gdal_handle
+ except Exception:
print('cannot find gdal shared object')
- return 'skip'
+ pytest.skip()
###############################################################################
# Call GDALDestroyDriverManager()
def GDALDestroyDriverManager():
+ if gdal_handle_stdcall:
+ gdal_handle_stdcall.GDALDestroyDriverManager.argtypes = []
+ gdal_handle_stdcall.GDALDestroyDriverManager.restype = None
- if gdal_handle is None:
- testnonboundtoswig_init()
-
- if gdal_handle is None:
- return 'skip'
-
- gdal_handle_stdcall.GDALDestroyDriverManager.argtypes = []
- gdal_handle_stdcall.GDALDestroyDriverManager.restype = None
-
- gdal_handle_stdcall.GDALDestroyDriverManager()
-
- return 'success'
+ gdal_handle_stdcall.GDALDestroyDriverManager()
###############################################################################
# Call OGRCleanupAll()
def OGRCleanupAll():
+ if gdal_handle_stdcall:
+ gdal_handle_stdcall.OGRCleanupAll.argtypes = []
+ gdal_handle_stdcall.OGRCleanupAll.restype = None
- if gdal_handle is None:
- testnonboundtoswig_init()
-
- if gdal_handle is None:
- return 'skip'
-
- gdal_handle_stdcall.OGRCleanupAll.argtypes = []
- gdal_handle_stdcall.OGRCleanupAll.restype = None
-
- gdal_handle_stdcall.OGRCleanupAll()
-
- return 'success'
+ gdal_handle_stdcall.OGRCleanupAll()
###############################################################################
# Call OSRCleanup()
def OSRCleanup():
+ if gdal_handle:
+ gdal_handle.OSRCleanup.argtypes = []
+ gdal_handle.OSRCleanup.restype = None
- if gdal_handle is None:
- testnonboundtoswig_init()
-
- if gdal_handle is None:
- return 'skip'
-
- gdal_handle.OSRCleanup.argtypes = []
- gdal_handle.OSRCleanup.restype = None
-
- gdal_handle.OSRCleanup()
-
- return 'success'
+ gdal_handle.OSRCleanup()
###############################################################################
# Test GDALSimpleImageWarp
-def testnonboundtoswig_GDALSimpleImageWarp():
-
- if gdal_handle is None:
- return 'skip'
+def test_testnonboundtoswig_GDALSimpleImageWarp():
src_ds = gdal.Open('data/byte.tif')
gt = src_ds.GetGeoTransform()
@@ -204,29 +174,20 @@ def testnonboundtoswig_GDALSimpleImageWarp():
filename = bytes(filename, 'utf-8')
native_in_ds = gdal_handle_stdcall.GDALOpen(filename, gdal.GA_ReadOnly)
- if native_in_ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert native_in_ds is not None
filename = '/vsimem/out.tif'
if version_info >= (3, 0, 0):
filename = bytes(filename, 'utf-8')
native_out_ds = gdal_handle_stdcall.GDALOpen(filename, gdal.GA_Update)
- if native_out_ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert native_out_ds is not None
pTransformerArg = gdal_handle.GDALCreateGenImgProjTransformer2(native_in_ds, native_out_ds, None)
- if pTransformerArg is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert pTransformerArg is not None
ret = gdal_handle_stdcall.GDALSimpleImageWarp(native_in_ds, native_out_ds, 0, None, gdal_handle_stdcall.GDALGenImgProjTransform, pTransformerArg, None, None, None)
- if ret != 1:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
+ assert ret == 1
gdal_handle.GDALDestroyGenImgProjTransformer(pTransformerArg)
@@ -239,12 +200,7 @@ def testnonboundtoswig_GDALSimpleImageWarp():
gdal.Unlink('/vsimem/out.tif')
- if cs != 4672:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4672
###############################################################################
# Test VRT derived bands with callback functions implemented in Python!
@@ -272,29 +228,29 @@ def GDALTypeToCTypes(gdaltype):
def my_pyDerivedPixelFunc(papoSources, nSources, pData, nBufXSize, nBufYSize, eSrcType, eBufType, nPixelSpace, nLineSpace):
if nSources != 1:
print(nSources)
- gdaltest.post_reason('did not get expected nSources')
+ print('did not get expected nSources')
return 1
srcctype = GDALTypeToCTypes(eSrcType)
if srcctype is None:
print(eSrcType)
- gdaltest.post_reason('did not get expected eSrcType')
+ print('did not get expected eSrcType')
return 1
dstctype = GDALTypeToCTypes(eBufType)
if dstctype is None:
print(eBufType)
- gdaltest.post_reason('did not get expected eBufType')
+ print('did not get expected eBufType')
return 1
if nPixelSpace != gdal.GetDataTypeSize(eBufType) / 8:
print(nPixelSpace)
- gdaltest.post_reason('did not get expected nPixelSpace')
+ print('did not get expected nPixelSpace')
return 1
if (nLineSpace % nPixelSpace) != 0:
print(nLineSpace)
- gdaltest.post_reason('did not get expected nLineSpace')
+ print('did not get expected nLineSpace')
return 1
nLineStride = (int)(nLineSpace / nPixelSpace)
@@ -308,10 +264,7 @@ def my_pyDerivedPixelFunc(papoSources, nSources, pData, nBufXSize, nBufYSize, eS
return 0
-def testnonboundtoswig_VRTDerivedBands():
-
- if gdal_handle is None:
- return 'skip'
+def test_testnonboundtoswig_VRTDerivedBands():
DerivedPixelFuncType = ctypes.CFUNCTYPE(ctypes.c_int, # ret CPLErr
ctypes.POINTER(ctypes.c_void_p), # void **papoSources
@@ -336,9 +289,7 @@ def testnonboundtoswig_VRTDerivedBands():
if version_info >= (3, 0, 0):
funcName = bytes(funcName, 'utf-8')
ret = gdal_handle_stdcall.GDALAddDerivedBandPixelFunc(funcName, my_cDerivedPixelFunc)
- if ret != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret == 0
vrt_xml = """
@@ -363,28 +314,6 @@ def testnonboundtoswig_VRTDerivedBands():
got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 20, 20)
ds = None
- if ref_cs != got_cs:
- gdaltest.post_reason('wrong checksum')
- print(got_cs)
- return 'fail'
-
- if ref_data != got_data:
- gdaltest.post_reason('wrong data')
- print(ref_data)
- print(got_data)
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = [testnonboundtoswig_init,
- testnonboundtoswig_GDALSimpleImageWarp,
- testnonboundtoswig_VRTDerivedBands]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('testnonboundtoswig')
-
- gdaltest.run_tests(gdaltest_list)
+ assert ref_cs == got_cs, 'wrong checksum'
- sys.exit(gdaltest.summarize())
+ assert ref_data == got_data
diff --git a/autotest/gcore/thread_test.py b/autotest/gcore/thread_test.py
index c7f3ce5460fa..c4ebd7b82f42 100755
--- a/autotest/gcore/thread_test.py
+++ b/autotest/gcore/thread_test.py
@@ -29,13 +29,11 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
import threading
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
+import pytest
def my_error_handler(err_type, err_no, err_msg):
@@ -57,13 +55,13 @@ def thread_test_1_worker(args_dict):
gdal.PopErrorHandler()
-def thread_test_1():
+def test_thread_test_1():
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
except (ImportError, AttributeError):
- return 'skip'
+ pytest.skip()
threads = []
args_array = []
@@ -83,13 +81,5 @@ def thread_test_1():
return ret
-gdaltest_list = [thread_test_1]
-if __name__ == '__main__':
-
- gdaltest.setup_run('thread_test')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/tiff_ovr.py b/autotest/gcore/tiff_ovr.py
index 5f4e303146b4..1a672e9cbdd3 100755
--- a/autotest/gcore/tiff_ovr.py
+++ b/autotest/gcore/tiff_ovr.py
@@ -38,57 +38,62 @@
from osgeo import osr
from osgeo import gdal
-sys.path.append('../pymod')
+import pytest
import gdaltest
+@pytest.fixture(params=['invert', 'dont-invert'])
+def both_endian(request):
+ """
+ Runs tests with both values of GDAL_TIFF_ENDIANNESS
+ """
+ if request.param == 'invert':
+ original = gdal.GetConfigOption('GDAL_TIFF_ENDIANNESS', "NATIVE")
+ gdal.SetConfigOption('GDAL_TIFF_ENDIANNESS', 'INVERTED')
+ yield
+ gdal.SetConfigOption('GDAL_TIFF_ENDIANNESS', original)
+ else:
+ yield
+
+
###############################################################################
# Check the overviews
def tiff_ovr_check(src_ds):
for i in (1, 2, 3):
- if src_ds.GetRasterBand(i).GetOverviewCount() != 2:
- gdaltest.post_reason('overviews missing')
- return 'fail'
+ assert src_ds.GetRasterBand(i).GetOverviewCount() == 2, 'overviews missing'
ovr_band = src_ds.GetRasterBand(i).GetOverview(0)
if ovr_band.XSize != 10 or ovr_band.YSize != 10:
msg = 'overview wrong size: band %d, overview 0, size = %d * %d,' % (i, ovr_band.XSize, ovr_band.YSize)
- gdaltest.post_reason(msg)
- return 'fail'
+ pytest.fail(msg)
if ovr_band.Checksum() != 1087:
msg = 'overview wrong checksum: band %d, overview 0, checksum = %d,' % (i, ovr_band.Checksum())
- gdaltest.post_reason(msg)
- return 'fail'
+ pytest.fail(msg)
ovr_band = src_ds.GetRasterBand(i).GetOverview(1)
if ovr_band.XSize != 5 or ovr_band.YSize != 5:
msg = 'overview wrong size: band %d, overview 1, size = %d * %d,' % (i, ovr_band.XSize, ovr_band.YSize)
- gdaltest.post_reason(msg)
- return 'fail'
+ pytest.fail(msg)
if ovr_band.Checksum() != 328:
msg = 'overview wrong checksum: band %d, overview 1, checksum = %d,' % (i, ovr_band.Checksum())
- gdaltest.post_reason(msg)
- return 'fail'
- return 'success'
-
+ pytest.fail(msg)
+
###############################################################################
# Create a 3 band floating point GeoTIFF file so we can build overviews on it
# later. Build overviews on it.
-def tiff_ovr_1():
+def test_tiff_ovr_1(both_endian):
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/mfloat32.vrt')
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
gdaltest.tiff_drv.CreateCopy('tmp/mfloat32.tif', src_ds,
options=['INTERLEAVE=PIXEL'])
@@ -96,15 +101,11 @@ def tiff_ovr_1():
ds = gdal.Open('tmp/mfloat32.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
err = ds.BuildOverviews(overviewlist=[2, 4])
- if err != 0:
- gdaltest.post_reason('BuildOverviews reports an error')
- return 'fail'
+ assert err == 0, 'BuildOverviews reports an error'
ret = tiff_ovr_check(ds)
@@ -116,13 +117,11 @@ def tiff_ovr_1():
###############################################################################
# Open file and verify some characteristics of the overviews.
-def tiff_ovr_2():
+def test_tiff_ovr_2(both_endian):
src_ds = gdal.Open('tmp/mfloat32.tif')
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
ret = tiff_ovr_check(src_ds)
@@ -134,20 +133,19 @@ def tiff_ovr_2():
# Open target file in update mode, and create internal overviews.
-def tiff_ovr_3():
+def test_tiff_ovr_3(both_endian):
- os.unlink('tmp/mfloat32.tif.ovr')
+ try:
+ os.unlink('tmp/mfloat32.tif.ovr')
+ except OSError:
+ pass
src_ds = gdal.Open('tmp/mfloat32.tif', gdal.GA_Update)
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
err = src_ds.BuildOverviews(overviewlist=[2, 4])
- if err != 0:
- gdaltest.post_reason('BuildOverviews reports an error')
- return 'fail'
+ assert err == 0, 'BuildOverviews reports an error'
ret = tiff_ovr_check(src_ds)
@@ -159,22 +157,20 @@ def tiff_ovr_3():
# Re-open target file and check overviews
-def tiff_ovr_3bis():
- return tiff_ovr_2()
+def test_tiff_ovr_3bis(both_endian):
+ return test_tiff_ovr_2(both_endian)
###############################################################################
# Test generation
-def tiff_ovr_4():
+def test_tiff_ovr_4(both_endian):
shutil.copyfile('data/oddsize_1bit2b.tif', 'tmp/ovr4.tif')
wrk_ds = gdal.Open('tmp/ovr4.tif', gdal.GA_Update)
- if wrk_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert wrk_ds is not None, 'Failed to open test dataset.'
wrk_ds.BuildOverviews('AVERAGE_BIT2GRAYSCALE', overviewlist=[2, 4])
wrk_ds = None
@@ -183,10 +179,8 @@ def tiff_ovr_4():
ovband = wrk_ds.GetRasterBand(1).GetOverview(1)
md = ovband.GetMetadata()
- if 'RESAMPLING' not in md \
- or md['RESAMPLING'] != 'AVERAGE_BIT2GRAYSCALE':
- gdaltest.post_reason('Did not get expected RESAMPLING metadata.')
- return 'fail'
+ assert 'RESAMPLING' in md and md['RESAMPLING'] == 'AVERAGE_BIT2GRAYSCALE', \
+ 'Did not get expected RESAMPLING metadata.'
# compute average value of overview band image data.
ovimage = ovband.ReadRaster(0, 0, ovband.XSize, ovband.YSize)
@@ -206,10 +200,7 @@ def tiff_ovr_4():
average = total / pix_count
exp_average = 153.0656
- if abs(average - exp_average) > 0.1:
- print(average)
- gdaltest.post_reason('got wrong average for overview image')
- return 'fail'
+ assert abs(average - exp_average) <= 0.1, 'got wrong average for overview image'
# Read base band as overview resolution and verify we aren't getting
# the grayscale image.
@@ -229,46 +220,34 @@ def tiff_ovr_4():
average = total / pix_count
exp_average = 0.6096
- if abs(average - exp_average) > 0.01:
- print(average)
- gdaltest.post_reason('got wrong average for downsampled image')
- return 'fail'
+ assert abs(average - exp_average) <= 0.01, 'got wrong average for downsampled image'
wrk_ds = None
- return 'success'
-
###############################################################################
# Test average overview generation with nodata.
-def tiff_ovr_5():
+def test_tiff_ovr_5(both_endian):
shutil.copyfile('data/nodata_byte.tif', 'tmp/ovr5.tif')
wrk_ds = gdal.Open('tmp/ovr5.tif', gdal.GA_ReadOnly)
- if wrk_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert wrk_ds is not None, 'Failed to open test dataset.'
wrk_ds.BuildOverviews('AVERAGE', overviewlist=[2])
cs = wrk_ds.GetRasterBand(1).GetOverview(0).Checksum()
exp_cs = 1130
- if cs != exp_cs:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs, 'got wrong overview checksum.'
###############################################################################
# Same as tiff_ovr_5 but with USE_RDD=YES to force external overview
-def tiff_ovr_6():
+def test_tiff_ovr_6(both_endian):
shutil.copyfile('data/nodata_byte.tif', 'tmp/ovr6.tif')
@@ -277,9 +256,7 @@ def tiff_ovr_6():
wrk_ds = gdal.Open('tmp/ovr6.tif', gdal.GA_Update)
- if wrk_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert wrk_ds is not None, 'Failed to open test dataset.'
wrk_ds.BuildOverviews('AVERAGE', overviewlist=[2])
@@ -288,24 +265,18 @@ def tiff_ovr_6():
try:
os.stat('tmp/ovr6.aux')
except OSError:
- gdaltest.post_reason('no external overview.')
- return 'fail'
+ pytest.fail('no external overview.')
cs = wrk_ds.GetRasterBand(1).GetOverview(0).Checksum()
exp_cs = 1130
- if cs != exp_cs:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs, 'got wrong overview checksum.'
###############################################################################
# Check nearest resampling on a dataset with a raster band that has a color table
-def tiff_ovr_7():
+def test_tiff_ovr_7(both_endian):
shutil.copyfile('data/test_average_palette.tif', 'tmp/test_average_palette.tif')
@@ -313,9 +284,7 @@ def tiff_ovr_7():
# In nearest resampling, we are expecting a uniform black image.
ds = gdal.Open('tmp/test_average_palette.tif', gdal.GA_Update)
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
ds.BuildOverviews('NEAREST', overviewlist=[2])
@@ -324,18 +293,13 @@ def tiff_ovr_7():
ds = None
- if cs != exp_cs:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs, 'got wrong overview checksum.'
###############################################################################
# Check average resampling on a dataset with a raster band that has a color table
-def tiff_ovr_8():
+def test_tiff_ovr_8(both_endian):
shutil.copyfile('data/test_average_palette.tif', 'tmp/test_average_palette.tif')
@@ -344,9 +308,7 @@ def tiff_ovr_8():
# index 2. So the result of the averaging is a uniform grey image.
ds = gdal.Open('tmp/test_average_palette.tif', gdal.GA_Update)
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
ds.BuildOverviews('AVERAGE', overviewlist=[2])
@@ -355,24 +317,20 @@ def tiff_ovr_8():
ds = None
- if cs != exp_cs:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs, 'got wrong overview checksum.'
###############################################################################
# Test --config COMPRESS_OVERVIEW JPEG --config PHOTOMETRIC_OVERVIEW YCBCR -ro
# Will also check that pixel interleaving is automatically selected (#3064)
-def tiff_ovr_9():
+def test_tiff_ovr_9(both_endian):
+ gdaltest.tiff_drv.Delete('tmp/ovr9.tif')
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
shutil.copyfile('data/rgbsmall.tif', 'tmp/ovr9.tif')
@@ -381,9 +339,7 @@ def tiff_ovr_9():
ds = gdal.Open('tmp/ovr9.tif', gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
ds.BuildOverviews('AVERAGE', overviewlist=[2])
@@ -395,10 +351,7 @@ def tiff_ovr_9():
ds = None
- if cs != exp_cs and cs != 5635:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
+ assert cs == exp_cs or cs == 5635, 'got wrong overview checksum.'
# Re-check after dataset reopening
ds = gdal.Open('tmp/ovr9.tif', gdal.GA_ReadOnly)
@@ -408,64 +361,46 @@ def tiff_ovr_9():
ds = None
- if cs != exp_cs and cs != 5635:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs or cs == 5635, 'got wrong overview checksum.'
###############################################################################
# Similar to tiff_ovr_9 but with internal overviews.
-def tiff_ovr_10():
+def test_tiff_ovr_10(both_endian):
src_ds = gdal.Open('data/rgbsmall.tif', gdal.GA_ReadOnly)
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
ds = gdaltest.tiff_drv.CreateCopy('tmp/ovr10.tif', src_ds, options=['COMPRESS=JPEG', 'PHOTOMETRIC=YCBCR'])
src_ds = None
- if ds is None:
- gdaltest.post_reason('Failed to apply JPEG compression.')
- return 'fail'
+ assert ds is not None, 'Failed to apply JPEG compression.'
ds.BuildOverviews('AVERAGE', overviewlist=[2])
ds = None
ds = gdal.Open('tmp/ovr10.tif', gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Failed to open copy of test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open copy of test dataset.'
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
exp_cs = 5562
ds = None
- if cs != exp_cs and cs != 5635:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs or cs == 5635, 'got wrong overview checksum.'
###############################################################################
# Overview on a dataset with NODATA_VALUES
-def tiff_ovr_11():
+def test_tiff_ovr_11(both_endian):
src_ds = gdal.Open('data/test_nodatavalues.tif', gdal.GA_ReadOnly)
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
ds = gdaltest.tiff_drv.CreateCopy('tmp/ovr11.tif', src_ds)
src_ds = None
@@ -484,9 +419,7 @@ def tiff_ovr_11():
ds = None
ds = gdal.Open('tmp/ovr11.tif', gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Failed to open copy of test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open copy of test dataset.'
cs = ds.GetRasterBand(2).GetOverview(0).Checksum()
# If NODATA_VALUES was ignored, we would get 2766
@@ -494,25 +427,18 @@ def tiff_ovr_11():
ds = None
- if cs != exp_cs:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs, 'got wrong overview checksum.'
###############################################################################
# Same as tiff_ovr_11 but with compression to trigger the multiband overview
# code
-def tiff_ovr_12():
+def test_tiff_ovr_12(both_endian):
src_ds = gdal.Open('data/test_nodatavalues.tif', gdal.GA_ReadOnly)
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
ds = gdaltest.tiff_drv.CreateCopy('tmp/ovr12.tif', src_ds, options=['COMPRESS=DEFLATE'])
src_ds = None
@@ -531,9 +457,7 @@ def tiff_ovr_12():
ds = None
ds = gdal.Open('tmp/ovr12.tif', gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Failed to open copy of test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open copy of test dataset.'
cs = ds.GetRasterBand(2).GetOverview(0).Checksum()
# If NODATA_VALUES was ignored, we would get 2766
@@ -541,26 +465,19 @@ def tiff_ovr_12():
ds = None
- if cs != exp_cs:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs, 'got wrong overview checksum.'
###############################################################################
# Test gaussian resampling
-def tiff_ovr_13():
+def test_tiff_ovr_13(both_endian):
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/mfloat32.vrt')
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
gdaltest.tiff_drv.CreateCopy('tmp/mfloat32.tif', src_ds,
options=['INTERLEAVE=PIXEL'])
@@ -568,15 +485,11 @@ def tiff_ovr_13():
ds = gdal.Open('tmp/mfloat32.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
err = ds.BuildOverviews('GAUSS', overviewlist=[2, 4])
- if err != 0:
- gdaltest.post_reason('BuildOverviews reports an error')
- return 'fail'
+ assert err == 0, 'BuildOverviews reports an error'
# if ds.GetRasterBand(1).GetOverview(0).Checksum() != 1225:
# gdaltest.post_reason( 'bad checksum' )
@@ -584,21 +497,17 @@ def tiff_ovr_13():
ds = None
- return 'success'
-
###############################################################################
# Check gauss resampling on a dataset with a raster band that has a color table
-def tiff_ovr_14():
+def test_tiff_ovr_14(both_endian):
shutil.copyfile('data/test_average_palette.tif', 'tmp/test_gauss_palette.tif')
ds = gdal.Open('tmp/test_gauss_palette.tif', gdal.GA_Update)
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
ds.BuildOverviews('GAUSS', overviewlist=[2])
@@ -607,25 +516,18 @@ def tiff_ovr_14():
ds = None
- if cs != exp_cs:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs, 'got wrong overview checksum.'
###############################################################################
# Same as tiff_ovr_11 but with gauss, and compression to trigger the multiband overview
# code
-def tiff_ovr_15():
+def test_tiff_ovr_15(both_endian):
src_ds = gdal.Open('data/test_nodatavalues.tif', gdal.GA_ReadOnly)
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
ds = gdaltest.tiff_drv.CreateCopy('tmp/ovr15.tif', src_ds, options=['COMPRESS=DEFLATE'])
src_ds = None
@@ -644,9 +546,7 @@ def tiff_ovr_15():
ds = None
ds = gdal.Open('tmp/ovr15.tif', gdal.GA_ReadOnly)
- if ds is None:
- gdaltest.post_reason('Failed to open copy of test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open copy of test dataset.'
cs = ds.GetRasterBand(2).GetOverview(0).Checksum()
# If NODATA_VALUES was ignored, we would get 2954
@@ -654,26 +554,19 @@ def tiff_ovr_15():
ds = None
- if cs != exp_cs:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs, 'got wrong overview checksum.'
###############################################################################
# Test mode resampling on non-byte dataset
-def tiff_ovr_16():
+def test_tiff_ovr_16(both_endian):
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
src_ds = gdal.Open('data/mfloat32.vrt')
- if src_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert src_ds is not None, 'Failed to open test dataset.'
gdaltest.tiff_drv.CreateCopy('tmp/ovr16.tif', src_ds,
options=['INTERLEAVE=PIXEL'])
@@ -681,71 +574,51 @@ def tiff_ovr_16():
ds = gdal.Open('tmp/ovr16.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
err = ds.BuildOverviews('MODE', overviewlist=[2, 4])
- if err != 0:
- gdaltest.post_reason('BuildOverviews reports an error')
- return 'fail'
+ assert err == 0, 'BuildOverviews reports an error'
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
exp_cs = 1122
- if cs != exp_cs:
- gdaltest.post_reason('bad checksum')
- print(exp_cs, cs)
- return 'fail'
+ assert cs == exp_cs, 'bad checksum'
ds = None
- return 'success'
-
###############################################################################
# Test mode resampling on a byte dataset
-def tiff_ovr_17():
+def test_tiff_ovr_17(both_endian):
shutil.copyfile('data/byte.tif', 'tmp/ovr17.tif')
ds = gdal.Open('tmp/ovr17.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
err = ds.BuildOverviews('MODE', overviewlist=[2, 4])
- if err != 0:
- gdaltest.post_reason('BuildOverviews reports an error')
- return 'fail'
+ assert err == 0, 'BuildOverviews reports an error'
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
exp_cs = 1122
- if cs != exp_cs:
- gdaltest.post_reason('bad checksum')
- print(exp_cs, cs)
- return 'fail'
+ assert cs == exp_cs, 'bad checksum'
ds = None
- return 'success'
-
###############################################################################
# Check mode resampling on a dataset with a raster band that has a color table
-def tiff_ovr_18():
+def test_tiff_ovr_18(both_endian):
shutil.copyfile('data/test_average_palette.tif', 'tmp/ovr18.tif')
ds = gdal.Open('tmp/ovr18.tif', gdal.GA_Update)
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
ds.BuildOverviews('MODE', overviewlist=[2])
@@ -754,12 +627,7 @@ def tiff_ovr_18():
ds = None
- if cs != exp_cs:
- gdaltest.post_reason('got wrong overview checksum.')
- print(exp_cs, cs)
- return 'fail'
-
- return 'success'
+ assert cs == exp_cs, 'got wrong overview checksum.'
###############################################################################
# Check that we can create overviews on a newly create file (#2621)
@@ -767,12 +635,12 @@ def tiff_ovr_18():
# if BigTIFF is not supported (this is a sign of an older libtiff...)
-def tiff_ovr_19():
+def test_tiff_ovr_19(both_endian):
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.GetDriverByName('GTiff').Create('tmp/ovr19.tif', 100, 100, 1)
ds.GetRasterBand(1).Fill(1)
@@ -783,43 +651,34 @@ def tiff_ovr_19():
ds.FlushCache()
ds.BuildOverviews('NEAR', overviewlist=[2, 4])
- if ds.GetRasterBand(1).GetOverviewCount() != 2 is None:
- print('Overview could not be generated')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 2, \
+ 'Overview could not be generated'
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs != 2500:
- print(cs)
- return 'fail'
+ assert cs == 2500
cs = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs != 625:
- print(cs)
- return 'fail'
+ assert cs == 625
ds = None
- return 'success'
-
###############################################################################
# Test BIGTIFF_OVERVIEW=YES option
-def tiff_ovr_20():
+def test_tiff_ovr_20(both_endian):
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/ovr20.tif', 100, 100, 1)
ds = None
ds = gdal.Open('tmp/ovr20.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
gdal.SetConfigOption('BIGTIFF_OVERVIEW', 'YES')
ds.BuildOverviews('NEAREST', overviewlist=[2, 4])
@@ -833,31 +692,26 @@ def tiff_ovr_20():
fileobj.close()
# Check BigTIFF signature
- if ((binvalues[2] != 0x2B or binvalues[3] != 0) and
- (binvalues[3] != 0x2B or binvalues[2] != 0)):
- return 'fail'
-
- return 'success'
+ assert (not ((binvalues[2] != 0x2B or binvalues[3] != 0) and
+ (binvalues[3] != 0x2B or binvalues[2] != 0)))
###############################################################################
# Test BIGTIFF_OVERVIEW=IF_NEEDED option
-def tiff_ovr_21():
+def test_tiff_ovr_21(both_endian):
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/ovr21.tif', 170000, 100000, 1, options=['SPARSE_OK=YES'])
ds = None
ds = gdal.Open('tmp/ovr21.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
# 170 k * 100 k = 17 GB. 17 GB / (2^2) = 4.25 GB > 4.2 GB
# so BigTIFF is needed
@@ -871,31 +725,26 @@ def tiff_ovr_21():
fileobj.close()
# Check BigTIFF signature
- if ((binvalues[2] != 0x2B or binvalues[3] != 0) and
- (binvalues[3] != 0x2B or binvalues[2] != 0)):
- return 'fail'
-
- return 'success'
+ assert (not ((binvalues[2] != 0x2B or binvalues[3] != 0) and
+ (binvalues[3] != 0x2B or binvalues[2] != 0)))
###############################################################################
# Test BIGTIFF_OVERVIEW=NO option when BigTIFF is really needed
-def tiff_ovr_22():
+def test_tiff_ovr_22(both_endian):
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/ovr22.tif', 170000, 100000, 1, options=['SPARSE_OK=YES'])
ds = None
ds = gdal.Open('tmp/ovr22.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
# 170 k * 100 k = 17 GB. 17 GB / (2^2) = 4.25 GB > 4.2 GB
# so BigTIFF is needed
@@ -908,29 +757,27 @@ def tiff_ovr_22():
ds = None
if err != 0:
- return 'success'
- return 'fail'
+ return
+ pytest.fail()
###############################################################################
# Same as before, but BigTIFF might be not needed as we use a compression
# method for the overviews.
-def tiff_ovr_23():
+def test_tiff_ovr_23(both_endian):
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/ovr23.tif', 170000, 100000, 1, options=['SPARSE_OK=YES'])
ds = None
ds = gdal.Open('tmp/ovr23.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
gdal.SetConfigOption('BIGTIFF_OVERVIEW', 'NO')
gdal.SetConfigOption('COMPRESS_OVERVIEW', 'DEFLATE')
@@ -946,31 +793,26 @@ def tiff_ovr_23():
fileobj.close()
# Check Classical TIFF signature
- if ((binvalues[2] != 0x2A or binvalues[3] != 0) and
- (binvalues[3] != 0x2A or binvalues[2] != 0)):
- return 'fail'
-
- return 'success'
+ assert (not ((binvalues[2] != 0x2A or binvalues[3] != 0) and
+ (binvalues[3] != 0x2A or binvalues[2] != 0)))
###############################################################################
# Test BIGTIFF_OVERVIEW=IF_SAFER option
-def tiff_ovr_24():
+def test_tiff_ovr_24(both_endian):
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/ovr24.tif', 85000, 100000, 1, options=['SPARSE_OK=YES'])
ds = None
ds = gdal.Open('tmp/ovr24.tif')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
# 85 k * 100 k = 8.5 GB, so BigTIFF might be needed as
# 8.5 GB / 2 > 4.2 GB
@@ -986,18 +828,15 @@ def tiff_ovr_24():
fileobj.close()
# Check BigTIFF signature
- if ((binvalues[2] != 0x2B or binvalues[3] != 0) and
- (binvalues[3] != 0x2B or binvalues[2] != 0)):
- return 'fail'
-
- return 'success'
+ assert (not ((binvalues[2] != 0x2B or binvalues[3] != 0) and
+ (binvalues[3] != 0x2B or binvalues[2] != 0)))
###############################################################################
# Test creating overviews after some blocks have been written in the main
# band and actually flushed
-def tiff_ovr_25():
+def test_tiff_ovr_25(both_endian):
ds = gdaltest.tiff_drv.Create('tmp/ovr25.tif', 100, 100, 1)
ds.GetRasterBand(1).Fill(1)
@@ -1006,25 +845,19 @@ def tiff_ovr_25():
ds = None
ds = gdal.Open('tmp/ovr25.tif')
- if ds is None:
- return 'fail'
-
- if ds.GetRasterBand(1).Checksum() != 10000:
- return 'fail'
+ assert ds is not None
- if ds.GetRasterBand(1).GetOverviewCount() == 0:
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 10000
- if ds.GetRasterBand(1).GetOverview(0).Checksum() != 2500:
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() != 0
- return 'success'
+ assert ds.GetRasterBand(1).GetOverview(0).Checksum() == 2500
###############################################################################
# Test gdal.RegenerateOverview()
-def tiff_ovr_26():
+def test_tiff_ovr_26(both_endian):
ds = gdaltest.tiff_drv.Create('tmp/ovr26.tif', 100, 100, 1)
ds.GetRasterBand(1).Fill(1)
@@ -1033,21 +866,17 @@ def tiff_ovr_26():
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
ds.GetRasterBand(1).GetOverview(0).Fill(0)
cs_new = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs_new != 0:
- return 'fail'
+ assert cs_new == 0
gdal.RegenerateOverview(ds.GetRasterBand(1), ds.GetRasterBand(1).GetOverview(0), 'NEAR')
cs_new = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs != cs_new:
- return 'fail'
+ assert cs == cs_new
ds = None
- return 'success'
-
###############################################################################
# Test gdal.RegenerateOverviews()
-def tiff_ovr_27():
+def test_tiff_ovr_27(both_endian):
ds = gdaltest.tiff_drv.Create('tmp/ovr27.tif', 100, 100, 1)
ds.GetRasterBand(1).Fill(1)
@@ -1059,48 +888,38 @@ def tiff_ovr_27():
ds.GetRasterBand(1).GetOverview(1).Fill(0)
cs_new = ds.GetRasterBand(1).GetOverview(0).Checksum()
cs2_new = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs_new != 0 or cs2_new != 0:
- return 'fail'
+ assert cs_new == 0 and cs2_new == 0
gdal.RegenerateOverviews(ds.GetRasterBand(1), [ds.GetRasterBand(1).GetOverview(0), ds.GetRasterBand(1).GetOverview(1)], 'NEAR')
cs_new = ds.GetRasterBand(1).GetOverview(0).Checksum()
cs2_new = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs != cs_new:
- return 'fail'
- if cs2 != cs2_new:
- return 'fail'
+ assert cs == cs_new
+ assert cs2 == cs2_new
ds = None
- return 'success'
-
###############################################################################
# Test cleaning overviews.
-def tiff_ovr_28():
+def test_tiff_ovr_28(both_endian):
ds = gdal.Open('tmp/ovr25.tif', gdal.GA_Update)
- if ds.BuildOverviews(overviewlist=[]) != 0:
- gdaltest.post_reason('BuildOverviews() returned error code.')
- return 'fail'
+ assert ds.BuildOverviews(overviewlist=[]) == 0, \
+ 'BuildOverviews() returned error code.'
- if ds.GetRasterBand(1).GetOverviewCount() != 0:
- gdaltest.post_reason('Overview(s) appear to still exist.')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 0, \
+ 'Overview(s) appear to still exist.'
# Close and reopen to confirm they are really gone.
ds = None
ds = gdal.Open('tmp/ovr25.tif')
- if ds.GetRasterBand(1).GetOverviewCount() != 0:
- gdaltest.post_reason('Overview(s) appear to still exist after reopen.')
- return 'fail'
-
- return 'success'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 0, \
+ 'Overview(s) appear to still exist after reopen.'
###############################################################################
# Test cleaning external overviews (ovr) on a non-TIFF format.
-def tiff_ovr_29():
+def test_tiff_ovr_29(both_endian):
src_ds = gdal.Open('data/byte.tif')
png_ds = gdal.GetDriverByName('PNG').CreateCopy('tmp/ovr29.png', src_ds)
@@ -1109,46 +928,33 @@ def tiff_ovr_29():
png_ds.BuildOverviews(overviewlist=[2])
png_ds = None
- if open('tmp/ovr29.png.ovr') is None:
- gdaltest.post_reason('Did not expected .ovr file.')
- return 'fail'
+ assert open('tmp/ovr29.png.ovr') is not None, 'Did not expected .ovr file.'
png_ds = gdal.Open('tmp/ovr29.png')
- if png_ds.GetRasterBand(1).GetOverviewCount() != 1:
- gdaltest.post_reason('did not find overview')
- return 'fail'
+ assert png_ds.GetRasterBand(1).GetOverviewCount() == 1, 'did not find overview'
png_ds.BuildOverviews(overviewlist=[])
- if png_ds.GetRasterBand(1).GetOverviewCount() != 0:
- gdaltest.post_reason('delete overview failed.')
- return 'fail'
+ assert png_ds.GetRasterBand(1).GetOverviewCount() == 0, 'delete overview failed.'
png_ds = None
png_ds = gdal.Open('tmp/ovr29.png')
- if png_ds.GetRasterBand(1).GetOverviewCount() != 0:
- gdaltest.post_reason('delete overview failed.')
- return 'fail'
+ assert png_ds.GetRasterBand(1).GetOverviewCount() == 0, 'delete overview failed.'
png_ds = None
- try:
+ with pytest.raises(OSError, message='.ovr file still present'):
os.stat('tmp/ovr29.png.ovr')
- gdaltest.post_reason('.ovr file still present')
- return 'fail'
- except OSError:
- pass
+
gdal.GetDriverByName('PNG').Delete('tmp/ovr29.png')
- return 'success'
-
###############################################################################
# Test fix for #2988.
-def tiff_ovr_30():
+def test_tiff_ovr_30(both_endian):
ds = gdaltest.tiff_drv.Create('tmp/ovr30.tif', 20, 20, 1)
ds.BuildOverviews(overviewlist=[2])
@@ -1169,16 +975,13 @@ def tiff_ovr_30():
ds = None
ds = gdal.Open('tmp/ovr30.tif')
- if ds.GetProjectionRef().find('4326') == -1:
- return 'fail'
-
- return 'success'
+ assert ds.GetProjectionRef().find('4326') != -1
###############################################################################
# Test fix for #3033
-def tiff_ovr_31():
+def test_tiff_ovr_31(both_endian):
ds = gdaltest.tiff_drv.Create('tmp/ovr31.tif', 100, 100, 4)
ds.GetRasterBand(1).Fill(255)
@@ -1188,23 +991,20 @@ def tiff_ovr_31():
ds.BuildOverviews('average', overviewlist=[2, 4])
cs = ds.GetRasterBand(1).GetOverview(1).Checksum()
expected_cs = 7646
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d' % (cs, expected_cs))
ds = None
- return 'success'
-
###############################################################################
# Test Cubic sampling.
-def tiff_ovr_32():
+def test_tiff_ovr_32(both_endian):
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
# 4 regular band
shutil.copyfile('data/stefan_full_rgba_photometric_rgb.tif', 'tmp/ovr32.tif')
@@ -1214,15 +1014,13 @@ def tiff_ovr_32():
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
expected_cs = 21168
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
cs = ds.GetRasterBand(3).GetOverview(1).Checksum()
expected_cs = 1851
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 1.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 1.' % (cs, expected_cs))
ds = None
@@ -1245,9 +1043,8 @@ def tiff_ovr_32():
cs = tmp2_ds.GetRasterBand(1).GetOverview(0).Checksum()
expected_cs = 21168
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
src_ds = None
tmp_ds = None
@@ -1267,15 +1064,13 @@ def tiff_ovr_32():
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
expected_cs = 21168
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
cs = ds.GetRasterBand(3).GetOverview(1).Checksum()
expected_cs = 1851
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 1.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 1.' % (cs, expected_cs))
ds = None
@@ -1289,15 +1084,13 @@ def tiff_ovr_32():
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
expected_cs = 21656
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
cs = ds.GetRasterBand(3).GetOverview(1).Checksum()
expected_cs = 2132
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 1.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 1.' % (cs, expected_cs))
ds = None
@@ -1321,9 +1114,8 @@ def tiff_ovr_32():
cs = tmp2_ds.GetRasterBand(1).GetOverview(0).Checksum()
# expected_cs = 21656
expected_cs = 21168
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
src_ds = None
tmp_ds = None
@@ -1338,27 +1130,23 @@ def tiff_ovr_32():
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
expected_cs = 21656
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 0.' % (cs, expected_cs))
cs = ds.GetRasterBand(3).GetOverview(1).Checksum()
expected_cs = 2132
- if cs != expected_cs:
- gdaltest.post_reason('Checksum is %d. Expected checksum is %d for overview 1.' % (cs, expected_cs))
- return 'fail'
+ assert cs == expected_cs, \
+ ('Checksum is %d. Expected checksum is %d for overview 1.' % (cs, expected_cs))
ds = None
gdaltest.tiff_drv.Delete('tmp/ovr32.tif')
- return 'success'
-
###############################################################################
# Test creation of overviews on a 1x1 dataset (fix for #3069)
-def tiff_ovr_33():
+def test_tiff_ovr_33(both_endian):
try:
os.remove('tmp/ovr33.tif.ovr')
@@ -1373,13 +1161,11 @@ def tiff_ovr_33():
gdaltest.tiff_drv.Delete('tmp/ovr33.tif')
- return 'success'
-
###############################################################################
# Confirm that overviews are used on a Band.RasterIO().
-def tiff_ovr_34():
+def test_tiff_ovr_34(both_endian):
ds_in = gdal.Open('data/byte.tif')
ds = gdaltest.tiff_drv.CreateCopy('tmp/ovr34.tif', ds_in)
@@ -1393,19 +1179,16 @@ def tiff_ovr_34():
ds = None
if data != ' '.encode('ascii'):
- gdaltest.post_reason('did not get expected cleared overview.')
print('[%s]' % data)
- return 'fail'
+ pytest.fail('did not get expected cleared overview.')
gdaltest.tiff_drv.Delete('tmp/ovr34.tif')
- return 'success'
-
###############################################################################
# Confirm that overviews are used on a Band.RasterIO().
-def tiff_ovr_35():
+def test_tiff_ovr_35(both_endian):
ds_in = gdal.Open('data/byte.tif')
ds = gdaltest.tiff_drv.CreateCopy('tmp/ovr35.tif', ds_in)
@@ -1419,24 +1202,21 @@ def tiff_ovr_35():
ds = None
if data != ' '.encode('ascii'):
- gdaltest.post_reason('did not get expected cleared overview.')
print('[%s]' % data)
- return 'fail'
+ pytest.fail('did not get expected cleared overview.')
gdaltest.tiff_drv.Delete('tmp/ovr35.tif')
- return 'success'
-
###############################################################################
# Confirm that overviews are used on a Band.RasterIO() when using BlockBasedRasterIO() (#3124)
-def tiff_ovr_36():
+def test_tiff_ovr_36(both_endian):
oldval = gdal.GetConfigOption('GDAL_FORCE_CACHING', 'NO')
gdal.SetConfigOption('GDAL_FORCE_CACHING', 'YES')
- ret = tiff_ovr_35()
+ ret = test_tiff_ovr_35(both_endian)
gdal.SetConfigOption('GDAL_FORCE_CACHING', oldval)
@@ -1446,15 +1226,13 @@ def tiff_ovr_36():
# Test PREDICTOR_OVERVIEW=2 option. (#3414)
-def tiff_ovr_37():
+def test_tiff_ovr_37(both_endian):
shutil.copy('../gdrivers/data/n43.dt0', 'tmp/ovr37.dt0')
ds = gdal.Open('tmp/ovr37.dt0')
- if ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert ds is not None, 'Failed to open test dataset.'
gdal.SetConfigOption('PREDICTOR_OVERVIEW', '2')
gdal.SetConfigOption('COMPRESS_OVERVIEW', 'LZW')
@@ -1466,32 +1244,24 @@ def tiff_ovr_37():
ds = gdal.Open('tmp/ovr37.dt0')
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs != 45378:
- print(cs)
- gdaltest.post_reason('got wrong overview checksum.')
- return 'fail'
+ assert cs == 45378, 'got wrong overview checksum.'
ds = None
predictor2_size = os.stat('tmp/ovr37.dt0.ovr')[stat.ST_SIZE]
# 3957 : on little-endian host
# XXXX : on big-endian host ??? FIXME: To be updated
- if predictor2_size != 3957:
- print(predictor2_size)
- gdaltest.post_reason('did not get expected file size.')
- return 'fail'
-
- return 'success'
+ assert predictor2_size == 3957, 'did not get expected file size.'
###############################################################################
# Test that the predictor flag gets well propagated to internal overviews
-def tiff_ovr_38():
+def test_tiff_ovr_38(both_endian):
# Skip with old libtiff (crash with 3.8.2)
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
src_ds = gdal.Open('../gdrivers/data/n43.dt0')
ds = gdaltest.tiff_drv.CreateCopy('tmp/ovr38.tif', src_ds, options=['COMPRESS=LZW', 'PREDICTOR=2'])
@@ -1500,18 +1270,13 @@ def tiff_ovr_38():
file_size = os.stat('tmp/ovr38.tif')[stat.ST_SIZE]
- if file_size > 21000:
- print(file_size)
- gdaltest.post_reason('did not get expected file size.')
- return 'fail'
-
- return 'success'
+ assert file_size <= 21000, 'did not get expected file size.'
###############################################################################
# Test external overviews on all datatypes
-def tiff_ovr_39():
+def test_tiff_ovr_39(both_endian):
for datatype in [gdal.GDT_Byte,
gdal.GDT_Int16,
@@ -1539,9 +1304,7 @@ def tiff_ovr_39():
ovr_datatype = ds.GetRasterBand(1).DataType
ds = None
- if datatype != ovr_datatype:
- gdaltest.post_reason('did not get expected datatype')
- return 'fail'
+ assert datatype == ovr_datatype, 'did not get expected datatype'
ds = gdal.Open('tmp/ovr39.tif')
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
@@ -1552,26 +1315,21 @@ def tiff_ovr_39():
else:
expected_cs = 1087
- if cs != expected_cs:
- gdaltest.post_reason('did not get expected checksum for datatype %s' % gdal.GetDataTypeName(datatype))
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == expected_cs, \
+ ('did not get expected checksum for datatype %s' % gdal.GetDataTypeName(datatype))
+
###############################################################################
# Test external overviews on 1 bit datasets with AVERAGE_BIT2GRAYSCALE (similar to tiff_ovr_4)
-def tiff_ovr_40():
+def test_tiff_ovr_40(both_endian):
shutil.copyfile('data/oddsize_1bit2b.tif', 'tmp/ovr40.tif')
wrk_ds = gdal.Open('tmp/ovr40.tif')
- if wrk_ds is None:
- gdaltest.post_reason('Failed to open test dataset.')
- return 'fail'
+ assert wrk_ds is not None, 'Failed to open test dataset.'
wrk_ds.BuildOverviews('AVERAGE_BIT2GRAYSCALE', overviewlist=[2, 4])
wrk_ds = None
@@ -1580,10 +1338,8 @@ def tiff_ovr_40():
ovband = wrk_ds.GetRasterBand(1).GetOverview(1)
md = ovband.GetMetadata()
- if 'RESAMPLING' not in md \
- or md['RESAMPLING'] != 'AVERAGE_BIT2GRAYSCALE':
- gdaltest.post_reason('Did not get expected RESAMPLING metadata.')
- return 'fail'
+ assert 'RESAMPLING' in md and md['RESAMPLING'] == 'AVERAGE_BIT2GRAYSCALE', \
+ 'Did not get expected RESAMPLING metadata.'
# compute average value of overview band image data.
ovimage = ovband.ReadRaster(0, 0, ovband.XSize, ovband.YSize)
@@ -1603,10 +1359,7 @@ def tiff_ovr_40():
average = total / pix_count
exp_average = 153.0656
- if abs(average - exp_average) > 0.1:
- print(average)
- gdaltest.post_reason('got wrong average for overview image')
- return 'fail'
+ assert abs(average - exp_average) <= 0.1, 'got wrong average for overview image'
# Read base band as overview resolution and verify we aren't getting
# the grayscale image.
@@ -1626,20 +1379,15 @@ def tiff_ovr_40():
average = total / pix_count
exp_average = 0.6096
- if abs(average - exp_average) > 0.01:
- print(average)
- gdaltest.post_reason('got wrong average for downsampled image')
- return 'fail'
+ assert abs(average - exp_average) <= 0.01, 'got wrong average for downsampled image'
wrk_ds = None
- return 'success'
-
###############################################################################
# Test external overviews on 1 bit datasets with NEAREST
-def tiff_ovr_41():
+def test_tiff_ovr_41(both_endian):
shutil.copyfile('data/oddsize_1bit2b.tif', 'tmp/ovr41.tif')
@@ -1656,18 +1404,13 @@ def tiff_ovr_41():
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
ds = None
- if cs != 1496:
- print(cs)
- gdaltest.post_reason('did not get expected checksum')
- return 'fail'
-
- return 'success'
+ assert cs == 1496, 'did not get expected checksum'
###############################################################################
# Test external overviews on dataset with color table
-def tiff_ovr_42():
+def test_tiff_ovr_42(both_endian):
ct_data = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)]
@@ -1686,28 +1429,24 @@ def tiff_ovr_42():
ds = gdal.Open('tmp/ovr42.tif.ovr')
ct2 = ds.GetRasterBand(1).GetRasterColorTable()
- if ct2.GetCount() != 256 or \
- ct2.GetColorEntry(0) != (255, 0, 0, 255) or \
- ct2.GetColorEntry(1) != (0, 255, 0, 255) or \
- ct2.GetColorEntry(2) != (0, 0, 255, 255) or \
- ct2.GetColorEntry(3) != (255, 255, 255, 255):
- gdaltest.post_reason('Wrong color table entry.')
- return 'fail'
+ assert (ct2.GetCount() == 256 and \
+ ct2.GetColorEntry(0) == (255, 0, 0, 255) and \
+ ct2.GetColorEntry(1) == (0, 255, 0, 255) and \
+ ct2.GetColorEntry(2) == (0, 0, 255, 255) and \
+ ct2.GetColorEntry(3) == (255, 255, 255, 255)), 'Wrong color table entry.'
ds = None
- return 'success'
-
###############################################################################
# Make sure that 16bit overviews with JPEG compression are handled using 12-bit
# jpeg-in-tiff (#3539)
-def tiff_ovr_43():
+def test_tiff_ovr_43(both_endian):
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
old_accum = gdal.GetConfigOption('CPL_ACCUM_ERROR_MSG', 'OFF')
gdal.SetConfigOption('CPL_ACCUM_ERROR_MSG', 'ON')
@@ -1726,7 +1465,7 @@ def tiff_ovr_43():
if gdal.GetLastErrorMsg().find(
'Unsupported JPEG data precision 12') != -1:
sys.stdout.write('(12bit jpeg not available) ... ')
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/ovr43.tif', 16, 16, 1, gdal.GDT_UInt16)
ds.GetRasterBand(1).Fill(4000)
@@ -1748,26 +1487,18 @@ def tiff_ovr_43():
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if 'NBITS' not in md or md['NBITS'] != '12':
- print(md)
- gdaltest.post_reason('did not get expected NBITS')
- return 'fail'
+ assert 'NBITS' in md and md['NBITS'] == '12', 'did not get expected NBITS'
- if cs != 642:
- print(cs)
- gdaltest.post_reason('did not get expected checksum')
- return 'fail'
+ assert cs == 642, 'did not get expected checksum'
gdaltest.tiff_drv.Delete('tmp/ovr43.tif')
- return 'success'
-
###############################################################################
# Test that we can change overview block size through GDAL_TIFF_OVR_BLOCKSIZE configuration
# option
-def tiff_ovr_44():
+def test_tiff_ovr_44(both_endian):
shutil.copyfile('data/byte.tif', 'tmp/ovr44.tif')
gdal.SetConfigOption('GDAL_TIFF_OVR_BLOCKSIZE', '256')
@@ -1780,26 +1511,19 @@ def tiff_ovr_44():
ovr_band = ds.GetRasterBand(1).GetOverview(0)
if 'GetBlockSize' in dir(gdal.Band):
(blockx, blocky) = ovr_band.GetBlockSize()
- if blockx != 256 or blocky != 256:
- gdaltest.post_reason('did not get expected block size')
- return 'fail'
+ assert blockx == 256 and blocky == 256, 'did not get expected block size'
cs = ovr_band.Checksum()
ds = None
gdaltest.tiff_drv.Delete('tmp/ovr44.tif')
- if cs != 1087:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 1087, 'did not get expected checksum'
###############################################################################
# Same as tiff_ovr_44, but with external overviews
-def tiff_ovr_45():
+def test_tiff_ovr_45(both_endian):
shutil.copyfile('data/byte.tif', 'tmp/ovr45.tif')
gdal.SetConfigOption('GDAL_TIFF_OVR_BLOCKSIZE', '256')
@@ -1812,33 +1536,26 @@ def tiff_ovr_45():
ovr_band = ds.GetRasterBand(1)
if 'GetBlockSize' in dir(gdal.Band):
(blockx, blocky) = ovr_band.GetBlockSize()
- if blockx != 256 or blocky != 256:
- gdaltest.post_reason('did not get expected block size')
- return 'fail'
+ assert blockx == 256 and blocky == 256, 'did not get expected block size'
cs = ovr_band.Checksum()
ds = None
gdaltest.tiff_drv.Delete('tmp/ovr45.tif')
- if cs != 1087:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 1087, 'did not get expected checksum'
###############################################################################
# Test overview on a dataset where width * height > 2 billion
-def tiff_ovr_46():
+def test_tiff_ovr_46():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
# Test NEAREST
gdal.SetConfigOption('GTIFF_DONT_WRITE_BLOCKS', 'YES')
@@ -1922,13 +1639,11 @@ def tiff_ovr_46():
gdaltest.tiff_drv.Delete('/vsimem/tiff_ovr_46.tif')
- return 'success'
-
###############################################################################
# Test workaround with libtiff 3.X when creating interleaved overviews
-def tiff_ovr_47():
+def test_tiff_ovr_47(both_endian):
mem_drv = gdal.GetDriverByName('MEM')
mem_ds = mem_drv.Create('', 852, 549, 3)
@@ -1948,18 +1663,13 @@ def tiff_ovr_47():
gdal.Unlink("/vsimem/tiff_ovr_47.tif")
- if cs != 35721:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 35721, 'did not get expected checksum'
###############################################################################
# Test that we don't average 0's in alpha band
-def tiff_ovr_48():
+def test_tiff_ovr_48(both_endian):
shutil.copy('data/rgba_with_alpha_0_and_255.tif', 'tmp')
ds = gdal.Open('tmp/rgba_with_alpha_0_and_255.tif')
@@ -1969,9 +1679,7 @@ def tiff_ovr_48():
ds = gdal.Open('tmp/rgba_with_alpha_0_and_255.tif.ovr')
for i in range(4):
cs = ds.GetRasterBand(i + 1).Checksum()
- if cs != 3:
- print(i)
- return 'fail'
+ assert cs == 3, i
# But if we define GDAL_OVR_PROPAGATE_NODATA, a nodata value in source
# samples will cause the target pixel to be zeroed.
@@ -1985,17 +1693,14 @@ def tiff_ovr_48():
ds = gdal.Open('tmp/rgba_with_alpha_0_and_255.tif.ovr')
for i in range(4):
cs = ds.GetRasterBand(i + 1).Checksum()
- if cs != 0:
- print(i)
- return 'fail'
-
- return 'success'
+ assert cs == 0, i
+
###############################################################################
# Test possible stride computation issue in GDALRegenerateOverviewsMultiBand (#5653)
-def tiff_ovr_49():
+def test_tiff_ovr_49(both_endian):
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_ovr_49.tif', 1023, 1023, 1)
ds.GetRasterBand(1).Fill(0)
@@ -2010,19 +1715,15 @@ def tiff_ovr_49():
gdal.SetConfigOption('COMPRESS_OVERVIEW', None)
ds = None
ds = gdal.Open('/vsimem/tiff_ovr_49.tif.ovr')
- if ds.GetRasterBand(1).Checksum() == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() != 0
ds = None
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_ovr_49.tif')
- return 'success'
-
###############################################################################
# Test overviews when X dimension is smaller than Y (#5794)
-def tiff_ovr_50():
+def test_tiff_ovr_50(both_endian):
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_ovr_50.tif', 6, 8192, 3,
options=['COMPRESS=DEFLATE'])
@@ -2033,17 +1734,15 @@ def tiff_ovr_50():
ds = None
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_ovr_50.tif')
- return 'success'
-
###############################################################################
# Test average overview on a color palette with nodata values (#6371)
-def tiff_ovr_51():
+def test_tiff_ovr_51():
src_ds = gdal.Open('data/stefan_full_rgba_pct32.png')
if src_ds is None:
- return 'skip'
+ pytest.skip()
ds = gdal.GetDriverByName('PNG').CreateCopy('/vsimem/tiff_ovr_51.png', src_ds)
ds.BuildOverviews('AVERAGE', [2])
@@ -2051,24 +1750,20 @@ def tiff_ovr_51():
ds = gdal.Open('/vsimem/tiff_ovr_51.png.ovr')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 24518:
- print(cs)
- return 'fail'
+ assert cs == 24518
ds = None
gdal.GetDriverByName('PNG').Delete('/vsimem/tiff_ovr_51.png')
- return 'success'
-
###############################################################################
# Test unsorted external overview building (#6617)
-def tiff_ovr_52():
+def test_tiff_ovr_52():
src_ds = gdal.Open('data/byte.tif')
if src_ds is None:
- return 'skip'
+ pytest.skip()
gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/tiff_ovr_52.tif', src_ds)
gdal.SetConfigOption('COMPRESS_OVERVIEW', 'DEFLATE')
@@ -2084,15 +1779,9 @@ def tiff_ovr_52():
ds = gdal.Open('/vsimem/tiff_ovr_52.tif')
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs != 328:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 328
cs = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs != 1087:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 1087
ds = None
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_ovr_52.tif')
@@ -2108,30 +1797,22 @@ def tiff_ovr_52():
ds = gdal.Open('/vsimem/tiff_ovr_52.tif')
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs != 328:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 328
cs = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs != 1087:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 1087
ds = None
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_ovr_52.tif')
- return 'success'
-
###############################################################################
# Test external overviews building in several steps
-def tiff_ovr_53():
+def test_tiff_ovr_53():
src_ds = gdal.Open('data/byte.tif')
if src_ds is None:
- return 'skip'
+ pytest.skip()
gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/tiff_ovr_53.tif', src_ds)
ds = gdal.Open('/vsimem/tiff_ovr_53.tif')
@@ -2145,15 +1826,9 @@ def tiff_ovr_53():
ds = gdal.Open('/vsimem/tiff_ovr_53.tif')
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs != 1087:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 1087
cs = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs != 328:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 328
ds = None
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_ovr_53.tif')
@@ -2175,31 +1850,23 @@ def tiff_ovr_53():
ds = gdal.Open('/vsimem/tiff_ovr_53.tif')
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs != 1087:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 1087
cs = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs != 328:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 328
ds = None
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_ovr_53.tif')
- return 'success'
-
###############################################################################
# Test external overviews building in several steps with jpeg compression
-def tiff_ovr_54():
+def test_tiff_ovr_54():
drv = gdal.GetDriverByName('GTiff')
md = drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
src_ds = gdal.Open('../gdrivers/data/small_world.tif')
gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/tiff_ovr_54.tif', src_ds)
@@ -2224,83 +1891,57 @@ def tiff_ovr_54():
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_ovr_54.tif')
- if cs0 == 0 or cs1 == 0:
- gdaltest.post_reason('fail')
- print(cs0, cs1)
- return 'fail'
-
- return 'success'
+ assert not (cs0 == 0 or cs1 == 0)
###############################################################################
-def tiff_ovr_too_many_levels_contig():
+def test_tiff_ovr_too_many_levels_contig():
src_ds = gdal.Open('data/byte.tif')
tmpfilename = '/vsimem/tiff_ovr_too_many_levels_contig.tif'
ds = gdal.GetDriverByName('GTiff').CreateCopy(tmpfilename, src_ds)
ds.BuildOverviews('AVERAGE', [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096])
- if ds.GetRasterBand(1).GetOverviewCount() != 5:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetOverviewCount())
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 5
ds.BuildOverviews('AVERAGE', [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096])
- if ds.GetRasterBand(1).GetOverviewCount() != 5:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 5
ds = None
gdal.GetDriverByName('GTiff').Delete(tmpfilename)
- return 'success'
-
###############################################################################
-def tiff_ovr_too_many_levels_separate():
+def test_tiff_ovr_too_many_levels_separate():
src_ds = gdal.Open('data/separate_tiled.tif')
tmpfilename = '/vsimem/tiff_ovr_too_many_levels_separate.tif'
ds = gdal.GetDriverByName('GTiff').CreateCopy(tmpfilename, src_ds)
ds.BuildOverviews('AVERAGE', [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096])
- if ds.GetRasterBand(1).GetOverviewCount() != 6:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetOverviewCount())
- return 'fail'
- if ds.GetRasterBand(1).GetOverviewCount() != 6:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetOverviewCount())
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 6
+ assert ds.GetRasterBand(1).GetOverviewCount() == 6
ds = None
gdal.GetDriverByName('GTiff').Delete(tmpfilename)
- return 'success'
-
###############################################################################
-def tiff_ovr_too_many_levels_external():
+def test_tiff_ovr_too_many_levels_external():
src_ds = gdal.Open('data/byte.tif')
tmpfilename = '/vsimem/tiff_ovr_too_many_levels_contig.tif'
gdal.GetDriverByName('GTiff').CreateCopy(tmpfilename, src_ds)
ds = gdal.Open(tmpfilename)
ds.BuildOverviews('AVERAGE', [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096])
- if ds.GetRasterBand(1).GetOverviewCount() != 5:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 5
ds.BuildOverviews('AVERAGE', [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096])
- if ds.GetRasterBand(1).GetOverviewCount() != 5:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 5
ds = None
gdal.GetDriverByName('GTiff').Delete(tmpfilename)
- return 'success'
-
###############################################################################
-def tiff_ovr_average_multiband_vs_singleband():
+def test_tiff_ovr_average_multiband_vs_singleband():
gdal.Translate('/vsimem/tiff_ovr_average_multiband_band.tif', 'data/reproduce_average_issue.tif', creationOptions=['INTERLEAVE=BAND'])
gdal.Translate('/vsimem/tiff_ovr_average_multiband_pixel.tif', 'data/reproduce_average_issue.tif', creationOptions=['INTERLEAVE=PIXEL'])
@@ -2318,146 +1959,7 @@ def tiff_ovr_average_multiband_vs_singleband():
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_ovr_average_multiband_band.tif')
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_ovr_average_multiband_pixel.tif')
- if cs_band != cs_pixel:
- gdaltest.post_reason('fail')
- print(cs_band, cs_pixel)
- return 'fail'
-
- return 'success'
+ assert cs_band == cs_pixel
-###############################################################################
-# Cleanup
-def tiff_ovr_cleanup():
- gdaltest.tiff_drv.Delete('tmp/mfloat32.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr4.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr5.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr6.tif')
- gdaltest.tiff_drv.Delete('tmp/test_average_palette.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr9.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr10.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr11.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr12.tif')
- gdaltest.tiff_drv.Delete('tmp/test_gauss_palette.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr15.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr16.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr17.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr18.tif')
- md = gdaltest.tiff_drv.GetMetadata()
- if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') != -1:
- gdaltest.tiff_drv.Delete('tmp/ovr19.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr20.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr21.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr22.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr23.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr24.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr25.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr26.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr27.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr30.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr31.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr37.dt0')
- if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') != -1:
- gdaltest.tiff_drv.Delete('tmp/ovr38.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr39.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr40.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr41.tif')
- gdaltest.tiff_drv.Delete('tmp/ovr42.tif')
- gdaltest.tiff_drv.Delete('tmp/rgba_with_alpha_0_and_255.tif')
- gdaltest.tiff_drv = None
-
- return 'success'
-
-
-gdaltest_list_internal = [
- tiff_ovr_1,
- tiff_ovr_2,
- tiff_ovr_3,
- tiff_ovr_3bis,
- tiff_ovr_4,
- tiff_ovr_5,
- tiff_ovr_6,
- tiff_ovr_7,
- tiff_ovr_8,
- tiff_ovr_9,
- tiff_ovr_10,
- tiff_ovr_11,
- tiff_ovr_12,
- tiff_ovr_13,
- tiff_ovr_14,
- tiff_ovr_15,
- tiff_ovr_16,
- tiff_ovr_17,
- tiff_ovr_18,
- tiff_ovr_19,
- tiff_ovr_20,
- tiff_ovr_21,
- tiff_ovr_22,
- tiff_ovr_23,
- tiff_ovr_24,
- tiff_ovr_25,
- tiff_ovr_26,
- tiff_ovr_27,
- tiff_ovr_28,
- tiff_ovr_29,
- tiff_ovr_30,
- tiff_ovr_31,
- tiff_ovr_32,
- tiff_ovr_33,
- tiff_ovr_34,
- tiff_ovr_35,
- tiff_ovr_36,
- tiff_ovr_37,
- tiff_ovr_38,
- tiff_ovr_39,
- tiff_ovr_40,
- tiff_ovr_41,
- tiff_ovr_42,
- tiff_ovr_43,
- tiff_ovr_44,
- tiff_ovr_45,
- tiff_ovr_46,
- tiff_ovr_47,
- tiff_ovr_48,
- tiff_ovr_49,
- tiff_ovr_50,
- tiff_ovr_cleanup]
-
-
-def tiff_ovr_invert_endianness():
- gdaltest.tiff_endianness = gdal.GetConfigOption('GDAL_TIFF_ENDIANNESS', "NATIVE")
- gdal.SetConfigOption('GDAL_TIFF_ENDIANNESS', 'INVERTED')
- return 'success'
-
-
-def tiff_ovr_restore_endianness():
- gdal.SetConfigOption('GDAL_TIFF_ENDIANNESS', gdaltest.tiff_endianness)
- return 'success'
-
-
-gdaltest_list = []
-for item in gdaltest_list_internal:
- gdaltest_list.append(item)
-gdaltest_list.append(tiff_ovr_invert_endianness)
-for item in gdaltest_list_internal:
- if item.__name__ != 'tiff_ovr_46':
- gdaltest_list.append((item, item.__name__ + '_inverted'))
-gdaltest_list.append(tiff_ovr_restore_endianness)
-
-gdaltest_list += [tiff_ovr_51,
- tiff_ovr_52,
- tiff_ovr_53,
- tiff_ovr_54,
- tiff_ovr_too_many_levels_contig,
- tiff_ovr_too_many_levels_separate,
- tiff_ovr_too_many_levels_external,
- tiff_ovr_average_multiband_vs_singleband ]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('tiff_ovr')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/tiff_read.py b/autotest/gcore/tiff_read.py
index b6411ef7fff6..a5f80c8f2cf2 100755
--- a/autotest/gcore/tiff_read.py
+++ b/autotest/gcore/tiff_read.py
@@ -31,135 +31,119 @@
import sys
import shutil
-sys.path.append('../pymod')
+import pytest
import gdaltest
from osgeo import gdal, osr
-###############################################################################
-# When imported build a list of units based on the files available.
-
-gdaltest_list = []
-
init_list = [
- ('byte.tif', 1, 4672, None),
- ('uint16_sgilog.tif', 1, 4672, None),
- ('next_literalrow.tif', 1, 4, None),
- ('next_literalspan.tif', 1, 4, None),
- ('next_default_case.tif', 1, 4, None),
- ('thunder.tif', 1, 3, None),
- ('int10.tif', 1, 4672, None),
- ('int12.tif', 1, 4672, None),
- ('int16.tif', 1, 4672, None),
- ('uint16.tif', 1, 4672, None),
- ('int24.tif', 1, 4672, None),
- ('int32.tif', 1, 4672, None),
- ('uint32.tif', 1, 4672, None),
- ('float16.tif', 1, 4672, None),
- ('float24.tif', 1, 4672, None),
- ('float32.tif', 1, 4672, None),
- ('float32_minwhite.tif', 1, 1, None),
- ('float64.tif', 1, 4672, None),
- ('cint16.tif', 1, 5028, None),
- ('cint32.tif', 1, 5028, None),
- ('cfloat32.tif', 1, 5028, None),
- ('cfloat64.tif', 1, 5028, None),
+ ('byte.tif', 1, 4672),
+ ('uint16_sgilog.tif', 1, 4672),
+ ('next_literalrow.tif', 1, 4),
+ ('next_literalspan.tif', 1, 4),
+ ('next_default_case.tif', 1, 4),
+ ('thunder.tif', 1, 3),
+ ('int10.tif', 1, 4672),
+ ('int12.tif', 1, 4672),
+ ('int16.tif', 1, 4672),
+ ('uint16.tif', 1, 4672),
+ ('int24.tif', 1, 4672),
+ ('int32.tif', 1, 4672),
+ ('uint32.tif', 1, 4672),
+ ('float16.tif', 1, 4672),
+ ('float24.tif', 1, 4672),
+ ('float32.tif', 1, 4672),
+ ('float32_minwhite.tif', 1, 1),
+ ('float64.tif', 1, 4672),
+ ('cint16.tif', 1, 5028),
+ ('cint32.tif', 1, 5028),
+ ('cfloat32.tif', 1, 5028),
+ ('cfloat64.tif', 1, 5028),
# The following four related partial final strip/tiles (#1179)
- ('separate_tiled.tif', 2, 15234, None),
- ('seperate_strip.tif', 2, 15234, None), # TODO: Spelling.
- ('contig_tiled.tif', 2, 15234, None),
- ('contig_strip.tif', 2, 15234, None),
- ('empty1bit.tif', 1, 0, None)]
+ ('separate_tiled.tif', 2, 15234),
+ ('seperate_strip.tif', 2, 15234), # TODO: Spelling.
+ ('contig_tiled.tif', 2, 15234),
+ ('contig_strip.tif', 2, 15234),
+ ('empty1bit.tif', 1, 0)
+]
+
+
+@pytest.mark.parametrize(
+ 'filename,band,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.require_driver('GTiff')
+def test_tiff_open(filename, band, checksum):
+ ut = gdaltest.GDALTest('GTiff', filename, band, checksum)
+ ut.testOpen()
+
###############################################################################
# Test absolute/offset && index directory access
-def tiff_read_off():
+def test_tiff_read_off():
# Test absolute/offset directory access.
ds = gdal.Open('GTIFF_DIR:off:408:data/byte.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672
# Same with GTIFF_RAW: prefix
ds = gdal.Open('GTIFF_RAW:GTIFF_DIR:off:408:data/byte.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672
# Test index directory access
ds = gdal.Open('GTIFF_DIR:1:data/byte.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672
# Check that georeferencing is read properly when accessing
# "GTIFF_DIR" subdatasets (#3478)
gt = ds.GetGeoTransform()
- if gt != (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0):
- gdaltest.post_reason('did not get expected geotransform')
- print(gt)
- return 'fail'
+ assert gt == (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0), \
+ 'did not get expected geotransform'
# Error cases
with gdaltest.error_handler():
ds = gdal.Open('GTIFF_DIR:')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
with gdaltest.error_handler():
ds = gdal.Open('GTIFF_DIR:1')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
with gdaltest.error_handler():
ds = gdal.Open('GTIFF_DIR:1:')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
with gdaltest.error_handler():
ds = gdal.Open('GTIFF_DIR:1:/vsimem/i_dont_exist.tif')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
# Requested directory not found
with gdaltest.error_handler():
ds = gdal.Open('GTIFF_DIR:2:data/byte.tif')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
# Opening a specific TIFF directory is not supported in update mode.
# Switching to read-only
with gdaltest.error_handler():
ds = gdal.Open('GTIFF_DIR:1:data/byte.tif', gdal.GA_Update)
- if ds is None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ds is not None
###############################################################################
# Confirm we interpret bands as alpha when we should, and not when we
# should not.
-def tiff_check_alpha():
+def test_tiff_check_alpha():
# Grey + alpha
ds = gdal.Open('data/stefan_full_greyalpha.tif')
- if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('Wrong color interpretation (stefan_full_greyalpha).')
- print(ds.GetRasterBand(2).GetRasterColorInterpretation())
- return 'fail'
+ assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_AlphaBand, \
+ 'Wrong color interpretation (stefan_full_greyalpha).'
ds = None
@@ -171,20 +155,15 @@ def tiff_check_alpha():
gdaltest.supports_force_rgba = True
if gdaltest.supports_force_rgba:
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
- if got_cs != [1970, 1970, 1970, 10807]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [1970, 1970, 1970, 10807]
ds = None
# RGB + alpha
ds = gdal.Open('data/stefan_full_rgba.tif')
- if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('Wrong color interpretation (stefan_full_rgba).')
- print(ds.GetRasterBand(4).GetRasterColorInterpretation())
- return 'fail'
+ assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_AlphaBand, \
+ 'Wrong color interpretation (stefan_full_rgba).'
ds = None
@@ -194,20 +173,15 @@ def tiff_check_alpha():
gdal.SetConfigOption('GTIFF_FORCE_RGBA', None)
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
# FIXME? Not the same as without GTIFF_FORCE_RGBA=YES
- if got_cs != [11547, 57792, 35643, 10807]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [11547, 57792, 35643, 10807]
ds = None
# RGB + undefined
ds = gdal.Open('data/stefan_full_rgba_photometric_rgb.tif')
- if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_Undefined:
- gdaltest.post_reason('Wrong color interpretation (stefan_full_rgba_photometric_rgb).')
- print(ds.GetRasterBand(4).GetRasterColorInterpretation())
- return 'fail'
+ assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_Undefined, \
+ 'Wrong color interpretation (stefan_full_rgba_photometric_rgb).'
ds = None
@@ -216,88 +190,69 @@ def tiff_check_alpha():
ds = gdal.Open('data/stefan_full_rgba_photometric_rgb.tif')
gdal.SetConfigOption('GTIFF_FORCE_RGBA', None)
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
- if got_cs != [12603, 58561, 36064, 10807]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [12603, 58561, 36064, 10807]
ds = None
- return 'success'
-
+
###############################################################################
# Test reading a CMYK tiff as RGBA image
-def tiff_read_cmyk_rgba():
+def test_tiff_read_cmyk_rgba():
ds = gdal.Open('data/rgbsmall_cmyk.tif')
md = ds.GetMetadata('IMAGE_STRUCTURE')
- if 'SOURCE_COLOR_SPACE' not in md or md['SOURCE_COLOR_SPACE'] != 'CMYK':
- print('bad value for IMAGE_STRUCTURE[SOURCE_COLOR_SPACE]')
- return 'fail'
+ assert 'SOURCE_COLOR_SPACE' in md and md['SOURCE_COLOR_SPACE'] == 'CMYK', \
+ 'bad value for IMAGE_STRUCTURE[SOURCE_COLOR_SPACE]'
- if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('Wrong color interpretation.')
- print(ds.GetRasterBand(1).GetRasterColorInterpretation())
- return 'fail'
+ assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_RedBand, \
+ 'Wrong color interpretation.'
- if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('Wrong color interpretation (alpha).')
- print(ds.GetRasterBand(4).GetRasterColorInterpretation())
- return 'fail'
+ assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_AlphaBand, \
+ 'Wrong color interpretation (alpha).'
- if ds.GetRasterBand(1).Checksum() != 23303:
- print('Expected checksum = %d. Got = %d' % (23303, ds.GetRasterBand(1).Checksum()))
- return 'fail'
-
- return 'success'
+ assert ds.GetRasterBand(1).Checksum() == 23303, \
+ ('Expected checksum = %d. Got = %d' % (23303, ds.GetRasterBand(1).Checksum()))
###############################################################################
# Test reading a CMYK tiff as a raw image
-def tiff_read_cmyk_raw():
+def test_tiff_read_cmyk_raw():
ds = gdal.Open('GTIFF_RAW:data/rgbsmall_cmyk.tif')
- if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_CyanBand:
- gdaltest.post_reason('Wrong color interpretation.')
- print(ds.GetRasterBand(1).GetRasterColorInterpretation())
- return 'fail'
-
- if ds.GetRasterBand(1).Checksum() != 29430:
- print('Expected checksum = %d. Got = %d' % (29430, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_CyanBand, \
+ 'Wrong color interpretation.'
- return 'success'
+ assert ds.GetRasterBand(1).Checksum() == 29430, \
+ ('Expected checksum = %d. Got = %d' % (29430, ds.GetRasterBand(1).Checksum()))
###############################################################################
# Test reading a OJPEG image
-def tiff_read_ojpeg():
+def test_tiff_read_ojpeg():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('data/zackthecat.tif')
gdal.PopErrorHandler()
if ds is None:
if gdal.GetLastErrorMsg().find('Cannot open TIFF file due to missing codec') == 0:
- return 'skip'
- print(gdal.GetLastErrorMsg())
- return 'fail'
+ pytest.skip()
+ pytest.fail(gdal.GetLastErrorMsg())
gdal.PushErrorHandler('CPLQuietErrorHandler')
got_cs = ds.GetRasterBand(1).Checksum()
gdal.PopErrorHandler()
expected_cs = 61570
- if got_cs != expected_cs:
- print('Expected checksum = %d. Got = %d' % (expected_cs, got_cs))
- return 'fail'
+ assert got_cs == expected_cs, \
+ ('Expected checksum = %d. Got = %d' % (expected_cs, got_cs))
#
gdal.PushErrorHandler('CPLQuietErrorHandler')
@@ -307,13 +262,12 @@ def tiff_read_ojpeg():
if cs != 0:
print('Should be 0 with internal libtiff')
- return 'success'
-
+
###############################################################################
# Read a .tif.gz file
-def tiff_read_gzip():
+def test_tiff_read_gzip():
try:
os.remove('data/byte.tif.gz.properties')
@@ -321,173 +275,140 @@ def tiff_read_gzip():
pass
ds = gdal.Open('/vsigzip/./data/byte.tif.gz')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
try:
os.stat('data/byte.tif.gz.properties')
- gdaltest.post_reason('did not expect data/byte.tif.gz.properties')
- return 'fail'
+ pytest.fail('did not expect data/byte.tif.gz.properties')
except OSError:
- return 'success'
+ return
###############################################################################
# Read a .tif.zip file (with explicit filename)
-def tiff_read_zip_1():
+def test_tiff_read_zip_1():
ds = gdal.Open('/vsizip/./data/byte.tif.zip/byte.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
- return 'success'
-
###############################################################################
# Read a .tif.zip file (with implicit filename)
-def tiff_read_zip_2():
+def test_tiff_read_zip_2():
ds = gdal.Open('/vsizip/./data/byte.tif.zip')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
- return 'success'
-
###############################################################################
# Read a .tif.zip file with a single file in a subdirectory (with explicit filename)
-def tiff_read_zip_3():
+def test_tiff_read_zip_3():
ds = gdal.Open('/vsizip/./data/onefileinsubdir.zip/onefileinsubdir/byte.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
- return 'success'
-
###############################################################################
# Read a .tif.zip file with a single file in a subdirectory(with implicit filename)
-def tiff_read_zip_4():
+def test_tiff_read_zip_4():
ds = gdal.Open('/vsizip/./data/onefileinsubdir.zip')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
- return 'success'
-
###############################################################################
# Read a .tif.zip file with 2 files in a subdirectory
-def tiff_read_zip_5():
+def test_tiff_read_zip_5():
ds = gdal.Open('/vsizip/./data/twofileinsubdir.zip/twofileinsubdir/byte.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
- return 'success'
-
###############################################################################
# Read a .tar file (with explicit filename)
-def tiff_read_tar_1():
+def test_tiff_read_tar_1():
ds = gdal.Open('/vsitar/./data/byte.tar/byte.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
- return 'success'
-
###############################################################################
# Read a .tar file (with implicit filename)
-def tiff_read_tar_2():
+def test_tiff_read_tar_2():
ds = gdal.Open('/vsitar/./data/byte.tar')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
- return 'success'
-
###############################################################################
# Read a .tgz file (with explicit filename)
-def tiff_read_tgz_1():
+def test_tiff_read_tgz_1():
ds = gdal.Open('/vsitar/./data/byte.tgz/byte.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
gdal.Unlink('data/byte.tgz.properties')
- return 'success'
-
###############################################################################
# Read a .tgz file (with implicit filename)
-def tiff_read_tgz_2():
+def test_tiff_read_tgz_2():
ds = gdal.Open('/vsitar/./data/byte.tgz')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
gdal.Unlink('data/byte.tgz.properties')
- return 'success'
-
###############################################################################
# Check handling of non-degree angular units (#601)
-def tiff_grads():
+def test_tiff_grads():
ds = gdal.Open('data/test_gf.tif')
srs = ds.GetProjectionRef()
- if srs.find('PARAMETER["latitude_of_origin",46.8]') == -1:
- print(srs)
- gdaltest.post_reason('Did not get expected latitude of origin.')
- return 'fail'
-
- return 'success'
+ assert srs.find('PARAMETER["latitude_of_origin",46.8]') != -1, \
+ 'Did not get expected latitude of origin.'
###############################################################################
# Check Erdas Citation Parsing for coordinate system.
-def tiff_citation():
+def test_tiff_citation():
build_info = gdal.VersionInfo('BUILD_INFO')
if build_info.find('ESRI_BUILD=YES') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/citation_mixedcase.tif')
wkt = ds.GetProjectionRef()
@@ -496,16 +417,14 @@ def tiff_citation():
if wkt != expected_wkt:
print('got: ', wkt)
- gdaltest.post_reason('Erdas citation processing failing?')
- return 'fail'
-
- return 'success'
+ pytest.fail('Erdas citation processing failing?')
+
###############################################################################
# Check that we can read linear projection parameters properly (#3901)
-def tiff_linearparmunits():
+def test_tiff_linearparmunits():
# Test the file with the correct formulation.
@@ -516,9 +435,7 @@ def tiff_linearparmunits():
srs = osr.SpatialReference(wkt)
fe = srs.GetProjParm(osr.SRS_PP_FALSE_EASTING)
- if abs(fe - 2000000.0) > 0.001:
- gdaltest.post_reason('did not get expected false easting (1)')
- return 'fail'
+ assert abs(fe - 2000000.0) <= 0.001, 'did not get expected false easting (1)'
# Test the file with the old (broken) GDAL formulation.
@@ -529,9 +446,7 @@ def tiff_linearparmunits():
srs = osr.SpatialReference(wkt)
fe = srs.GetProjParm(osr.SRS_PP_FALSE_EASTING)
- if abs(fe - 609601.219202438) > 0.001:
- gdaltest.post_reason('did not get expected false easting (2)')
- return 'fail'
+ assert abs(fe - 609601.219202438) <= 0.001, 'did not get expected false easting (2)'
# Test the file when using an EPSG code.
@@ -542,17 +457,13 @@ def tiff_linearparmunits():
srs = osr.SpatialReference(wkt)
fe = srs.GetProjParm(osr.SRS_PP_FALSE_EASTING)
- if abs(fe - 2000000.0) > 0.001:
- gdaltest.post_reason('did not get expected false easting (3)')
- return 'fail'
-
- return 'success'
+ assert abs(fe - 2000000.0) <= 0.001, 'did not get expected false easting (3)'
###############################################################################
# Check that the GTIFF_LINEAR_UNITS handling works properly (#3901)
-def tiff_linearparmunits2():
+def test_tiff_linearparmunits2():
gdal.SetConfigOption('GTIFF_LINEAR_UNITS', 'BROKEN')
@@ -565,9 +476,7 @@ def tiff_linearparmunits2():
srs = osr.SpatialReference(wkt)
fe = srs.GetProjParm(osr.SRS_PP_FALSE_EASTING)
- if abs(fe - 6561666.66667) > 0.001:
- gdaltest.post_reason('did not get expected false easting (1)')
- return 'fail'
+ assert abs(fe - 6561666.66667) <= 0.001, 'did not get expected false easting (1)'
# Test the file with the correct formulation that is marked as correct.
@@ -578,9 +487,7 @@ def tiff_linearparmunits2():
srs = osr.SpatialReference(wkt)
fe = srs.GetProjParm(osr.SRS_PP_FALSE_EASTING)
- if abs(fe - 2000000.0) > 0.001:
- gdaltest.post_reason('did not get expected false easting (2)')
- return 'fail'
+ assert abs(fe - 2000000.0) <= 0.001, 'did not get expected false easting (2)'
# Test the file with the old (broken) GDAL formulation.
@@ -591,86 +498,67 @@ def tiff_linearparmunits2():
srs = osr.SpatialReference(wkt)
fe = srs.GetProjParm(osr.SRS_PP_FALSE_EASTING)
- if abs(fe - 2000000.0) > 0.001:
- gdaltest.post_reason('did not get expected false easting (3)')
- return 'fail'
+ assert abs(fe - 2000000.0) <= 0.001, 'did not get expected false easting (3)'
gdal.SetConfigOption('GTIFF_LINEAR_UNITS', 'DEFAULT')
- return 'success'
-
###############################################################################
# Test GTiffSplitBitmapBand to treat one row 1bit files as scanline blocks (#2622)
-def tiff_g4_split():
+def test_tiff_g4_split():
if 'GetBlockSize' not in dir(gdal.Band):
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/slim_g4.tif')
(_, blocky) = ds.GetRasterBand(1).GetBlockSize()
- if blocky != 1:
- gdaltest.post_reason('Did not get scanline sized blocks.')
- return 'fail'
+ assert blocky == 1, 'Did not get scanline sized blocks.'
cs = ds.GetRasterBand(1).Checksum()
- if cs != 3322:
- print(cs)
- gdaltest.post_reason('Got wrong checksum')
- return 'fail'
-
- return 'success'
+ assert cs == 3322, 'Got wrong checksum'
###############################################################################
# Test reading a tiff with multiple images in it
-def tiff_multi_images():
+def test_tiff_multi_images():
# Implicitly get the content of the first image (backward compatibility).
ds = gdal.Open('data/twoimages.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' %
+ assert ds.GetRasterBand(1).Checksum() == 4672, ('Expected checksum = %d. Got = %d' %
(4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
md = ds.GetMetadata('SUBDATASETS')
- if md['SUBDATASET_1_NAME'] != 'GTIFF_DIR:1:data/twoimages.tif':
- print(md)
- gdaltest.post_reason('did not get expected subdatasets metadata.')
- return 'fail'
+ assert md['SUBDATASET_1_NAME'] == 'GTIFF_DIR:1:data/twoimages.tif', \
+ 'did not get expected subdatasets metadata.'
ds = None
# Explicitly get the content of the first image.
ds = gdal.Open('GTIFF_DIR:1:data/twoimages.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
# Explicitly get the content of the second image.
ds = gdal.Open('GTIFF_DIR:2:data/twoimages.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds = None
- return 'success'
-
###############################################################################
# Test reading a tiff from a memory buffer (#2931)
-def tiff_vsimem():
+def test_tiff_vsimem():
try:
gdal.FileFromMemBuffer
except AttributeError:
- return 'skip'
+ pytest.skip()
content = open('data/byte.tif', mode='rb').read()
@@ -678,40 +566,35 @@ def tiff_vsimem():
gdal.FileFromMemBuffer('/vsimem/tiffinmem', content)
ds = gdal.Open('/vsimem/tiffinmem', gdal.GA_Update)
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
ds.GetRasterBand(1).Fill(0)
ds = None
ds = gdal.Open('/vsimem/tiffinmem')
- if ds.GetRasterBand(1).Checksum() != 0:
- print('Expected checksum = %d. Got = %d' % (0, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 0, \
+ ('Expected checksum = %d. Got = %d' % (0, ds.GetRasterBand(1).Checksum()))
ds = None
# Also test with anti-slash
ds = gdal.Open('/vsimem\\tiffinmem')
- if ds.GetRasterBand(1).Checksum() != 0:
- print('Expected checksum = %d. Got = %d' % (0, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 0, \
+ ('Expected checksum = %d. Got = %d' % (0, ds.GetRasterBand(1).Checksum()))
ds = None
# Release memory associated to the in-memory file
gdal.Unlink('/vsimem/tiffinmem')
- return 'success'
-
###############################################################################
# Test reading a tiff from inside a zip in a memory buffer !
-def tiff_vsizip_and_mem():
+def test_tiff_vsizip_and_mem():
try:
gdal.FileFromMemBuffer
except AttributeError:
- return 'skip'
+ pytest.skip()
content = open('data/byte.tif.zip', mode='rb').read()
@@ -719,48 +602,37 @@ def tiff_vsizip_and_mem():
gdal.FileFromMemBuffer('/vsimem/tiffinmem.zip', content)
ds = gdal.Open('/vsizip/vsimem/tiffinmem.zip/byte.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- print('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672, \
+ ('Expected checksum = %d. Got = %d' % (4672, ds.GetRasterBand(1).Checksum()))
# Release memory associated to the in-memory file
gdal.Unlink('/vsimem/tiffinmem.zip')
- return 'success'
-
###############################################################################
# Test reading a GeoTIFF with only ProjectedCSTypeGeoKey defined (ticket #3019)
-def tiff_ProjectedCSTypeGeoKey_only():
+def test_tiff_ProjectedCSTypeGeoKey_only():
ds = gdal.Open('data/ticket3019.tif')
- if ds.GetProjectionRef().find('WGS 84 / UTM zone 31N') == -1:
- print(ds.GetProjectionRef())
- return 'fail'
+ assert ds.GetProjectionRef().find('WGS 84 / UTM zone 31N') != -1
ds = None
- return 'success'
-
###############################################################################
# Test reading a GeoTIFF with only GTModelTypeGeoKey defined
-def tiff_GTModelTypeGeoKey_only():
+def test_tiff_GTModelTypeGeoKey_only():
ds = gdal.Open('data/GTModelTypeGeoKey_only.tif')
- if ds.GetProjectionRef().find('LOCAL_CS["unnamed",GEOGCS["unknown",DATUM["unknown",SPHEROID["unretrievable - using WGS84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT[,0.0174532925199433]],UNIT["unknown",1]]') != 0:
- print(ds.GetProjectionRef())
- return 'fail'
+ assert ds.GetProjectionRef().find('LOCAL_CS["unnamed",GEOGCS["unknown",DATUM["unknown",SPHEROID["unretrievable - using WGS84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT[,0.0174532925199433]],UNIT["unknown",1]]') == 0
ds = None
- return 'success'
-
###############################################################################
# Test reading a 12bit jpeg compressed geotiff.
-def tiff_12bitjpeg():
+def test_tiff_12bitjpeg():
old_accum = gdal.GetConfigOption('CPL_ACCUM_ERROR_MSG', 'OFF')
gdal.SetConfigOption('CPL_ACCUM_ERROR_MSG', 'ON')
@@ -781,31 +653,26 @@ def tiff_12bitjpeg():
if gdal.GetLastErrorMsg().find(
'Unsupported JPEG data precision 12') != -1:
sys.stdout.write('(12bit jpeg not available) ... ')
- return 'skip'
+ pytest.skip()
elif ds is None:
- gdaltest.post_reason('failed to open 12bit jpeg file with unexpected error')
- return 'fail'
+ pytest.fail('failed to open 12bit jpeg file with unexpected error')
try:
stats = ds.GetRasterBand(1).GetStatistics(0, 1)
except:
pass
- if stats[2] < 2150 or stats[2] > 2180 or str(stats[2]) == 'nan':
- gdaltest.post_reason('did not get expected mean for band1.')
- print(stats)
- return 'fail'
+ assert not (stats[2] < 2150 or stats[2] > 2180 or str(stats[2]) == 'nan'), \
+ 'did not get expected mean for band1.'
ds = None
os.unlink('data/mandrilmini_12bitjpeg.tif.aux.xml')
- return 'success'
-
###############################################################################
# Test that statistics for TIFF files are stored and correctly read from .aux.xml
-def tiff_read_stats_from_pam():
+def test_tiff_read_stats_from_pam():
try:
os.remove('data/byte.tif.aux.xml')
@@ -814,29 +681,22 @@ def tiff_read_stats_from_pam():
ds = gdal.Open('data/byte.tif')
md = ds.GetRasterBand(1).GetMetadata()
- if 'STATISTICS_MINIMUM' in md:
- gdaltest.post_reason('Unexpected presence of STATISTICS_MINIMUM')
- return 'fail'
+ assert 'STATISTICS_MINIMUM' not in md, 'Unexpected presence of STATISTICS_MINIMUM'
# Force statistics computation
stats = ds.GetRasterBand(1).GetStatistics(0, 1)
- if stats[0] != 74.0 or stats[1] != 255.0:
- print(stats)
- return 'fail'
+ assert stats[0] == 74.0 and stats[1] == 255.0
ds = None
try:
os.stat('data/byte.tif.aux.xml')
except OSError:
- gdaltest.post_reason('Expected generation of data/byte.tif.aux.xml')
- return 'fail'
+ pytest.fail('Expected generation of data/byte.tif.aux.xml')
ds = gdal.Open('data/byte.tif')
# Just read statistics (from PAM) without forcing their computation
stats = ds.GetRasterBand(1).GetStatistics(0, 0)
- if stats[0] != 74.0 or stats[1] != 255.0:
- print(stats)
- return 'fail'
+ assert stats[0] == 74.0 and stats[1] == 255.0
ds = None
try:
@@ -844,13 +704,12 @@ def tiff_read_stats_from_pam():
except OSError:
pass
- return 'success'
-
+
###############################################################################
# Test extracting georeferencing from a .TAB file
-def tiff_read_from_tab():
+def test_tiff_read_from_tab():
ds = gdal.GetDriverByName('GTiff').Create('tmp/tiff_read_from_tab.tif', 1, 1)
ds = None
@@ -879,30 +738,20 @@ def tiff_read_from_tab():
gdal.GetDriverByName('GTiff').Delete('tmp/tiff_read_from_tab.tif')
- try:
+ with pytest.raises(OSError, message='did not expect to find .tab file at that point'):
os.stat('tmp/tiff_read_from_tab.tab')
- gdaltest.post_reason('did not expect to find .tab file at that point')
- return 'fail'
- except OSError:
- pass
-
- if gt != (400000.0, 25.0, 0.0, 1300000.0, 0.0, -25.0):
- gdaltest.post_reason('did not get expected geotransform')
- print(gt)
- return 'fail'
+
- if wkt.find('OSGB_1936') == -1:
- gdaltest.post_reason('did not get expected SRS')
- print(wkt)
- return 'fail'
+ assert gt == (400000.0, 25.0, 0.0, 1300000.0, 0.0, -25.0), \
+ 'did not get expected geotransform'
- return 'success'
+ assert wkt.find('OSGB_1936') != -1, 'did not get expected SRS'
###############################################################################
# Test reading PixelIsPoint file.
-def tiff_read_pixelispoint():
+def test_tiff_read_pixelispoint():
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', 'FALSE')
@@ -912,10 +761,7 @@ def tiff_read_pixelispoint():
gt_expected = (440690.0, 60.0, 0.0, 3751350.0, 0.0, -60.0)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform')
- return 'fail'
+ assert gt == gt_expected, 'did not get expected geotransform'
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', 'TRUE')
@@ -925,20 +771,16 @@ def tiff_read_pixelispoint():
gt_expected = (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform with GTIFF_POINT_GEO_IGNORE TRUE')
- return 'fail'
+ assert gt == gt_expected, \
+ 'did not get expected geotransform with GTIFF_POINT_GEO_IGNORE TRUE'
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', None)
- return 'success'
-
###############################################################################
# Test reading a GeoTIFF file with a geomatrix in PixelIsPoint format.
-def tiff_read_geomatrix():
+def test_tiff_read_geomatrix():
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', 'FALSE')
@@ -948,10 +790,7 @@ def tiff_read_geomatrix():
gt_expected = (1841001.75, 1.5, -5.0, 1144003.25, -5.0, -1.5)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform')
- return 'fail'
+ assert gt == gt_expected, 'did not get expected geotransform'
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', 'TRUE')
@@ -961,20 +800,16 @@ def tiff_read_geomatrix():
gt_expected = (1841000.0, 1.5, -5.0, 1144000.0, -5.0, -1.5)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform with GTIFF_POINT_GEO_IGNORE TRUE')
- return 'fail'
+ assert gt == gt_expected, \
+ 'did not get expected geotransform with GTIFF_POINT_GEO_IGNORE TRUE'
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', None)
- return 'success'
-
###############################################################################
# Test that we don't crash when reading a TIFF with corrupted GeoTIFF tags
-def tiff_read_corrupted_gtiff():
+def test_tiff_read_corrupted_gtiff():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('data/corrupted_gtiff_tags.tif')
@@ -982,37 +817,30 @@ def tiff_read_corrupted_gtiff():
del ds
err_msg = gdal.GetLastErrorMsg()
- if err_msg.find('IO error during') == -1 and \
- err_msg.find('Error fetching data for field') == -1:
- gdaltest.post_reason('did not get expected error message')
- print(err_msg)
- return 'fail'
-
- return 'success'
+ assert (not (err_msg.find('IO error during') == -1 and \
+ err_msg.find('Error fetching data for field') == -1)), \
+ 'did not get expected error message'
###############################################################################
# Test that we don't crash when reading a TIFF with corrupted GeoTIFF tags
-def tiff_read_tag_without_null_byte():
+def test_tiff_read_tag_without_null_byte():
gdal.ErrorReset()
oldval = gdal.GetConfigOption('CPL_DEBUG')
gdal.SetConfigOption('CPL_DEBUG', 'OFF')
ds = gdal.Open('data/tag_without_null_byte.tif')
gdal.SetConfigOption('CPL_DEBUG', oldval)
- if gdal.GetLastErrorType() != 0:
- gdaltest.post_reason('should have not emitted a warning, but only a CPLDebug() message')
- return 'fail'
+ assert gdal.GetLastErrorType() == 0, \
+ 'should have not emitted a warning, but only a CPLDebug() message'
del ds
- return 'success'
-
###############################################################################
# Test the effect of the GTIFF_IGNORE_READ_ERRORS configuration option (#3994)
-def tiff_read_buggy_packbits():
+def test_tiff_read_buggy_packbits():
old_val = gdal.GetConfigOption('GTIFF_IGNORE_READ_ERRORS')
gdal.SetConfigOption('GTIFF_IGNORE_READ_ERRORS', None)
@@ -1021,9 +849,7 @@ def tiff_read_buggy_packbits():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ret = ds.ReadRaster(0, 0, 20, 20)
gdal.PopErrorHandler()
- if ret is not None:
- gdaltest.post_reason('did not expected a valid result')
- return 'fail'
+ assert ret is None, 'did not expected a valid result'
ds = None
gdal.SetConfigOption('GTIFF_IGNORE_READ_ERRORS', 'YES')
@@ -1032,18 +858,14 @@ def tiff_read_buggy_packbits():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ret = ds.ReadRaster(0, 0, 20, 20)
gdal.PopErrorHandler()
- if ret is None:
- gdaltest.post_reason('expected a valid result')
- return 'fail'
+ assert ret is not None, 'expected a valid result'
ds = None
- return 'success'
-
###############################################################################
# Test reading a GeoEye _rpc.txt (#3639)
-def tiff_read_rpc_txt():
+def test_tiff_read_rpc_txt():
shutil.copy('data/byte.tif', 'tmp/test.tif')
shutil.copy('data/test_rpc.txt', 'tmp/test_rpc.txt')
@@ -1053,39 +875,28 @@ def tiff_read_rpc_txt():
os.remove('tmp/test.tif')
os.remove('tmp/test_rpc.txt')
- if rpc_md['HEIGHT_OFF'] != '+0300.000 meters':
- gdaltest.post_reason('HEIGHT_OFF wrong:"' + rpc_md['HEIGHT_OFF'] + '"')
- return 'fail'
-
- if rpc_md['LINE_DEN_COEFF'].find(
- '+1.000000000000000E+00 -5.207696939454288E-03') != 0:
- print(rpc_md['LINE_DEN_COEFF'])
- gdaltest.post_reason('LINE_DEN_COEFF wrong')
- return 'fail'
+ assert rpc_md['HEIGHT_OFF'] == '+0300.000 meters', \
+ ('HEIGHT_OFF wrong:"' + rpc_md['HEIGHT_OFF'] + '"')
- return 'success'
+ assert (rpc_md['LINE_DEN_COEFF'].find(
+ '+1.000000000000000E+00 -5.207696939454288E-03') == 0), \
+ 'LINE_DEN_COEFF wrong'
###############################################################################
# Test reading a TIFF with the RPC tag per
# http://geotiff.maptools.org/rpc_prop.html
-def tiff_read_rpc_tif():
+def test_tiff_read_rpc_tif():
ds = gdal.Open('data/byte_rpc.tif')
rpc_md = ds.GetMetadata('RPC')
ds = None
- if rpc_md['HEIGHT_OFF'] != '300':
- gdaltest.post_reason('HEIGHT_OFF wrong:' + rpc_md['HEIGHT_OFF'])
- return 'fail'
-
- if rpc_md['LINE_DEN_COEFF'].find('1 -0.00520769693945429') != 0:
- print(rpc_md['LINE_DEN_COEFF'])
- gdaltest.post_reason('LINE_DEN_COEFF wrong')
- return 'fail'
+ assert rpc_md['HEIGHT_OFF'] == '300', ('HEIGHT_OFF wrong:' + rpc_md['HEIGHT_OFF'])
- return 'success'
+ assert rpc_md['LINE_DEN_COEFF'].find('1 -0.00520769693945429') == 0, \
+ 'LINE_DEN_COEFF wrong'
###############################################################################
# Test a very small TIFF with only 4 tags :
@@ -1097,7 +908,7 @@ def tiff_read_rpc_tif():
# StripByteCounts (279) LONG (4) 1<1>
-def tiff_small():
+def test_tiff_small():
content = '\x49\x49\x2A\x00\x08\x00\x00\x00\x04\x00\x00\x01\x03\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01\x01\x03\x00\x01\x00\x00\x00\x01\x00\x00\x00\x11\x01\x04\x00\x01\x00\x00\x00\x00\x00\x00\x00\x17\x01\x04\x00\x01\x00\x00\x00\x01\x00\x00\x00'
@@ -1105,160 +916,125 @@ def tiff_small():
gdal.FileFromMemBuffer('/vsimem/small.tif', content)
ds = gdal.Open('/vsimem/small.tif')
- if ds.GetRasterBand(1).Checksum() != 0:
- print('Expected checksum = %d. Got = %d' % (0, ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 0, \
+ ('Expected checksum = %d. Got = %d' % (0, ds.GetRasterBand(1).Checksum()))
# Release memory associated to the in-memory file
gdal.Unlink('/vsimem/small.tif')
- return 'success'
-
###############################################################################
# Test that we can workaround a DoS with
-def tiff_dos_strip_chop():
+def test_tiff_dos_strip_chop():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('data/tiff_dos_strip_chop.tif')
gdal.PopErrorHandler()
del ds
- return 'success'
-
###############################################################################
# Test reading EXIF and GPS metadata
-def tiff_read_exif_and_gps():
+def test_tiff_read_exif_and_gps():
ds = gdal.Open('data/exif_and_gps.tif')
exif_md = ds.GetMetadata('EXIF')
ds = None
- if exif_md is None or not exif_md:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert exif_md is not None and exif_md
ds = gdal.Open('data/exif_and_gps.tif')
EXIF_GPSVersionID = ds.GetMetadataItem('EXIF_GPSVersionID', 'EXIF')
ds = None
- if EXIF_GPSVersionID is None:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert EXIF_GPSVersionID is not None
# We should not get any EXIF metadata with that file
ds = gdal.Open('data/byte.tif')
exif_md = ds.GetMetadata('EXIF')
ds = None
- if not (exif_md is None or not exif_md):
- gdaltest.post_reason('failed')
- return 'fail'
-
- return 'success'
+ assert (exif_md is None or not exif_md)
###############################################################################
# Test reading a pixel interleaved RGBA JPEG-compressed TIFF
-def tiff_jpeg_rgba_pixel_interleaved():
+def test_tiff_jpeg_rgba_pixel_interleaved():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/stefan_full_rgba_jpeg_contig.tif')
md = ds.GetMetadata('IMAGE_STRUCTURE')
- if md['INTERLEAVE'] != 'PIXEL':
- gdaltest.post_reason('failed')
- return 'fail'
+ assert md['INTERLEAVE'] == 'PIXEL'
expected_cs = [16404, 62700, 37913, 14174]
for i in range(4):
cs = ds.GetRasterBand(i + 1).Checksum()
- if cs != expected_cs[i]:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert cs == expected_cs[i]
- if ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != gdal.GCI_RedBand + i:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert ds.GetRasterBand(i + 1).GetRasterColorInterpretation() == gdal.GCI_RedBand + i
ds = None
- return 'success'
-
###############################################################################
# Test reading a band interleaved RGBA JPEG-compressed TIFF
-def tiff_jpeg_rgba_band_interleaved():
+def test_tiff_jpeg_rgba_band_interleaved():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/stefan_full_rgba_jpeg_separate.tif')
md = ds.GetMetadata('IMAGE_STRUCTURE')
- if md['INTERLEAVE'] != 'BAND':
- gdaltest.post_reason('failed')
- return 'fail'
+ assert md['INTERLEAVE'] == 'BAND'
expected_cs = [16404, 62700, 37913, 14174]
for i in range(4):
cs = ds.GetRasterBand(i + 1).Checksum()
- if cs != expected_cs[i]:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert cs == expected_cs[i]
- if ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != gdal.GCI_RedBand + i:
- gdaltest.post_reason('failed')
- return 'fail'
+ assert ds.GetRasterBand(i + 1).GetRasterColorInterpretation() == gdal.GCI_RedBand + i
ds = None
- return 'success'
-
###############################################################################
# Test reading a YCbCr JPEG all-in-one-strip multiband TIFF (#3259, #3894)
-def tiff_read_online_1():
+def test_tiff_read_online_1():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
if not gdaltest.download_file('http://trac.osgeo.org/gdal/raw-attachment/ticket/3259/imgpb17.tif', 'imgpb17.tif'):
- return 'skip'
+ pytest.skip()
ds = gdal.Open('tmp/cache/imgpb17.tif')
gdal.ErrorReset()
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if gdal.GetLastErrorMsg() != '':
- return 'fail'
+ assert gdal.GetLastErrorMsg() == ''
- if cs != 62628 and cs != 28554:
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 62628 or cs == 28554
###############################################################################
# Use GTIFF_DIRECT_IO=YES option combined with /vsicurl to test for multi-range
# support
-def tiff_read_online_2():
+def test_tiff_read_online_2():
if gdal.GetDriverByName('HTTP') is None:
- return 'skip'
+ pytest.skip()
if gdaltest.gdalurlopen('http://download.osgeo.org/gdal/data/gtiff/utm.tif') is None:
- print('cannot open URL')
- return 'skip'
+ pytest.skip('cannot open URL')
old_val = gdal.GetConfigOption('GTIFF_DIRECT_IO')
gdal.SetConfigOption('GTIFF_DIRECT_IO', 'YES')
@@ -1269,9 +1045,7 @@ def tiff_read_online_2():
gdal.SetConfigOption('CPL_VSIL_CURL_ALLOWED_EXTENSIONS', None)
gdal.SetConfigOption('GDAL_DISABLE_READDIR_ON_OPEN', None)
- if ds is None:
- gdaltest.post_reason('could not open dataset')
- return 'fail'
+ assert ds is not None, 'could not open dataset'
# Read subsampled data
subsampled_data = ds.ReadRaster(0, 0, 512, 512, 128, 128)
@@ -1282,28 +1056,22 @@ def tiff_read_online_2():
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 54935:
- gdaltest.post_reason('wrong checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 54935, 'wrong checksum'
###############################################################################
# Test reading a TIFF made of a single-strip that is more than 2GB (#5403)
-def tiff_read_huge4GB():
+def test_tiff_read_huge4GB():
# Need libtiff 4.X anyway
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if not gdaltest.filesystem_supports_sparse_files('tmp'):
ds = gdal.Open('data/huge4GB.tif')
- if ds is None:
- return 'fail'
+ assert ds is not None
else:
shutil.copy('data/huge4GB.tif', 'tmp/huge4GB.tif')
f = open('tmp/huge4GB.tif', 'rb+')
@@ -1313,109 +1081,79 @@ def tiff_read_huge4GB():
ds = gdal.Open('tmp/huge4GB.tif')
if ds is None:
os.remove('tmp/huge4GB.tif')
- return 'fail'
+ pytest.fail()
ds = None
os.remove('tmp/huge4GB.tif')
- return 'success'
-
+
###############################################################################
# Test reading a (small) BigTIFF. Tests GTiffCacheOffsetOrCount8()
-def tiff_read_bigtiff():
+def test_tiff_read_bigtiff():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/byte_bigtiff_strip5lines.tif')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 4672:
- return 'fail'
-
- return 'success'
+ assert cs == 4672
###############################################################################
# Test reading in TIFF metadata domain
-def tiff_read_tiff_metadata():
+def test_tiff_read_tiff_metadata():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/stefan_full_rgba_jpeg_contig.tif')
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_0', 'TIFF') != '254':
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_0', 'TIFF') != '770':
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('JPEGTABLES', 'TIFF').find('FFD8') != 0:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_100_0', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_100', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_100_0', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_100', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_0', 'TIFF') == '254'
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_0', 'TIFF') == '770'
+ assert ds.GetRasterBand(1).GetMetadataItem('JPEGTABLES', 'TIFF').find('FFD8') == 0
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_100_0', 'TIFF') is None
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_100', 'TIFF') is None
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_100_0', 'TIFF') is None
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_100', 'TIFF') is None
ds = gdal.Open('data/stefan_full_rgba_jpeg_separate.tif')
- if ds.GetRasterBand(4).GetMetadataItem('BLOCK_OFFSET_0_2', 'TIFF') != '11071':
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(4).GetMetadataItem('BLOCK_SIZE_0_2', 'TIFF') != '188':
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ds.GetRasterBand(4).GetMetadataItem('BLOCK_OFFSET_0_2', 'TIFF') == '11071'
+ assert ds.GetRasterBand(4).GetMetadataItem('BLOCK_SIZE_0_2', 'TIFF') == '188'
###############################################################################
# Test reading a JPEG-in-TIFF with tiles of irregular size (corrupted image)
-def tiff_read_irregular_tile_size_jpeg_in_tiff():
+def test_tiff_read_irregular_tile_size_jpeg_in_tiff():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/irregular_tile_size_jpeg_in_tiff.tif')
gdal.ErrorReset()
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds.GetRasterBand(1).Checksum()
gdal.PopErrorHandler()
- if gdal.GetLastErrorType() == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorType() != 0
gdal.ErrorReset()
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds.GetRasterBand(1).GetOverview(0).Checksum()
gdal.PopErrorHandler()
- if gdal.GetLastErrorType() == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorType() != 0
gdal.ErrorReset()
- return 'success'
-
###############################################################################
# Test GTIFF_DIRECT_IO and GTIFF_VIRTUAL_MEM_IO optimizations
-def tiff_direct_and_virtual_mem_io():
+def test_tiff_direct_and_virtual_mem_io():
# Test with pixel-interleaved and band-interleaved datasets
for dt in [gdal.GDT_Byte, gdal.GDT_Int16, gdal.GDT_CInt16]:
@@ -1635,147 +1373,103 @@ def tiff_direct_and_virtual_mem_io():
gdal.Unlink(filename)
if ref_data_native_type != got_data_native_type:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if truncated and not band_interleaved:
if got_data_native_type_whole is not None:
- gdaltest.post_reason('fail')
print(truncated)
print(band_interleaved)
print(option)
print(i)
- print(gdal.GetDataTypeName(dt))
- return 'fail'
+ pytest.fail(gdal.GetDataTypeName(dt))
elif ref_data_native_type_whole != got_data_native_type_whole:
- gdaltest.post_reason('fail')
- print(option)
print(i)
- return 'fail'
+ pytest.fail(option)
if ref_data_native_type_downsampled != got_data_native_type_downsampled:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if not truncated and ref_data_native_type_downsampled_not_nearest != got_data_native_type_downsampled_not_nearest:
- gdaltest.post_reason('fail')
- print(truncated)
print(band_interleaved)
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if ref_data_native_type_upsampled != got_data_native_type_upsampled:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
for y in range(ysize):
for x in range(xsize):
for k in range(dt_size):
if ref_data_native_type_custom_spacings[(y * xsize + x) * nbands * dt_size + k] != got_data_native_type_custom_spacings[(y * xsize + x) * nbands * dt_size + k]:
- gdaltest.post_reason('fail')
print(gdal.GetDataTypeName(dt))
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if not truncated:
for band in range(nbands):
if ref_nbands_data_native_type_custom_spacings[(y * xsize + x) * 2 * nbands * dt_size + band * dt_size + k] != got_nbands_data_native_type_custom_spacings[(y * xsize + x) * 2 * nbands * dt_size + band * dt_size + k]:
- gdaltest.post_reason('fail')
print(gdal.GetDataTypeName(dt))
print(option)
- print(i)
- print(x, y, k, band)
- return 'fail'
+ pytest.fail(i)
if nbands == 3:
for band in range(nbands):
if ref_nbands_data_native_type_custom_spacings_2[(y * xsize + x) * 4 * dt_size + band * dt_size + k] != got_nbands_data_native_type_custom_spacings_2[(y * xsize + x) * 4 * dt_size + band * dt_size + k]:
- gdaltest.post_reason('fail')
print(gdal.GetDataTypeName(dt))
print(option)
- print(i)
- print(x, y, k, band)
- return 'fail'
+ pytest.fail(i)
if ref_data_float32 != got_data_float32:
- gdaltest.post_reason('fail')
print(gdal.GetDataTypeName(dt))
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if not truncated and ref_nbands_data_native_type != got_nbands_data_native_type:
- gdaltest.post_reason('fail')
- print(truncated)
print(band_interleaved)
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if truncated:
if got_nbands_data_native_type_whole is not None:
- gdaltest.post_reason('fail')
print(gdal.GetDataTypeName(dt))
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
elif ref_nbands_data_native_type_whole != got_nbands_data_native_type_whole:
- gdaltest.post_reason('fail')
- print(gdal.GetDataTypeName(dt))
print(option)
print(i)
- return 'fail'
+ pytest.fail(gdal.GetDataTypeName(dt))
if truncated:
if got_nbands_data_native_type_pixel_interleaved_whole is not None:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
elif ref_nbands_data_native_type_pixel_interleaved_whole != got_nbands_data_native_type_pixel_interleaved_whole:
- gdaltest.post_reason('fail')
- print(option)
print(i)
- return 'fail'
+ pytest.fail(option)
if truncated and got_nbands_data_native_type_bottom_right_downsampled is not None:
- gdaltest.post_reason('fail')
print(gdal.GetDataTypeName(dt))
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if truncated:
continue
if ref_nbands_data_native_type_downsampled != got_nbands_data_native_type_downsampled:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if ref_nbands_data_native_type_downsampled_interleaved != got_nbands_data_native_type_downsampled_interleaved:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if ref_nbands_data_native_type_downsampled_not_nearest != got_nbands_data_native_type_downsampled_not_nearest:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if ref_nbands_data_native_type_upsampled != got_nbands_data_native_type_upsampled:
- gdaltest.post_reason('fail')
print(option)
- print(i)
# import struct
# f1 = open('out1.txt', 'wb')
# f2 = open('out2.txt', 'wb')
@@ -1783,12 +1477,10 @@ def tiff_direct_and_virtual_mem_io():
# for y in range(4 * ysize):
# f1.write('%s\n' % str(struct.unpack('B' * 4 * xsize, ref_nbands_data_native_type_upsampled[(b * 4 * ysize + y) * 4 * xsize : (b * 4 * ysize + y + 1) * 4 * xsize])))
# f2.write('%s\n' % str(struct.unpack('B' * 4 * xsize, got_nbands_data_native_type_upsampled[(b * 4 * ysize + y) * 4 * xsize : (b * 4 * ysize + y + 1) * 4 * xsize])))
- return 'fail'
+ pytest.fail(i)
if ref_nbands_data_native_type_downsampled_x_upsampled_y != got_nbands_data_native_type_downsampled_x_upsampled_y:
- gdaltest.post_reason('fail')
print(option)
- print(i)
# import struct
# f1 = open('out1.txt', 'wb')
# f2 = open('out2.txt', 'wb')
@@ -1796,60 +1488,45 @@ def tiff_direct_and_virtual_mem_io():
# for y in range(32 * ysize):
# f1.write('%s\n' % str(struct.unpack('B' * int(xsize/2), ref_nbands_data_native_type_downsampled_x_upsampled_y[(b * 32 * ysize + y) * int(xsize/2) : (b * 32 * ysize + y + 1) * int(xsize/2)])))
# f2.write('%s\n' % str(struct.unpack('B' * int(xsize/2), got_nbands_data_native_type_downsampled_x_upsampled_y[(b * 32 * ysize + y) * int(xsize/2) : (b * 32 * ysize + y + 1) * int(xsize/2)])))
- return 'fail'
+ pytest.fail(i)
if ref_nbands_data_native_type_unordered_list != got_nbands_data_native_type_unordered_list:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if ref_nbands_data_native_type_pixel_interleaved != got_nbands_data_native_type_pixel_interleaved:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
for y in range(ysize):
for x in range(xsize):
for b in range(nbands - 1):
for k in range(dt_size):
if ref_nbands_m_1_data_native_type_pixel_interleaved_with_extra_space[((y * xsize + x) * nbands + b) * dt_size + k] != got_nbands_m_1_data_native_type_pixel_interleaved_with_extra_space[((y * xsize + x) * nbands + b) * dt_size + k]:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- print(y)
- print(x)
- print(b)
- return 'fail'
+ pytest.fail(i)
if ref_nbands_data_float32 != got_nbands_data_float32:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
if ref_nbands_data_float32_pixel_interleaved != got_nbands_data_float32_pixel_interleaved:
- gdaltest.post_reason('fail')
print(option)
- print(i)
- return 'fail'
+ pytest.fail(i)
ds = gdal.Open('data/byte.tif') # any GTiff file will do
unreached = ds.GetMetadataItem('UNREACHED_VIRTUALMEMIO_CODE_PATH', '_DEBUG_')
ds = None
if unreached:
- gdaltest.post_reason('missing code coverage in VirtualMemIO()')
print('unreached = %s' % unreached)
- return 'fail'
-
- return 'success'
+ pytest.fail('missing code coverage in VirtualMemIO()')
+
###############################################################################
# Check read Digital Globe metadata IMD & RPB format
-def tiff_read_md1():
+def test_tiff_read_md1():
try:
os.remove('data/md_dg.tif.aux.xml')
@@ -1859,47 +1536,33 @@ def tiff_read_md1():
ds = gdal.Open('data/md_dg.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 3:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 3, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 6:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 6, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2010-04-01 12:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2010-04-01 12:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_dg.tif.aux.xml'):
os.stat('data/md_dg.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_dg.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read Digital Globe metadata XML format
-def tiff_read_md2():
+def test_tiff_read_md2():
try:
os.remove('data/md_dg_2.tif.aux.xml')
@@ -1909,47 +1572,33 @@ def tiff_read_md2():
ds = gdal.Open('data/md_dg_2.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 2:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 2, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 6:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 6, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2011-05-01 13:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2011-05-01 13:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_dg_2.tif.aux.xml'):
os.stat('data/md_dg_2.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_dg_2.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read GeoEye metadata format
-def tiff_read_md3():
+def test_tiff_read_md3():
try:
os.remove('data/md_ge_rgb_0010000.tif.aux.xml')
@@ -1959,47 +1608,33 @@ def tiff_read_md3():
ds = gdal.Open('data/md_ge_rgb_0010000.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 3:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 3, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 6:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 6, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2012-06-01 14:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2012-06-01 14:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_ge_rgb_0010000.tif.aux.xml'):
os.stat('data/md_ge_rgb_0010000.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_ge_rgb_0010000.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read OrbView metadata format
-def tiff_read_md4():
+def test_tiff_read_md4():
try:
os.remove('data/md_ov.tif.aux.xml')
@@ -2009,47 +1644,33 @@ def tiff_read_md4():
ds = gdal.Open('data/md_ov.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 3:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 3, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 6:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 6, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2013-07-01 15:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2013-07-01 15:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_ov.tif.aux.xml'):
os.stat('data/md_ov.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_ov.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read Resurs-DK1 metadata format
-def tiff_read_md5():
+def test_tiff_read_md5():
try:
os.remove('data/md_rdk1.tif.aux.xml')
@@ -2059,47 +1680,33 @@ def tiff_read_md5():
ds = gdal.Open('data/md_rdk1.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 2:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 2, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 5:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 5, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2014-08-01 16:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2014-08-01 16:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_rdk1.tif.aux.xml'):
os.stat('data/md_rdk1.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_rdk1.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read Landsat metadata format
-def tiff_read_md6():
+def test_tiff_read_md6():
try:
os.remove('data/md_ls_b1.tif.aux.xml')
@@ -2109,47 +1716,33 @@ def tiff_read_md6():
ds = gdal.Open('data/md_ls_b1.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 2:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 2, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 5:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 5, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2015-09-01 17:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2015-09-01 17:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_ls_b1.tif.aux.xml'):
os.stat('data/md_ls_b1.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_ls_b1.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read Spot metadata format
-def tiff_read_md7():
+def test_tiff_read_md7():
try:
os.remove('data/spot/md_spot.tif.aux.xml')
@@ -2159,47 +1752,33 @@ def tiff_read_md7():
ds = gdal.Open('data/spot/md_spot.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 2:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 2, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 5:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 5, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2001-03-01 00:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2001-03-01 00:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/spot/md_spot.tif.aux.xml'):
os.stat('data/spot/md_spot.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/spot/md_spot.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read RapidEye metadata format
-def tiff_read_md8():
+def test_tiff_read_md8():
try:
os.remove('data/md_re.tif.aux.xml')
@@ -2209,47 +1788,33 @@ def tiff_read_md8():
ds = gdal.Open('data/md_re.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 2:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 2, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 5:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 5, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2010-02-01 12:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2010-02-01 12:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_re.tif.aux.xml'):
os.stat('data/md_re.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_re.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read Alos metadata format
-def tiff_read_md9():
+def test_tiff_read_md9():
try:
os.remove('data/alos/IMG-md_alos.tif.aux.xml')
@@ -2259,44 +1824,32 @@ def tiff_read_md9():
ds = gdal.Open('data/alos/IMG-md_alos.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 3:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 3, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 6:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 6, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2010-07-01 00:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2010-07-01 00:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/alos/IMG-md_alos.tif.aux.xml'):
os.stat('data/alos/IMG-md_alos.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/alos/IMG-md_alos.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read Eros metadata format
-def tiff_read_md10():
+def test_tiff_read_md10():
try:
os.remove('data/md_eros.tif.aux.xml')
@@ -2306,47 +1859,33 @@ def tiff_read_md10():
ds = gdal.Open('data/md_eros.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 3:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 3, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 6:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 6, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2013-04-01 11:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2013-04-01 11:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_eros.tif.aux.xml'):
os.stat('data/md_eros.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_eros.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read Kompsat metadata format
-def tiff_read_md11():
+def test_tiff_read_md11():
try:
os.remove('data/md_kompsat.tif.aux.xml')
@@ -2356,91 +1895,61 @@ def tiff_read_md11():
ds = gdal.Open('data/md_kompsat.tif', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 3:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 3, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 6:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 6, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2007-05-01 07:00:00':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2007-05-01 07:00:00', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_kompsat.tif.aux.xml'):
os.stat('data/md_kompsat.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_kompsat.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Check read Dimap metadata format
-def tiff_read_md12():
+def test_tiff_read_md12():
ds = gdal.Open('../gdrivers/data/dimap2/IMG_foo_R2C1.TIF', gdal.GA_ReadOnly)
filelist = ds.GetFileList()
- if len(filelist) != 3:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
+ assert len(filelist) == 3, 'did not get expected file list.'
metadata = ds.GetMetadataDomainList()
- if len(metadata) != 6:
- gdaltest.post_reason('did not get expected metadata list.')
- return 'fail'
+ assert len(metadata) == 6, 'did not get expected metadata list.'
md = ds.GetMetadata('IMAGERY')
- if 'SATELLITEID' not in md:
- print('SATELLITEID not present in IMAGERY Domain')
- return 'fail'
- if 'CLOUDCOVER' not in md:
- print('CLOUDCOVER not present in IMAGERY Domain')
- return 'fail'
- if 'ACQUISITIONDATETIME' not in md:
- print('ACQUISITIONDATETIME not present in IMAGERY Domain')
- return 'fail'
+ assert 'SATELLITEID' in md, 'SATELLITEID not present in IMAGERY Domain'
+ assert 'CLOUDCOVER' in md, 'CLOUDCOVER not present in IMAGERY Domain'
+ assert 'ACQUISITIONDATETIME' in md, \
+ 'ACQUISITIONDATETIME not present in IMAGERY Domain'
# Test UTC date
- if md['ACQUISITIONDATETIME'] != '2016-06-17 12:34:56':
- print('bad value for IMAGERY[ACQUISITIONDATETIME]')
- return 'fail'
+ assert md['ACQUISITIONDATETIME'] == '2016-06-17 12:34:56', \
+ 'bad value for IMAGERY[ACQUISITIONDATETIME]'
# Test RPC and that we have a LINE_OFF shift
rpc = ds.GetMetadata('RPC')
- if rpc['LINE_OFF'] != '-11':
- gdaltest.post_reason('RPC wrong.')
- print(rpc)
- return 'fail'
+ assert rpc['LINE_OFF'] == '-11', 'RPC wrong.'
ds = None
- try:
+ with pytest.raises(OSError, message='Expected not generation of data/md_kompsat.tif.aux.xml'):
os.stat('data/md_kompsat.tif.aux.xml')
- gdaltest.post_reason('Expected not generation of data/md_kompsat.tif.aux.xml')
- return 'fail'
- except OSError:
- pass
+
# Test not valid DIMAP product [https://github.com/OSGeo/gdal/issues/431]
shutil.copy('../gdrivers/data/dimap2/IMG_foo_R2C1.TIF', 'tmp/IMG_foo_temp.TIF')
@@ -2453,35 +1962,26 @@ def tiff_read_md12():
gdal.Unlink('tmp/DIM_foo.XML')
gdal.Unlink('tmp/RPC_foo.XML')
- if len(filelist) > 1:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
-
- return 'success'
+ assert len(filelist) <= 1, 'did not get expected file list.'
###############################################################################
# Test reading a TIFFTAG_GDAL_NODATA with empty text
-def tiff_read_empty_nodata_tag():
+def test_tiff_read_empty_nodata_tag():
ds = gdal.Open('data/empty_nodata.tif')
- if ds.GetRasterBand(1).GetNoDataValue() is not None:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetNoDataValue())
- return 'fail'
-
- return 'success'
+ assert ds.GetRasterBand(1).GetNoDataValue() is None
###############################################################################
# Check that no auxiliary files are read with a simple Open(), reading
# imagery and getting IMAGE_STRUCTURE metadata
-def tiff_read_strace_check():
+def test_tiff_read_strace_check():
if not sys.platform.startswith('linux'):
- return 'skip'
+ pytest.skip()
python_exe = sys.executable
cmd = "strace -f %s -c \"from osgeo import gdal; " % python_exe + (
@@ -2495,25 +1995,20 @@ def tiff_read_strace_check():
(_, err) = gdaltest.runexternal_out_and_err(cmd)
except:
# strace not available
- return 'skip'
+ pytest.skip()
lines_with_dotdot_gcore = []
for line in err.split('\n'):
if line.find('../gcore') >= 0:
lines_with_dotdot_gcore += [line]
- if len(lines_with_dotdot_gcore) != 1:
- gdaltest.post_reason('fail')
- print(lines_with_dotdot_gcore)
- return 'fail'
-
- return 'success'
+ assert len(lines_with_dotdot_gcore) == 1
###############################################################################
# Test GDAL_READDIR_LIMIT_ON_OPEN
-def tiff_read_readdir_limit_on_open():
+def test_tiff_read_readdir_limit_on_open():
gdal.SetConfigOption('GDAL_READDIR_LIMIT_ON_OPEN', '1')
@@ -2522,84 +2017,65 @@ def tiff_read_readdir_limit_on_open():
gdal.SetConfigOption('GDAL_READDIR_LIMIT_ON_OPEN', None)
- if len(filelist) != 3:
- gdaltest.post_reason('did not get expected file list.')
- return 'fail'
-
- return 'success'
+ assert len(filelist) == 3, 'did not get expected file list.'
###############################################################################
#
-def tiff_read_minisblack_as_rgba():
+def test_tiff_read_minisblack_as_rgba():
if not gdaltest.supports_force_rgba:
- return 'skip'
+ pytest.skip()
gdal.SetConfigOption('GTIFF_FORCE_RGBA', 'YES')
ds = gdal.Open('data/byte.tif')
gdal.SetConfigOption('GTIFF_FORCE_RGBA', None)
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
- if got_cs != [4672, 4672, 4672, 4873]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [4672, 4672, 4672, 4873]
ds = None
- return 'success'
-
###############################################################################
#
-def tiff_read_colortable_as_rgba():
+def test_tiff_read_colortable_as_rgba():
if not gdaltest.supports_force_rgba:
- return 'skip'
+ pytest.skip()
gdal.SetConfigOption('GTIFF_FORCE_RGBA', 'YES')
ds = gdal.Open('data/test_average_palette.tif')
gdal.SetConfigOption('GTIFF_FORCE_RGBA', None)
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
- if got_cs != [2433, 2433, 2433, 4873]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [2433, 2433, 2433, 4873]
ds = None
- return 'success'
-
###############################################################################
#
-def tiff_read_logl_as_rgba():
+def test_tiff_read_logl_as_rgba():
if not gdaltest.supports_force_rgba:
- return 'skip'
+ pytest.skip()
gdal.SetConfigOption('GTIFF_FORCE_RGBA', 'YES')
ds = gdal.Open('data/uint16_sgilog.tif')
gdal.SetConfigOption('GTIFF_FORCE_RGBA', None)
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
# I'm pretty sure this isn't the expected result...
- if got_cs != [0, 0, 0, 4873]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [0, 0, 0, 4873]
ds = None
- return 'success'
-
###############################################################################
#
-def tiff_read_strip_separate_as_rgba():
+def test_tiff_read_strip_separate_as_rgba():
if not gdaltest.supports_force_rgba:
- return 'skip'
+ pytest.skip()
# 3 band
gdal.Translate('/vsimem/tiff_read_strip_separate_as_rgba.tif',
@@ -2609,10 +2085,7 @@ def tiff_read_strip_separate_as_rgba():
ds = gdal.Open('/vsimem/tiff_read_strip_separate_as_rgba.tif')
gdal.SetConfigOption('GTIFF_FORCE_RGBA', None)
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
- if got_cs != [21212, 21053, 21349, 30658]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [21212, 21053, 21349, 30658]
ds = None
gdal.Unlink('/vsimem/tiff_read_strip_separate_as_rgba.tif')
@@ -2626,24 +2099,19 @@ def tiff_read_strip_separate_as_rgba():
ds = gdal.Open('/vsimem/tiff_read_strip_separate_as_rgba.tif')
gdal.SetConfigOption('GTIFF_FORCE_RGBA', None)
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
- if got_cs != [21212, 21212, 21212, 30658]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [21212, 21212, 21212, 30658]
ds = None
gdal.Unlink('/vsimem/tiff_read_strip_separate_as_rgba.tif')
- return 'success'
-
###############################################################################
#
-def tiff_read_tiled_separate_as_rgba():
+def test_tiff_read_tiled_separate_as_rgba():
if not gdaltest.supports_force_rgba:
- return 'skip'
+ pytest.skip()
# 3 band
gdal.Translate('/vsimem/tiff_read_tiled_separate_as_rgba.tif',
@@ -2653,10 +2121,7 @@ def tiff_read_tiled_separate_as_rgba():
ds = gdal.Open('/vsimem/tiff_read_tiled_separate_as_rgba.tif')
gdal.SetConfigOption('GTIFF_FORCE_RGBA', None)
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
- if got_cs != [21212, 21053, 21349, 30658]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [21212, 21053, 21349, 30658]
ds = None
gdal.Unlink('/vsimem/tiff_read_tiled_separate_as_rgba.tif')
@@ -2669,70 +2134,50 @@ def tiff_read_tiled_separate_as_rgba():
ds = gdal.Open('/vsimem/tiff_read_tiled_separate_as_rgba.tif')
gdal.SetConfigOption('GTIFF_FORCE_RGBA', None)
got_cs = [ds.GetRasterBand(i + 1).Checksum() for i in range(ds.RasterCount)]
- if got_cs != [4672, 4672, 4672, 4873]:
- gdaltest.post_reason('fail')
- print(got_cs)
- return 'fail'
+ assert got_cs == [4672, 4672, 4672, 4873]
ds = None
gdal.Unlink('/vsimem/tiff_read_tiled_separate_as_rgba.tif')
- return 'success'
-
###############################################################################
#
-def tiff_read_scanline_more_than_2GB():
+def test_tiff_read_scanline_more_than_2GB():
with gdaltest.error_handler():
ds = gdal.Open('data/scanline_more_than_2GB.tif')
- if ds is not None:
- return 'fail'
- return 'success'
+ assert ds is None
###############################################################################
# Test that we are at least robust to wrong number of ExtraSamples and warn
# about it
-def tiff_read_wrong_number_extrasamples():
+def test_tiff_read_wrong_number_extrasamples():
gdal.ErrorReset()
with gdaltest.error_handler():
ds = gdal.Open('data/6band_wrong_number_extrasamples.tif')
- if gdal.GetLastErrorMsg().find('Wrong number of ExtraSamples') < 0:
- gdaltest.post_reason('fail')
- print(gdal.GetLastErrorMsg())
- return 'fail'
- if ds.GetRasterBand(6).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(6).GetRasterColorInterpretation())
- return 'fail'
-
- return 'success'
+ assert gdal.GetLastErrorMsg().find('Wrong number of ExtraSamples') >= 0
+ assert ds.GetRasterBand(6).GetRasterColorInterpretation() == gdal.GCI_AlphaBand
###############################################################################
# Test that we can read a one-trip TIFF without StripByteCounts tag
-def tiff_read_one_strip_no_bytecount():
+def test_tiff_read_one_strip_no_bytecount():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('data/one_strip_nobytecount.tif')
gdal.PopErrorHandler()
- if ds.GetRasterBand(1).Checksum() != 1:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).Checksum())
- return 'fail'
-
- return 'success'
+ assert ds.GetRasterBand(1).Checksum() == 1
###############################################################################
# Test GDAL_GEOREF_SOURCES
-def tiff_read_nogeoref():
+def test_tiff_read_nogeoref():
tests = [(None, True, True, False, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)),
(None, True, True, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)),
@@ -2784,24 +2229,21 @@ def tiff_read_nogeoref():
gdal.Unlink('/vsimem/byte_nogeoref.tab')
if gt != expected_gt:
- gdaltest.post_reason('Iteration %d, did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile)))
print('Got ' + str(gt))
print('Expected ' + str(expected_gt))
- return 'fail'
+ pytest.fail('Iteration %d, did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile)))
if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and srs_wkt.find(expected_srs) < 0):
- gdaltest.post_reason('Iteration %d, did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile)))
print('Got ' + srs_wkt)
print('Expected ' + expected_srs)
- return 'fail'
-
- return 'success'
+ pytest.fail('Iteration %d, did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile)))
+
###############################################################################
# Test GDAL_GEOREF_SOURCES
-def tiff_read_inconsistent_georef():
+def test_tiff_read_inconsistent_georef():
tests = [(None, True, True, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)),
(None, False, True, True, '26711', (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0)),
@@ -2845,24 +2287,21 @@ def tiff_read_inconsistent_georef():
gdal.Unlink('/vsimem/byte_inconsistent_georef.tab')
if gt != expected_gt:
- gdaltest.post_reason('Iteration %d, did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile)))
print('Got ' + str(gt))
print('Expected ' + str(expected_gt))
- return 'fail'
+ pytest.fail('Iteration %d, did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile)))
if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and srs_wkt.find(expected_srs) < 0):
- gdaltest.post_reason('Iteration %d, did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile)))
print('Got ' + srs_wkt)
print('Expected ' + expected_srs)
- return 'fail'
-
- return 'success'
+ pytest.fail('Iteration %d, did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile)))
+
###############################################################################
# Test GDAL_GEOREF_SOURCES
-def tiff_read_gcp_internal_and_auxxml():
+def test_tiff_read_gcp_internal_and_auxxml():
tests = [(None, True, 'LOCAL_CS["PAM"]', 1),
(None, False, '4326', 2),
@@ -2896,19 +2335,16 @@ def tiff_read_gcp_internal_and_auxxml():
gdal.Unlink('/vsimem/byte_gcp.tif.aux.xml')
if gcp_count != expected_gcp_count:
- gdaltest.post_reason('Iteration %d, did not get expected gcp count for %s,copy_pam=%s' % (iteration, config_option_value, str(copy_pam)))
print('Got ' + str(gcp_count))
print('Expected ' + str(expected_gcp_count))
- return 'fail'
+ pytest.fail('Iteration %d, did not get expected gcp count for %s,copy_pam=%s' % (iteration, config_option_value, str(copy_pam)))
if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and srs_wkt.find(expected_srs) < 0):
- gdaltest.post_reason('Iteration %d, did not get expected SRS for %s,copy_pam=%s' % (iteration, config_option_value, str(copy_pam)))
print('Got ' + srs_wkt)
print('Expected ' + expected_srs)
- return 'fail'
-
- return 'success'
+ pytest.fail('Iteration %d, did not get expected SRS for %s,copy_pam=%s' % (iteration, config_option_value, str(copy_pam)))
+
###############################################################################
# Test reading .tif + .aux
@@ -2923,7 +2359,7 @@ def handler(self, eErrClass, err_no, msg):
self.msg = msg
-def tiff_read_aux():
+def test_tiff_read_aux():
gdal.ErrorReset()
ds = gdal.Open('data/f2r23.tif')
@@ -2931,77 +2367,58 @@ def tiff_read_aux():
gdal.PushErrorHandler(handler.handler)
ds.GetFileList()
gdal.PopErrorHandler()
- if handler.msg is not None:
- gdaltest.post_reason('Got message that indicate recursive calls: %s' % handler.msg)
- return 'fail'
+ assert handler.msg is None, \
+ ('Got message that indicate recursive calls: %s' % handler.msg)
- return 'success'
-
-def tiff_read_one_band_from_two_bands():
+def test_tiff_read_one_band_from_two_bands():
gdal.Translate('/vsimem/tiff_read_one_band_from_two_bands.tif', 'data/byte.tif', options='-b 1 -b 1')
gdal.Translate('/vsimem/tiff_read_one_band_from_two_bands_dst.tif', '/vsimem/tiff_read_one_band_from_two_bands.tif', options='-b 1')
ds = gdal.Open('/vsimem/tiff_read_one_band_from_two_bands_dst.tif')
- if ds.GetRasterBand(1).Checksum() != 4672:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672
ds = None
gdal.Unlink('/vsimem/tiff_read_one_band_from_two_bands.tif')
gdal.Unlink('/vsimem/tiff_read_one_band_from_two_bands.tif.aux.xml')
gdal.Unlink('/vsimem/tiff_read_one_band_from_two_bands_dst.tif')
- return 'success'
-
-def tiff_read_jpeg_cloud_optimized():
+def test_tiff_read_jpeg_cloud_optimized():
for i in range(4):
ds = gdal.Open('data/byte_ovr_jpeg_tablesmode%d.tif' % i)
cs0 = ds.GetRasterBand(1).Checksum()
cs1 = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs0 != 4743 or cs1 != 1133:
- gdaltest.post_reason('failure')
- print(i)
- print(cs0)
- print(cs1)
- return 'fail'
+ assert cs0 == 4743 and cs1 == 1133, i
ds = None
- return 'success'
-
+
# This one was generated with a buggy code that emit JpegTables with mode == 1
# when creating the overview directory but failed to properly set this mode while
# writing the imagery. libjpeg-6b emits a 'JPEGLib:Huffman table 0x00 was not defined'
# error while jpeg-8 works fine
-def tiff_read_corrupted_jpeg_cloud_optimized():
+def test_tiff_read_corrupted_jpeg_cloud_optimized():
ds = gdal.Open('data/byte_ovr_jpeg_tablesmode_not_correctly_set_on_ovr.tif')
cs0 = ds.GetRasterBand(1).Checksum()
- if cs0 != 4743:
- gdaltest.post_reason('failure')
- print(cs0)
- return 'fail'
+ assert cs0 == 4743
with gdaltest.error_handler():
cs1 = ds.GetRasterBand(1).GetOverview(0).Checksum()
if cs1 == 0:
print('Expected error while writing overview with libjpeg-6b')
elif cs1 != 1133:
- gdaltest.post_reason('failure')
- print(cs1)
- return 'fail'
-
- return 'success'
+ pytest.fail(cs1)
+
###############################################################################
# Test reading YCbCr images with LZW compression
-def tiff_read_ycbcr_lzw():
+def test_tiff_read_ycbcr_lzw():
tests = [('ycbcr_11_lzw.tif', 13459, 12939, 12414),
('ycbcr_12_lzw.tif', 13565, 13105, 12660),
@@ -3024,36 +2441,26 @@ def tiff_read_ycbcr_lzw():
got_cs3 = ds.GetRasterBand(3).Checksum()
if cs1 == 0:
gdal.PopErrorHandler()
- if got_cs1 != cs1 or got_cs2 != cs2 or got_cs3 != cs3:
- gdaltest.post_reason('failure')
- print(filename, got_cs1, got_cs2, got_cs3)
- return 'fail'
-
- return 'success'
+ assert got_cs1 == cs1 and got_cs2 == cs2 and got_cs3 == cs3, \
+ (filename, got_cs1, got_cs2, got_cs3)
+
###############################################################################
# Test reading YCbCr images with nbits > 8
-def tiff_read_ycbcr_int12():
+def test_tiff_read_ycbcr_int12():
with gdaltest.error_handler():
ds = gdal.Open('data/int12_ycbcr_contig.tif')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
- if gdal.GetLastErrorMsg().find('Cannot open TIFF file with') < 0:
- gdaltest.post_reason('fail')
- print(gdal.GetLastErrorMsg())
- return 'fail'
-
- return 'success'
+ assert ds is None
+ assert gdal.GetLastErrorMsg().find('Cannot open TIFF file with') >= 0
###############################################################################
# Test reading band unit from VERT_CS unit (#6675)
-def tiff_read_unit_from_srs():
+def test_tiff_read_unit_from_srs():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_read_unit_from_srs.tif', 1, 1)
sr = osr.SpatialReference()
@@ -3063,122 +2470,86 @@ def tiff_read_unit_from_srs():
ds = gdal.Open('/vsimem/tiff_read_unit_from_srs.tif')
unit = ds.GetRasterBand(1).GetUnitType()
- if unit != 'metre':
- gdaltest.post_reason('fail')
- print(unit)
- return 'fail'
+ assert unit == 'metre'
ds = None
gdal.Unlink('/vsimem/tiff_read_unit_from_srs.tif')
- return 'success'
-
###############################################################################
# Test reading ArcGIS 9.3 .aux.xml
-def tiff_read_arcgis93_geodataxform_gcp():
+def test_tiff_read_arcgis93_geodataxform_gcp():
ds = gdal.Open('data/arcgis93_geodataxform_gcp.tif')
- if ds.GetGCPProjection().find('26712') < 0:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGCPCount() != 16:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetGCPProjection().find('26712') >= 0
+ assert ds.GetGCPCount() == 16
gcp = ds.GetGCPs()[0]
- if abs(gcp.GCPPixel - 565) > 1e-5 or \
- abs(gcp.GCPLine - 11041) > 1e-5 or \
- abs(gcp.GCPX - 500000) > 1e-5 or \
- abs(gcp.GCPY - 4705078.79016612) > 1e-5 or \
- abs(gcp.GCPZ - 0) > 1e-5:
- gdaltest.post_reason('fail')
- return 'fail'
- return 'success'
+ assert (abs(gcp.GCPPixel - 565) <= 1e-5 and \
+ abs(gcp.GCPLine - 11041) <= 1e-5 and \
+ abs(gcp.GCPX - 500000) <= 1e-5 and \
+ abs(gcp.GCPY - 4705078.79016612) <= 1e-5 and \
+ abs(gcp.GCPZ - 0) <= 1e-5)
###############################################################################
# Test reading file with block size > signed int 32 bit
-def tiff_read_block_width_above_32bit():
+def test_tiff_read_block_width_above_32bit():
with gdaltest.error_handler():
ds = gdal.Open('data/block_width_above_32bit.tif')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
- return 'success'
+ assert ds is None
###############################################################################
# Test reading file with image size > signed int 32 bit
-def tiff_read_image_width_above_32bit():
+def test_tiff_read_image_width_above_32bit():
with gdaltest.error_handler():
ds = gdal.Open('data/image_width_above_32bit.tif')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
- return 'success'
+ assert ds is None
###############################################################################
# Test reading file with image size > signed int 32 bit
-def tiff_read_second_image_width_above_32bit():
+def test_tiff_read_second_image_width_above_32bit():
ds = gdal.Open('data/second_image_width_above_32bit.tif')
with gdaltest.error_handler():
- if ds.GetMetadata("SUBDATASETS") != {}:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadata("SUBDATASETS") == {}
with gdaltest.error_handler():
ds = gdal.Open('GTIFF_DIR:2:data/second_image_width_above_32bit.tif')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# Test reading file with minimal number of warnings without warning
-def tiff_read_minimum_tiff_tags_no_warning():
+def test_tiff_read_minimum_tiff_tags_no_warning():
gdal.ErrorReset()
ds = gdal.Open('data/minimum_tiff_tags_no_warning.tif')
- if gdal.GetLastErrorMsg() != '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() == ''
ds.GetRasterBand(1).Checksum()
- if gdal.GetLastErrorMsg() != '':
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert gdal.GetLastErrorMsg() == ''
###############################################################################
# Test reading file with minimal number of warnings but warning
-def tiff_read_minimum_tiff_tags_with_warning():
+def test_tiff_read_minimum_tiff_tags_with_warning():
gdal.ErrorReset()
with gdaltest.error_handler():
ds = gdal.Open('data/minimum_tiff_tags_with_warning.tif')
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() != ''
gdal.ErrorReset()
ds.GetRasterBand(1).Checksum()
- if gdal.GetLastErrorMsg() != '':
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert gdal.GetLastErrorMsg() == ''
###############################################################################
@@ -3209,320 +2580,262 @@ def check_libtiff_internal_or_at_least(expected_maj, expected_min, expected_micr
###############################################################################
-def tiff_read_unknown_compression():
+def test_tiff_read_unknown_compression():
with gdaltest.error_handler():
ds = gdal.Open('data/unknown_compression.tif')
- if ds is not None:
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
-def tiff_read_leak_ZIPSetupDecode():
+def test_tiff_read_leak_ZIPSetupDecode():
if not check_libtiff_internal_or_at_least(4, 0, 8):
- return 'skip'
+ pytest.skip()
with gdaltest.error_handler():
ds = gdal.Open('data/leak-ZIPSetupDecode.tif')
for i in range(ds.RasterCount):
ds.GetRasterBand(i + 1).Checksum()
- return 'success'
-
+
###############################################################################
-def tiff_read_excessive_memory_TIFFFillStrip():
+def test_tiff_read_excessive_memory_TIFFFillStrip():
if not check_libtiff_internal_or_at_least(4, 0, 8):
- return 'skip'
+ pytest.skip()
with gdaltest.error_handler():
ds = gdal.Open('data/excessive-memory-TIFFFillStrip.tif')
for i in range(ds.RasterCount):
ds.GetRasterBand(i + 1).Checksum()
- return 'success'
-
+
###############################################################################
-def tiff_read_excessive_memory_TIFFFillStrip2():
+def test_tiff_read_excessive_memory_TIFFFillStrip2():
if not check_libtiff_internal_or_at_least(4, 0, 8):
- return 'skip'
+ pytest.skip()
with gdaltest.error_handler():
ds = gdal.Open('data/excessive-memory-TIFFFillStrip2.tif')
ds.GetRasterBand(1).Checksum()
- return 'success'
-
+
###############################################################################
-def tiff_read_excessive_memory_TIFFFillTile():
+def test_tiff_read_excessive_memory_TIFFFillTile():
if not check_libtiff_internal_or_at_least(4, 0, 8):
- return 'skip'
+ pytest.skip()
with gdaltest.error_handler():
ds = gdal.Open('data/excessive-memory-TIFFFillTile.tif')
ds.GetRasterBand(1).Checksum()
- return 'success'
-
+
###############################################################################
-def tiff_read_big_strip():
+def test_tiff_read_big_strip():
if not check_libtiff_internal_or_at_least(4, 0, 8):
- return 'skip'
+ pytest.skip()
gdal.Translate('/vsimem/test.tif', 'data/byte.tif', options='-co compress=lzw -outsize 10000 2000 -co blockysize=2000 -r bilinear -ot float32')
if gdal.GetLastErrorMsg().find('cannot allocate') >= 0:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('/vsimem/test.tif')
- if ds.GetRasterBand(1).Checksum() != 2676:
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 2676
ds = None
gdal.Unlink('/vsimem/test.tif')
- return 'success'
-
###############################################################################
# (Potentially) test libtiff CHUNKY_STRIP_READ_SUPPORT
-def tiff_read_big_strip_chunky_way():
+def test_tiff_read_big_strip_chunky_way():
gdal.Translate('/vsimem/test.tif', 'data/byte.tif', options='-co compress=lzw -outsize 1000 2001 -co blockysize=2001 -r bilinear')
ds = gdal.Open('/vsimem/test.tif')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 38337:
- print(cs)
- return 'fail'
+ assert cs == 38337
ds = None
gdal.Unlink('/vsimem/test.tif')
- return 'success'
-
###############################################################################
-def tiff_read_big_tile():
+def test_tiff_read_big_tile():
if not check_libtiff_internal_or_at_least(4, 0, 8):
- return 'skip'
+ pytest.skip()
gdal.Translate('/vsimem/test.tif', 'data/byte.tif', options='-co compress=lzw -outsize 10000 2000 -co tiled=yes -co blockxsize=10000 -co blockysize=2000 -r bilinear -ot float32')
if gdal.GetLastErrorMsg().find('cannot allocate') >= 0:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('/vsimem/test.tif')
- if ds.GetRasterBand(1).Checksum() != 2676:
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 2676
ds = None
gdal.Unlink('/vsimem/test.tif')
- return 'success'
-
###############################################################################
-def tiff_read_huge_tile():
+def test_tiff_read_huge_tile():
with gdaltest.error_handler():
ds = gdal.Open('data/hugeblocksize.tif')
- if ds is not None:
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
-def tiff_read_huge_number_strips():
+def test_tiff_read_huge_number_strips():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['LIBTIFF'] != 'INTERNAL':
- return 'skip'
+ pytest.skip()
with gdaltest.error_handler():
ds = gdal.Open('data/huge-number-strips.tif')
ds.GetRasterBand(1).Checksum()
- return 'success'
-
+
###############################################################################
-def tiff_read_huge_implied_number_strips():
+def test_tiff_read_huge_implied_number_strips():
if not check_libtiff_internal_or_at_least(4, 0, 10):
- return 'skip'
+ pytest.skip()
with gdaltest.error_handler():
gdal.Open('data/huge-implied-number-strips.tif')
- return 'success'
-
+
###############################################################################
-def tiff_read_many_blocks():
+def test_tiff_read_many_blocks():
# Runs super slow on some Windows configs
if sys.platform == 'win32':
- return 'skip'
+ pytest.skip()
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['LIBTIFF'] != 'INTERNAL':
- return 'skip'
+ pytest.skip()
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/test.tif', 1, 2000000, options=['BLOCKYSIZE=1'])
ds = None
ds = gdal.Open('/vsimem/test.tif')
- if ds.GetRasterBand(1).Checksum() != 0:
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 0
ds = None
gdal.Unlink('/vsimem/test.tif')
- return 'success'
-
###############################################################################
-def tiff_read_many_blocks_truncated():
+def test_tiff_read_many_blocks_truncated():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['LIBTIFF'] != 'INTERNAL':
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/many_blocks_truncated.tif')
with gdaltest.error_handler():
ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_2000000', 'TIFF')
- if gdal.GetLastErrorMsg() != 'File too short':
- print(gdal.GetLastErrorMsg())
- return 'fail'
-
- return 'success'
+ assert gdal.GetLastErrorMsg() == 'File too short'
###############################################################################
# Test reading images with nbits > 32
-def tiff_read_uint33():
+def test_tiff_read_uint33():
with gdaltest.error_handler():
ds = gdal.Open('data/uint33.tif')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
- if gdal.GetLastErrorMsg().find('Unsupported TIFF configuration') < 0:
- gdaltest.post_reason('fail')
- print(gdal.GetLastErrorMsg())
- return 'fail'
-
- return 'success'
+ assert ds is None
+ assert gdal.GetLastErrorMsg().find('Unsupported TIFF configuration') >= 0
###############################################################################
# Test fix for https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=1545
-def tiff_read_corrupted_deflate_singlestrip():
+def test_tiff_read_corrupted_deflate_singlestrip():
if not check_libtiff_internal_or_at_least(4, 0, 8):
- return 'skip'
+ pytest.skip()
with gdaltest.error_handler():
ds = gdal.Open('data/corrupted_deflate_singlestrip.tif')
ds.GetRasterBand(1).Checksum()
- return 'success'
-
+
###############################################################################
# Test fix for https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=1563
-def tiff_read_packbits_not_enough_data():
+def test_tiff_read_packbits_not_enough_data():
if not check_libtiff_internal_or_at_least(4, 0, 8):
- return 'skip'
+ pytest.skip()
with gdaltest.error_handler():
ds = gdal.Open('data/packbits-not-enough-data.tif')
ds.GetRasterBand(1).Checksum()
- return 'success'
-
+
###############################################################################
# Test reading images with more than 2billion blocks for a single band
-def tiff_read_toomanyblocks():
+def test_tiff_read_toomanyblocks():
with gdaltest.error_handler():
ds = gdal.Open('data/toomanyblocks.tif')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# Test reading images with more than 2billion blocks for all bands
-def tiff_read_toomanyblocks_separate():
+def test_tiff_read_toomanyblocks_separate():
with gdaltest.error_handler():
ds = gdal.Open('data/toomanyblocks_separate.tif')
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# Test reading images where the number of items in StripByteCounts/StripOffsets
# tag is lesser than the number of strips
-def tiff_read_size_of_stripbytecount_lower_than_stripcount():
+def test_tiff_read_size_of_stripbytecount_lower_than_stripcount():
ds = gdal.Open('data/size_of_stripbytecount_lower_than_stripcount.tif')
# There are 3 strips but StripByteCounts has just two elements;
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_1', 'TIFF') != '171':
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_1', 'TIFF') != '1':
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_2', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_2', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_1', 'TIFF') == '171'
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_1', 'TIFF') == '1'
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_2', 'TIFF') is None
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_2', 'TIFF') is None
ds = gdal.Open('data/size_of_stripbytecount_at_1_and_lower_than_stripcount.tif')
# There are 3 strips but StripByteCounts has just one element;
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_0', 'TIFF') != '1':
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_0', 'TIFF') == '1'
###############################################################################
# Test different datatypes for StripOffsets tag with little/big, classic/bigtiff
-def tiff_read_stripoffset_types():
+def test_tiff_read_stripoffset_types():
tests = [
('data/classictiff_one_block_byte.tif', []), # unsupported
@@ -3567,18 +2880,17 @@ def tiff_read_stripoffset_types():
if offsets != expected_offsets:
print(filename, expected_offsets, offsets)
- return 'success'
-
+
###############################################################################
# Test reading a JPEG-in-TIFF file that contains the 2 denial of service
# vulnerabilities listed in
# http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf
-def tiff_read_progressive_jpeg_denial_of_service():
+def test_tiff_read_progressive_jpeg_denial_of_service():
if not check_libtiff_internal_or_at_least(4, 0, 9):
- return 'skip'
+ pytest.skip()
# Should error out with 'JPEGPreDecode:Reading this strip would require
# libjpeg to allocate at least...'
@@ -3586,9 +2898,7 @@ def tiff_read_progressive_jpeg_denial_of_service():
ds = gdal.Open('/vsizip/data/eofloop_valid_huff.tif.zip')
with gdaltest.error_handler():
cs = ds.GetRasterBand(1).Checksum()
- if cs != 0 or gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert cs == 0 and gdal.GetLastErrorMsg() != ''
# Should error out with 'TIFFjpeg_progress_monitor:Scan number...
gdal.ErrorReset()
@@ -3599,37 +2909,30 @@ def tiff_read_progressive_jpeg_denial_of_service():
cs = ds.GetRasterBand(1).Checksum()
del os.environ['LIBTIFF_ALLOW_LARGE_LIBJPEG_MEM_ALLOC']
del os.environ['LIBTIFF_JPEG_MAX_ALLOWED_SCAN_NUMBER']
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert gdal.GetLastErrorMsg() != ''
+
###############################################################################
# Test reading old-style LZW
-def tiff_read_old_style_lzw():
+def test_tiff_read_old_style_lzw():
if not check_libtiff_internal_or_at_least(4, 0, 8):
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/quad-lzw-old-style.tif')
# Shut down warning about old style LZW
with gdaltest.error_handler():
cs = ds.GetRasterBand(1).Checksum()
- if cs != 34282:
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 34282
###############################################################################
# Test libtiff mmap interface (actually not using mmap, but our /vsimem
# mmap emulation)
-def tiff_read_mmap_interface():
+def test_tiff_read_mmap_interface():
src_ds = gdal.Open('data/byte.tif')
tmpfile = '/vsimem/tiff_read_mmap_interface.tif'
@@ -3642,10 +2945,7 @@ def tiff_read_mmap_interface():
ds = gdal.Open(tmpfile)
cs = ds.GetRasterBand(1).Checksum()
gdal.SetConfigOption('GTIFF_USE_MMAP', None)
- if cs != 4672:
- gdaltest.post_reason('fail')
- print(options, cs)
- return 'fail'
+ assert cs == 4672, (options, cs)
f = gdal.VSIFOpenL(tmpfile, "rb")
data = gdal.VSIFReadL(1, gdal.VSIStatL(tmpfile).size - 1, f)
@@ -3658,80 +2958,60 @@ def tiff_read_mmap_interface():
ds = gdal.Open(tmpfile)
cs = ds.GetRasterBand(1).Checksum()
gdal.SetConfigOption('GTIFF_USE_MMAP', None)
- if cs != 0:
- gdaltest.post_reason('fail')
- print(options, cs)
- return 'fail'
+ assert cs == 0, (options, cs)
gdal.Unlink(tmpfile)
gdal.Unlink(tmpfile)
- return 'success'
-
###############################################################################
# Test reading JPEG compressed file whole last strip height is the full
# strip height, instead of just the number of lines needed to reach the
# image height.
-def tiff_read_jpeg_too_big_last_stripe():
+def test_tiff_read_jpeg_too_big_last_stripe():
if not check_libtiff_internal_or_at_least(4, 0, 9):
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/tif_jpeg_too_big_last_stripe.tif')
with gdaltest.error_handler():
cs = ds.GetRasterBand(1).Checksum()
- if cs != 4557:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 4557
ds = gdal.Open('data/tif_jpeg_ycbcr_too_big_last_stripe.tif')
with gdaltest.error_handler():
cs = ds.GetRasterBand(1).Checksum()
- if cs != 4557:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4557
###############################################################################
# Test reading GeoTIFF file with negative ScaleY in GeoPixelScale tag
-def tiff_read_negative_scaley():
+def test_tiff_read_negative_scaley():
ds = gdal.Open('data/negative_scaley.tif')
with gdaltest.error_handler():
- if ds.GetGeoTransform()[5] != -60:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetGeoTransform()[5] == -60
ds = gdal.Open('data/negative_scaley.tif')
with gdaltest.config_option('GTIFF_HONOUR_NEGATIVE_SCALEY', 'NO'):
- if ds.GetGeoTransform()[5] != -60:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetGeoTransform()[5] == -60
ds = gdal.Open('data/negative_scaley.tif')
with gdaltest.config_option('GTIFF_HONOUR_NEGATIVE_SCALEY', 'YES'):
- if ds.GetGeoTransform()[5] != 60:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ds.GetGeoTransform()[5] == 60
+
###############################################################################
# Test ZSTD compression
-def tiff_read_zstd():
+def test_tiff_read_zstd():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('ZSTD') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte_zstd.tif', 1, 4672)
return ut.testOpen()
@@ -3740,11 +3020,11 @@ def tiff_read_zstd():
# Test ZSTD compression
-def tiff_read_zstd_corrupted():
+def test_tiff_read_zstd_corrupted():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('ZSTD') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte_zstd_corrupted.tif', 1, 0)
with gdaltest.error_handler():
@@ -3754,11 +3034,11 @@ def tiff_read_zstd_corrupted():
# Test ZSTD compression
-def tiff_read_zstd_corrupted2():
+def test_tiff_read_zstd_corrupted2():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('ZSTD') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte_zstd_corrupted2.tif', 1, 0)
with gdaltest.error_handler():
@@ -3769,11 +3049,11 @@ def tiff_read_zstd_corrupted2():
# Test WEBP compression
-def tiff_read_webp():
+def test_tiff_read_webp():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('WEBP') == -1:
- return 'skip'
+ pytest.skip()
stats = (0, 215, 66.38, 47.186)
ut = gdaltest.GDALTest('GTiff', 'tif_webp.tif', 1, None)
success = ut.testOpen(check_approx_stat=stats, stat_epsilon=1)
@@ -3784,37 +3064,31 @@ def tiff_read_webp():
# Test WEBP compression
-def tiff_read_webp_huge_single_strip():
+def test_tiff_read_webp_huge_single_strip():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('WEBP') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/tif_webp_huge_single_strip.tif')
- if ds.GetRasterBand(1).Checksum() == 0:
- return 'fail'
-
- return 'success'
+ assert ds.GetRasterBand(1).Checksum() != 0
###############################################################################
-def tiff_read_1bit_2bands():
+def test_tiff_read_1bit_2bands():
ds = gdal.Open('data/1bit_2bands.tif')
cs = (ds.GetRasterBand(1).Checksum(), ds.GetRasterBand(2).Checksum())
- if cs != (200, 824):
- print(cs)
- return 'fail'
- return 'success'
+ assert cs == (200, 824)
###############################################################################
# Test LERC compression
-def tiff_read_lerc():
+def test_tiff_read_lerc():
md = gdal.GetDriverByName('GTiff').GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte_lerc.tif', 1, 4672)
return ut.testOpen()
@@ -3822,7 +3096,7 @@ def tiff_read_lerc():
###############################################################################
-def tiff_read_overview_of_external_mask():
+def test_tiff_read_overview_of_external_mask():
filename = '/vsimem/tiff_read_overview_of_external_mask.tif'
gdal.Translate(filename, 'data/byte.tif', options='-b 1 -mask 1')
@@ -3841,161 +3115,11 @@ def tiff_read_overview_of_external_mask():
gdal.Unlink(filename)
gdal.Unlink(filename + '.msk')
- if cs1 != cs2:
- gdaltest.post_reason('fail')
- print(cs1, cs2)
- return 'fail'
- if flags1 != gdal.GMF_PER_DATASET:
- gdaltest.post_reason('fail')
- print(flags1)
- return 'fail'
-
- return 'success'
-
-###############################################################################
-
-
-for item in init_list:
- ut = gdaltest.GDALTest('GTiff', item[0], item[1], item[2])
- if ut is None:
- print('GTiff tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testOpen, item[0]))
-gdaltest_list.append((tiff_read_off))
-gdaltest_list.append((tiff_check_alpha))
-gdaltest_list.append((tiff_read_cmyk_rgba))
-gdaltest_list.append((tiff_read_cmyk_raw))
-gdaltest_list.append((tiff_read_ojpeg))
-gdaltest_list.append((tiff_read_gzip))
-gdaltest_list.append((tiff_read_zip_1))
-gdaltest_list.append((tiff_read_zip_2))
-gdaltest_list.append((tiff_read_zip_3))
-gdaltest_list.append((tiff_read_zip_4))
-gdaltest_list.append((tiff_read_zip_5))
-gdaltest_list.append((tiff_read_tar_1))
-gdaltest_list.append((tiff_read_tar_2))
-gdaltest_list.append((tiff_read_tgz_1))
-gdaltest_list.append((tiff_read_tgz_2))
-gdaltest_list.append((tiff_grads))
-gdaltest_list.append((tiff_citation))
-gdaltest_list.append((tiff_linearparmunits))
-gdaltest_list.append((tiff_linearparmunits2))
-gdaltest_list.append((tiff_g4_split))
-gdaltest_list.append((tiff_multi_images))
-gdaltest_list.append((tiff_vsimem))
-gdaltest_list.append((tiff_vsizip_and_mem))
-gdaltest_list.append((tiff_ProjectedCSTypeGeoKey_only))
-gdaltest_list.append((tiff_GTModelTypeGeoKey_only))
-gdaltest_list.append((tiff_12bitjpeg))
-gdaltest_list.append((tiff_read_stats_from_pam))
-gdaltest_list.append((tiff_read_from_tab))
-gdaltest_list.append((tiff_read_pixelispoint))
-gdaltest_list.append((tiff_read_geomatrix))
-gdaltest_list.append((tiff_read_corrupted_gtiff))
-gdaltest_list.append((tiff_read_tag_without_null_byte))
-gdaltest_list.append((tiff_read_buggy_packbits))
-gdaltest_list.append((tiff_read_rpc_txt))
-gdaltest_list.append((tiff_read_rpc_tif))
-gdaltest_list.append((tiff_small))
-gdaltest_list.append((tiff_dos_strip_chop))
-gdaltest_list.append((tiff_read_exif_and_gps))
-gdaltest_list.append((tiff_jpeg_rgba_pixel_interleaved))
-gdaltest_list.append((tiff_jpeg_rgba_band_interleaved))
-gdaltest_list.append((tiff_read_huge4GB))
-gdaltest_list.append((tiff_read_bigtiff))
-gdaltest_list.append((tiff_read_tiff_metadata))
-gdaltest_list.append((tiff_read_irregular_tile_size_jpeg_in_tiff))
-gdaltest_list.append((tiff_direct_and_virtual_mem_io))
-gdaltest_list.append((tiff_read_empty_nodata_tag))
-gdaltest_list.append((tiff_read_strace_check))
-gdaltest_list.append((tiff_read_readdir_limit_on_open))
-gdaltest_list.append((tiff_read_minisblack_as_rgba))
-gdaltest_list.append((tiff_read_colortable_as_rgba))
-gdaltest_list.append((tiff_read_logl_as_rgba))
-gdaltest_list.append((tiff_read_strip_separate_as_rgba))
-gdaltest_list.append((tiff_read_tiled_separate_as_rgba))
-gdaltest_list.append((tiff_read_scanline_more_than_2GB))
-gdaltest_list.append((tiff_read_wrong_number_extrasamples))
-gdaltest_list.append((tiff_read_one_strip_no_bytecount))
-
-gdaltest_list.append((tiff_read_md1))
-gdaltest_list.append((tiff_read_md2))
-gdaltest_list.append((tiff_read_md3))
-gdaltest_list.append((tiff_read_md4))
-gdaltest_list.append((tiff_read_md5))
-gdaltest_list.append((tiff_read_md6))
-gdaltest_list.append((tiff_read_md7))
-gdaltest_list.append((tiff_read_md8))
-gdaltest_list.append((tiff_read_md9))
-gdaltest_list.append((tiff_read_md10))
-gdaltest_list.append((tiff_read_md11))
-gdaltest_list.append((tiff_read_md12))
-
-gdaltest_list.append((tiff_read_nogeoref))
-gdaltest_list.append((tiff_read_inconsistent_georef))
-gdaltest_list.append((tiff_read_gcp_internal_and_auxxml))
-
-gdaltest_list.append((tiff_read_aux))
-
-gdaltest_list.append((tiff_read_one_band_from_two_bands))
-
-gdaltest_list.append((tiff_read_jpeg_cloud_optimized))
-gdaltest_list.append((tiff_read_corrupted_jpeg_cloud_optimized))
-
-gdaltest_list.append((tiff_read_ycbcr_lzw))
-gdaltest_list.append((tiff_read_ycbcr_int12))
-
-gdaltest_list.append((tiff_read_unit_from_srs))
-gdaltest_list.append((tiff_read_arcgis93_geodataxform_gcp))
-gdaltest_list.append((tiff_read_block_width_above_32bit))
-gdaltest_list.append((tiff_read_image_width_above_32bit))
-gdaltest_list.append((tiff_read_second_image_width_above_32bit))
-gdaltest_list.append((tiff_read_minimum_tiff_tags_no_warning))
-gdaltest_list.append((tiff_read_minimum_tiff_tags_with_warning))
-gdaltest_list.append((tiff_read_unknown_compression))
-gdaltest_list.append((tiff_read_leak_ZIPSetupDecode))
-gdaltest_list.append((tiff_read_excessive_memory_TIFFFillStrip))
-gdaltest_list.append((tiff_read_excessive_memory_TIFFFillStrip2))
-gdaltest_list.append((tiff_read_excessive_memory_TIFFFillTile))
-gdaltest_list.append((tiff_read_big_strip))
-gdaltest_list.append((tiff_read_big_strip_chunky_way))
-gdaltest_list.append((tiff_read_big_tile))
-gdaltest_list.append((tiff_read_huge_tile))
-gdaltest_list.append((tiff_read_huge_number_strips))
-gdaltest_list.append((tiff_read_huge_implied_number_strips))
-gdaltest_list.append((tiff_read_many_blocks))
-gdaltest_list.append((tiff_read_many_blocks_truncated))
-gdaltest_list.append((tiff_read_uint33))
-gdaltest_list.append((tiff_read_corrupted_deflate_singlestrip))
-gdaltest_list.append((tiff_read_packbits_not_enough_data))
-gdaltest_list.append((tiff_read_toomanyblocks))
-gdaltest_list.append((tiff_read_toomanyblocks_separate))
-gdaltest_list.append((tiff_read_size_of_stripbytecount_lower_than_stripcount))
-gdaltest_list.append((tiff_read_stripoffset_types))
-gdaltest_list.append((tiff_read_progressive_jpeg_denial_of_service))
-gdaltest_list.append((tiff_read_old_style_lzw))
-gdaltest_list.append((tiff_read_mmap_interface))
-gdaltest_list.append((tiff_read_jpeg_too_big_last_stripe))
-gdaltest_list.append((tiff_read_negative_scaley))
-gdaltest_list.append((tiff_read_zstd))
-gdaltest_list.append((tiff_read_zstd_corrupted))
-gdaltest_list.append((tiff_read_zstd_corrupted2))
-gdaltest_list.append((tiff_read_1bit_2bands))
-gdaltest_list.append((tiff_read_lerc))
-gdaltest_list.append((tiff_read_overview_of_external_mask))
-
-gdaltest_list.append((tiff_read_online_1))
-gdaltest_list.append((tiff_read_online_2))
-
-gdaltest_list.append((tiff_read_webp))
-gdaltest_list.append((tiff_read_webp_huge_single_strip))
-
-# gdaltest_list = [ tiff_read_mmap_interface ]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('tiff_read')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ assert cs1 == cs2
+ assert flags1 == gdal.GMF_PER_DATASET
+
+###############################################################################
+
+
+
+
diff --git a/autotest/gcore/tiff_srs.py b/autotest/gcore/tiff_srs.py
index 6f39bd6a9021..b74f302bf6f9 100755
--- a/autotest/gcore/tiff_srs.py
+++ b/autotest/gcore/tiff_srs.py
@@ -28,70 +28,18 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
+
+import pytest
from osgeo import gdal
from osgeo import osr
-sys.path.append('../pymod')
-
-import gdaltest
-
-
-###############################################################################
-# Write a geotiff and read it back to check its SRS
-
-class TestTiffSRS(object):
- def __init__(self, epsg_code, use_epsg_code, expected_fail):
- self.epsg_code = epsg_code
- self.use_epsg_code = use_epsg_code
- self.expected_fail = expected_fail
-
- def test(self):
- sr = osr.SpatialReference()
- if isinstance(self.epsg_code, str):
- sr.SetFromUserInput(self.epsg_code)
- else:
- sr.ImportFromEPSG(self.epsg_code)
- if self.use_epsg_code == 0:
- proj4str = sr.ExportToProj4()
- # print(proj4str)
- sr.SetFromUserInput(proj4str)
-
- ds = gdal.GetDriverByName('GTiff').Create('/vsimem/TestTiffSRS.tif', 1, 1)
- ds.SetProjection(sr.ExportToWkt())
- ds = None
-
- ds = gdal.Open('/vsimem/TestTiffSRS.tif')
- wkt = ds.GetProjectionRef()
- sr2 = osr.SpatialReference()
- sr2.SetFromUserInput(wkt)
- ds = None
-
- gdal.Unlink('/vsimem/TestTiffSRS.tif')
-
- if sr.IsSame(sr2) != 1:
- if self.expected_fail:
- print('did not get expected SRS. known to be broken currently. FIXME!')
- # print(sr)
- # print(sr2)
- return 'expected_fail'
-
- gdaltest.post_reason('did not get expected SRS')
- print(sr)
- print(sr2)
- return 'fail'
- else:
- if self.expected_fail:
- print('Succeeded but expected fail...')
-
- return 'success'
###############################################################################
# Test fix for #4677:
-def tiff_srs_without_linear_units():
+def test_tiff_srs_without_linear_units():
sr = osr.SpatialReference()
sr.ImportFromProj4('+proj=vandg +datum=WGS84')
@@ -108,20 +56,13 @@ def tiff_srs_without_linear_units():
gdal.Unlink('/vsimem/tiff_srs_without_linear_units.tif')
- if sr.IsSame(sr2) != 1:
-
- gdaltest.post_reason('did not get expected SRS')
- print(sr)
- print(sr2)
- return 'fail'
-
- return 'success'
+ assert sr.IsSame(sr2) == 1, 'did not get expected SRS'
###############################################################################
# Test COMPDCS without VerticalCSType
-def tiff_srs_compd_cs():
+def test_tiff_srs_compd_cs():
sr = osr.SpatialReference()
# EPSG:7400 without the Authority
@@ -156,28 +97,19 @@ def tiff_srs_compd_cs():
gdal.Unlink('/vsimem/tiff_srs_compd_cs.tif')
- if sr.IsSame(sr2) != 1:
-
- gdaltest.post_reason('did not get expected SRS')
- print(sr)
- print(sr2)
- return 'fail'
-
- return 'success'
+ assert sr.IsSame(sr2) == 1, 'did not get expected SRS'
###############################################################################
# Test reading a GeoTIFF with both StdParallel1 and ScaleAtNatOrigin defined (#5791)
-def tiff_srs_weird_mercator_2sp():
+def test_tiff_srs_weird_mercator_2sp():
ds = gdal.Open('data/weird_mercator_2sp.tif')
gdal.PushErrorHandler()
wkt = ds.GetProjectionRef()
gdal.PopErrorHandler()
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('warning expected')
- return 'fail'
+ assert gdal.GetLastErrorMsg() != '', 'warning expected'
sr2 = osr.SpatialReference()
sr2.SetFromUserInput(wkt)
ds = None
@@ -202,20 +134,13 @@ def tiff_srs_weird_mercator_2sp():
UNIT["metre",1,
AUTHORITY["EPSG","9001"]]]""")
- if sr.IsSame(sr2) != 1:
-
- gdaltest.post_reason('did not get expected SRS')
- print(sr)
- print(sr2)
- return 'fail'
-
- return 'success'
+ assert sr.IsSame(sr2) == 1, 'did not get expected SRS'
###############################################################################
# Test reading ESRI WGS_1984_Web_Mercator_Auxiliary_Sphere
-def tiff_srs_WGS_1984_Web_Mercator_Auxiliary_Sphere():
+def test_tiff_srs_WGS_1984_Web_Mercator_Auxiliary_Sphere():
ds = gdal.Open('data/WGS_1984_Web_Mercator_Auxiliary_Sphere.tif')
wkt = ds.GetProjectionRef()
@@ -224,7 +149,7 @@ def tiff_srs_WGS_1984_Web_Mercator_Auxiliary_Sphere():
wkt = sr.ExportToPrettyWkt()
ds = None
- if wkt != """PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere",
+ assert wkt == """PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere",
GEOGCS["GCS_WGS_1984",
DATUM["D_WGS_1984",
SPHEROID["WGS_1984",6378137.0,298.257223563]],
@@ -237,18 +162,13 @@ def tiff_srs_WGS_1984_Web_Mercator_Auxiliary_Sphere():
PARAMETER["Standard_Parallel_1",0.0],
PARAMETER["Auxiliary_Sphere_Type",0.0],
UNIT["Meter",1.0],
- EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs"]]""":
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
-
- return 'success'
+ EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs"]]"""
###############################################################################
# Test writing and reading various angular units
-def tiff_srs_angular_units():
+def test_tiff_srs_angular_units():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_srs_angular_units.tif', 1, 1)
ds.SetProjection("""GEOGCS["WGS 84 (arc-second)",
@@ -259,11 +179,8 @@ def tiff_srs_angular_units():
ds = None
ds = gdal.Open('/vsimem/tiff_srs_angular_units.tif')
wkt = ds.GetProjectionRef()
- if wkt.find('UNIT["arc-second",4.848136811095361e-06]') < 0 and \
- wkt.find('UNIT["arc-second",4.848136811095361e-006]') < 0: # wine variant
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert (wkt.find('UNIT["arc-second",4.848136811095361e-06]') >= 0 or \
+ wkt.find('UNIT["arc-second",4.848136811095361e-006]') >= 0)
ds = None
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_srs_angular_units.tif', 1, 1)
@@ -275,10 +192,7 @@ def tiff_srs_angular_units():
ds = None
ds = gdal.Open('/vsimem/tiff_srs_angular_units.tif')
wkt = ds.GetProjectionRef()
- if wkt.find('UNIT["arc-minute",0.0002908882086657216]') < 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt.find('UNIT["arc-minute",0.0002908882086657216]') >= 0
ds = None
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_srs_angular_units.tif', 1, 1)
@@ -290,10 +204,7 @@ def tiff_srs_angular_units():
ds = None
ds = gdal.Open('/vsimem/tiff_srs_angular_units.tif')
wkt = ds.GetProjectionRef()
- if wkt.find('UNIT["grad",0.01570796326794897]') < 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt.find('UNIT["grad",0.01570796326794897]') >= 0
ds = None
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_srs_angular_units.tif', 1, 1)
@@ -305,10 +216,7 @@ def tiff_srs_angular_units():
ds = None
ds = gdal.Open('/vsimem/tiff_srs_angular_units.tif')
wkt = ds.GetProjectionRef()
- if wkt.find('UNIT["gon",0.01570796326794897]') < 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt.find('UNIT["gon",0.01570796326794897]') >= 0
ds = None
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_srs_angular_units.tif', 1, 1)
@@ -320,10 +228,7 @@ def tiff_srs_angular_units():
ds = None
ds = gdal.Open('/vsimem/tiff_srs_angular_units.tif')
wkt = ds.GetProjectionRef()
- if wkt.find('UNIT["radian",1]') < 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt.find('UNIT["radian",1]') >= 0
ds = None
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_srs_angular_units.tif', 1, 1)
@@ -335,21 +240,16 @@ def tiff_srs_angular_units():
ds = None
ds = gdal.Open('/vsimem/tiff_srs_angular_units.tif')
wkt = ds.GetProjectionRef()
- if wkt.find('UNIT["custom",1.23]') < 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt.find('UNIT["custom",1.23]') >= 0
ds = None
gdal.Unlink('/vsimem/tiff_srs_angular_units.tif')
- return 'success'
-
###############################################################################
# Test writing and reading a unknown datum but with a known ellipsoid
-def tiff_custom_datum_known_ellipsoid():
+def test_tiff_custom_datum_known_ellipsoid():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_custom_datum_known_ellipsoid.tif', 1, 1)
ds.SetProjection("""GEOGCS["WGS 84 based",
@@ -360,49 +260,36 @@ def tiff_custom_datum_known_ellipsoid():
ds = None
ds = gdal.Open('/vsimem/tiff_custom_datum_known_ellipsoid.tif')
wkt = ds.GetProjectionRef()
- if wkt != 'GEOGCS["WGS 84 based",DATUM["WGS_1984_based",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]':
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt == 'GEOGCS["WGS 84 based",DATUM["WGS_1984_based",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]'
ds = None
gdal.Unlink('/vsimem/tiff_custom_datum_known_ellipsoid.tif')
- return 'success'
-
###############################################################################
# Test reading a GeoTIFF file with only PCS set, but with a ProjLinearUnitsGeoKey
# override to another unit (us-feet) ... (#6210)
-def tiff_srs_epsg_2853_with_us_feet():
+def test_tiff_srs_epsg_2853_with_us_feet():
old_val = gdal.GetConfigOption('GTIFF_IMPORT_FROM_EPSG')
gdal.SetConfigOption('GTIFF_IMPORT_FROM_EPSG', 'YES')
ds = gdal.Open('data/epsg_2853_with_us_feet.tif')
gdal.SetConfigOption('GTIFF_IMPORT_FROM_EPSG', old_val)
wkt = ds.GetProjectionRef()
- if wkt.find('PARAMETER["false_easting",11482916.66') < 0 or wkt.find('UNIT["us_survey_feet",0.3048006') < 0 or wkt.find('2853') >= 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt.find('PARAMETER["false_easting",11482916.66') >= 0 and wkt.find('UNIT["us_survey_feet",0.3048006') >= 0 and wkt.find('2853') < 0
gdal.SetConfigOption('GTIFF_IMPORT_FROM_EPSG', 'NO')
ds = gdal.Open('data/epsg_2853_with_us_feet.tif')
gdal.SetConfigOption('GTIFF_IMPORT_FROM_EPSG', old_val)
wkt = ds.GetProjectionRef()
- if wkt.find('PARAMETER["false_easting",11482916.66') < 0 or wkt.find('UNIT["us_survey_feet",0.3048006') < 0 or wkt.find('2853') >= 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
-
- return 'success'
+ assert wkt.find('PARAMETER["false_easting",11482916.66') >= 0 and wkt.find('UNIT["us_survey_feet",0.3048006') >= 0 and wkt.find('2853') < 0
###############################################################################
# Test reading a SRS with a PCSCitationGeoKey = "LUnits = ..."
-def tiff_srs_PCSCitationGeoKey_LUnits():
+def test_tiff_srs_PCSCitationGeoKey_LUnits():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_srs_PCSCitationGeoKey_LUnits.tif', 1, 1)
ds.SetProjection("""PROJCS["UTM Zone 32, Northern Hemisphere",
@@ -422,167 +309,171 @@ def tiff_srs_PCSCitationGeoKey_LUnits():
ds = None
ds = gdal.Open('/vsimem/tiff_srs_PCSCitationGeoKey_LUnits.tif')
wkt = ds.GetProjectionRef()
- if wkt != 'PROJCS["UTM Zone 32, Northern Hemisphere",GEOGCS["GRS 1980(IUGG, 1980)",DATUM["unknown",SPHEROID["GRS80",6378137,298.257222101],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",9],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",50000000],PARAMETER["false_northing",0],UNIT["Centimeter",0.01]]':
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt == 'PROJCS["UTM Zone 32, Northern Hemisphere",GEOGCS["GRS 1980(IUGG, 1980)",DATUM["unknown",SPHEROID["GRS80",6378137,298.257222101],TOWGS84[0,0,0,0,0,0,0]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",9],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",50000000],PARAMETER["false_northing",0],UNIT["Centimeter",0.01]]'
ds = None
gdal.Unlink('/vsimem/tiff_srs_PCSCitationGeoKey_LUnits.tif')
- return 'success'
-
###############################################################################
# Test reading a geotiff key ProjectionGeoKey (Short,1): Unknown-3856
-def tiff_srs_projection_3856():
+def test_tiff_srs_projection_3856():
ds = gdal.Open('data/projection_3856.tif')
wkt = ds.GetProjectionRef()
ds = None
- if wkt.find('EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs') < 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
-
- return 'success'
+ assert wkt.find('EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs') >= 0
###############################################################################
# Test reading a geotiff with a LOCAL_CS and a Imagine citation
-def tiff_srs_imagine_localcs_citation():
+def test_tiff_srs_imagine_localcs_citation():
ds = gdal.Open('data/imagine_localcs_citation.tif')
wkt = ds.GetProjectionRef()
ds = None
- if wkt != 'LOCAL_CS["Projection Name = UTM Units = meters GeoTIFF Units = meters",UNIT["unknown",1]]':
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
-
- return 'success'
+ assert wkt == 'LOCAL_CS["Projection Name = UTM Units = meters GeoTIFF Units = meters",UNIT["unknown",1]]'
###############################################################################
# Test reading a geotiff with a EPSG code and a TOWGS84 key that must
# override the default coming from EPSG
-def tiff_srs_towgs84_override():
+def test_tiff_srs_towgs84_override():
ds = gdal.Open('data/gtiff_towgs84_override.tif')
wkt = ds.GetProjectionRef()
ds = None
- if wkt.find('TOWGS84[584.8,67,400.3,0.105,0.013,-2.378,10.29]') < 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
-
- return 'success'
+ assert wkt.find('TOWGS84[584.8,67,400.3,0.105,0.013,-2.378,10.29]') >= 0
###############################################################################
# Test reading PCSCitationGeoKey (#7199)
-def tiff_srs_pcscitation():
+def test_tiff_srs_pcscitation():
ds = gdal.Open('data/pcscitation.tif')
wkt = ds.GetProjectionRef()
ds = None
- if wkt.find('PROJCS["mycitation",') != 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
-
- return 'success'
-
-
-gdaltest_list = []
-
-tiff_srs_list = [2758, # tmerc
- 2036, # sterea
- 2046, # tmerc
- 3031, # polar stere (ticket #3220)
- 3032, # polar stere (ticket #3220)
- 32661, # stere
- 3035, # laea
- 2062, # lcc 1SP
- [2065, False, True], # krovak
- 2066, # cass
- 2964, # aea
- 3410, # cea
- 3786, # eqc spherical, method=9823
- 32663, # eqc elliptical, method=9842
- 4087, # eqc WGS 84 / World Equidistant Cylindrical method=1028
- 4088, # eqc World Equidistant Cylindrical (Sphere) method=1029
- 2934, # merc
- 27200, # nzmg
- 2057, # omerc Hotine_Oblique_Mercator_Azimuth_Center
- 3591, # omerc Hotine_Oblique_Mercator
- 29100, # poly
- 2056, # somerc
- 2027, # utm
- 4326, # longlat
- 26943, # lcc 2SP,
- 4328, # geocentric
- 3994, # mercator 2SP
- 26920, # UTM NAD83 special case
- 26720, # UTM NAD27 special case
- 32630, # UTM WGS84 north special case
- 32730, # UTM WGS84 south special case
- 22700, # unknown datum 'Deir_ez_Zor'
- 31491, # Germany Zone projection
- [3857, False, True], # Web Mercator
- [102113, False, True], # ESRI WGS_1984_Web_Mercator
- ]
-
-for item in tiff_srs_list:
- try:
- epsg_code = item[0]
- epsg_broken = item[1]
- epsg_proj4_broken = item[2]
- except TypeError:
- epsg_code = item
- epsg_broken = False
- epsg_proj4_broken = False
-
- ut = TestTiffSRS(epsg_code, 1, epsg_broken)
- gdaltest_list.append((ut.test, "tiff_srs_epsg_%d" % epsg_code))
- ut = TestTiffSRS(epsg_code, 0, epsg_proj4_broken)
- gdaltest_list.append((ut.test, "tiff_srs_proj4_of_epsg_%d" % epsg_code))
-
-tiff_srs_list_proj4 = [['eqdc', '+proj=eqdc +lat_0=%.16g +lon_0=%.16g +lat_1=%.16g +lat_2=%.16g" +x_0=%.16g +y_0=%.16g' % (1, 2, 3, 4, 5, 6)],
- ['mill', '+proj=mill +lat_0=%.16g +lon_0=%.16g +x_0=%.16g +y_0=%.16g +R_A' % (1, 2, 3, 4)],
- ['gnom', '+proj=gnom +lat_0=%.16g +lon_0=%.16g +x_0=%.16g +y_0=%.16g' % (1, 2, 3, 4)],
- ['robin', '+proj=robin +lon_0=%.16g +x_0=%.16g +y_0=%.16g' % (1, 2, 3)],
- ['sinu', '+proj=sinu +lon_0=%.16g +x_0=%.16g +y_0=%.16g' % (1, 2, 3)],
- ]
-for (title, proj4) in tiff_srs_list_proj4:
- ut = TestTiffSRS(proj4, 0, False)
- gdaltest_list.append((ut.test, "tiff_srs_proj4_%s" % title))
-
-gdaltest_list.append(tiff_srs_without_linear_units)
-gdaltest_list.append(tiff_srs_compd_cs)
-gdaltest_list.append(tiff_srs_weird_mercator_2sp)
-gdaltest_list.append(tiff_srs_WGS_1984_Web_Mercator_Auxiliary_Sphere)
-gdaltest_list.append(tiff_srs_angular_units)
-gdaltest_list.append(tiff_custom_datum_known_ellipsoid)
-gdaltest_list.append(tiff_srs_epsg_2853_with_us_feet)
-gdaltest_list.append(tiff_srs_PCSCitationGeoKey_LUnits)
-gdaltest_list.append(tiff_srs_projection_3856)
-gdaltest_list.append(tiff_srs_imagine_localcs_citation)
-gdaltest_list.append(tiff_srs_towgs84_override)
-gdaltest_list.append(tiff_srs_pcscitation)
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('tiff_srs')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ assert wkt.find('PROJCS["mycitation",') == 0
+
+
+def _test_tiff_srs(sr, expect_fail):
+ """
+ This is not a test by itself; it gets called by the tests below.
+ """
+ ds = gdal.GetDriverByName('GTiff').Create('/vsimem/TestTiffSRS.tif', 1, 1)
+ ds.SetProjection(sr.ExportToWkt())
+ ds = None
+
+ ds = gdal.Open('/vsimem/TestTiffSRS.tif')
+ wkt = ds.GetProjectionRef()
+ sr2 = osr.SpatialReference()
+ sr2.SetFromUserInput(wkt)
+ ds = None
+
+ gdal.Unlink('/vsimem/TestTiffSRS.tif')
+
+ if sr.IsSame(sr2) != 1:
+ if expect_fail:
+ pytest.xfail('did not get expected SRS. known to be broken currently. FIXME!')
+
+ print(sr)
+ print(sr2)
+ assert False, 'did not get expected SRS'
+ else:
+ if expect_fail:
+ print('Succeeded but expected fail...')
+
+
+###############################################################################
+# Write a geotiff and read it back to check its SRS
+
+epsg_list = [
+ [2758, False], # tmerc
+ [2036, False], # sterea
+ [2046, False], # tmerc
+ [3031, False], # polar stere (ticket #3220)
+ [3032, False], # polar stere (ticket #3220)
+ [32661, False], # stere
+ [3035, False], # laea
+ [2062, False], # lcc 1SP
+ [2065, True], # krovak
+ [2066, False], # cass
+ [2964, False], # aea
+ [3410, False], # cea
+ [3786, False], # eqc spherical, method=9823
+ [32663, False], # eqc elliptical, method=9842
+ [4087, False], # eqc WGS 84 / World Equidistant Cylindrical method=1028
+ [4088, False], # eqc World Equidistant Cylindrical (Sphere) method=1029
+ [2934, False], # merc
+ [27200, False], # nzmg
+ [2057, False], # omerc Hotine_Oblique_Mercator_Azimuth_Center
+ [3591, False], # omerc Hotine_Oblique_Mercator
+ [29100, False], # poly
+ [2056, False], # somerc
+ [2027, False], # utm
+ [4326, False], # longlat
+ [26943, False], # lcc 2SP,
+ [4328, False], # geocentric
+ [3994, False], # mercator 2SP
+ [26920, False], # UTM NAD83 special case
+ [26720, False], # UTM NAD27 special case
+ [32630, False], # UTM WGS84 north special case
+ [32730, False], # UTM WGS84 south special case
+ [22700, False], # unknown datum 'Deir_ez_Zor'
+ [31491, False], # Germany Zone projection
+ [3857, True], # Web Mercator
+ [102113, True], # ESRI WGS_1984_Web_Mercator
+]
+
+
+@pytest.mark.parametrize('use_epsg_code', [0, 1])
+@pytest.mark.parametrize(
+ 'epsg_code,epsg_proj4_broken',
+ epsg_list,
+ ids=[str(r[0]) for r in epsg_list],
+)
+def test_tiff_srs(use_epsg_code, epsg_code, epsg_proj4_broken):
+ sr = osr.SpatialReference()
+ sr.ImportFromEPSG(epsg_code)
+ expect_fail = False
+ if use_epsg_code == 0:
+ proj4str = sr.ExportToProj4()
+ # print(proj4str)
+ sr.SetFromUserInput(proj4str)
+ expect_fail = epsg_proj4_broken
+
+ _test_tiff_srs(sr, expect_fail)
+
+
+@pytest.mark.parametrize(
+ 'proj4',
+ [
+ '+proj=eqdc +lat_0=%.16g +lon_0=%.16g +lat_1=%.16g +lat_2=%.16g" +x_0=%.16g +y_0=%.16g' % (1, 2, 3, 4, 5, 6),
+ '+proj=mill +lat_0=%.16g +lon_0=%.16g +x_0=%.16g +y_0=%.16g +R_A' % (1, 2, 3, 4),
+ '+proj=gnom +lat_0=%.16g +lon_0=%.16g +x_0=%.16g +y_0=%.16g' % (1, 2, 3, 4),
+ '+proj=robin +lon_0=%.16g +x_0=%.16g +y_0=%.16g' % (1, 2, 3),
+ '+proj=sinu +lon_0=%.16g +x_0=%.16g +y_0=%.16g' % (1, 2, 3),
+ ],
+ ids=[
+ 'eqdc',
+ 'mill',
+ 'gnom',
+ 'robin',
+ 'sinu',
+ ]
+)
+def test_tiff_srs_proj4(proj4):
+ sr = osr.SpatialReference()
+ sr.SetFromUserInput(proj4)
+ _test_tiff_srs(sr, False)
+
+
+
diff --git a/autotest/gcore/tiff_write.py b/autotest/gcore/tiff_write.py
index a61191658485..78b9225b7f3a 100755
--- a/autotest/gcore/tiff_write.py
+++ b/autotest/gcore/tiff_write.py
@@ -34,8 +34,8 @@
import shutil
from osgeo import gdal
from osgeo import osr
+import pytest
-sys.path.append('../pymod')
sys.path.append('../../gdal/swig/python/samples')
import gdaltest
@@ -46,34 +46,26 @@
# Get the GeoTIFF driver, and verify a few things about it.
-def tiff_write_1():
+def test_tiff_write_1():
gdaltest.tiff_drv = gdal.GetDriverByName('GTiff')
- if gdaltest.tiff_drv is None:
- gdaltest.post_reason('GTiff driver not found!')
- return 'fail'
+ assert gdaltest.tiff_drv is not None, 'GTiff driver not found!'
drv_md = gdaltest.tiff_drv.GetMetadata()
- if drv_md['DMD_MIMETYPE'] != 'image/tiff':
- gdaltest.post_reason('mime type is wrong')
- return 'fail'
-
- return 'success'
+ assert drv_md['DMD_MIMETYPE'] == 'image/tiff', 'mime type is wrong'
###############################################################################
# Create a simple file by copying from an existing one.
-def tiff_write_2():
+def test_tiff_write_2():
src_ds = gdal.Open('data/cfloat64.tif')
new_ds = gdaltest.tiff_drv.CreateCopy('tmp/test_2.tif', src_ds)
bnd = new_ds.GetRasterBand(1)
- if bnd.Checksum() != 5028:
- gdaltest.post_reason('Didnt get expected checksum on still-open file')
- return 'fail'
+ assert bnd.Checksum() == 5028, 'Didnt get expected checksum on still-open file'
bnd = None
new_ds = None
@@ -82,26 +74,21 @@ def tiff_write_2():
new_ds = gdal.Open('tmp/test_2.tif')
bnd = new_ds.GetRasterBand(1)
- if bnd.Checksum() != 5028:
- gdaltest.post_reason('Didnt get expected checksum on reopened file')
- return 'fail'
+ assert bnd.Checksum() == 5028, 'Didnt get expected checksum on reopened file'
- if bnd.ComputeRasterMinMax() != (74.0, 255.0):
- gdaltest.post_reason('ComputeRasterMinMax() returned wrong value')
- return 'fail'
+ assert bnd.ComputeRasterMinMax() == (74.0, 255.0), \
+ 'ComputeRasterMinMax() returned wrong value'
bnd = None
new_ds = None
gdaltest.tiff_drv.Delete('tmp/test_2.tif')
- return 'success'
-
###############################################################################
# Create a simple file by copying from an existing one.
-def tiff_write_3():
+def test_tiff_write_3():
src_ds = gdal.Open('data/utmsmall.tif')
@@ -111,27 +98,23 @@ def tiff_write_3():
options=options)
bnd = new_ds.GetRasterBand(1)
- if bnd.Checksum() != 50054:
- gdaltest.post_reason('Didnt get expected checksum on still-open file')
- return 'fail'
+ assert bnd.Checksum() == 50054, 'Didnt get expected checksum on still-open file'
bnd = None
new_ds = None
gdaltest.tiff_drv.Delete('tmp/test_3.tif')
- return 'success'
-
###############################################################################
# Create a tiled file.
-def tiff_write_4():
+def test_tiff_write_4():
try:
from osgeo import gdalnumeric
except ImportError:
- return 'skip'
+ pytest.skip()
options = ['TILED=YES', 'BLOCKXSIZE=32', 'BLOCKYSIZE=32']
@@ -173,15 +156,10 @@ def tiff_write_4():
gt = (0.0, 1.0, 0.0, 50.0, 0.0, -1.0)
new_ds.SetGeoTransform(gt)
- if new_ds.GetRasterBand(1).Checksum() != 21577 \
- or new_ds.GetRasterBand(2).Checksum() != 20950 \
- or new_ds.GetRasterBand(3).Checksum() != 23730:
- gdaltest.post_reason('Wrong checksum.')
- return 'fail'
+ assert new_ds.GetRasterBand(1).Checksum() == 21577 and new_ds.GetRasterBand(2).Checksum() == 20950 and new_ds.GetRasterBand(3).Checksum() == 23730, \
+ 'Wrong checksum.'
- if gt != new_ds.GetGeoTransform():
- gdaltest.post_reason('Wrong geotransform.')
- return 'fail'
+ assert gt == new_ds.GetGeoTransform(), 'Wrong geotransform.'
new_ds.SetMetadata({'TEST_KEY': 'TestValue'})
@@ -189,51 +167,36 @@ def tiff_write_4():
new_ds = gdal.Open('tmp/test_4.tif')
- if new_ds.GetRasterBand(1).Checksum() != 21577 \
- or new_ds.GetRasterBand(2).Checksum() != 20950 \
- or new_ds.GetRasterBand(3).Checksum() != 23730:
- gdaltest.post_reason('Wrong checksum (2).')
- return 'fail'
+ assert new_ds.GetRasterBand(1).Checksum() == 21577 and new_ds.GetRasterBand(2).Checksum() == 20950 and new_ds.GetRasterBand(3).Checksum() == 23730, \
+ 'Wrong checksum (2).'
- if gt != new_ds.GetGeoTransform():
- gdaltest.post_reason('Wrong geotransform(2).')
- return 'fail'
+ assert gt == new_ds.GetGeoTransform(), 'Wrong geotransform(2).'
nd = new_ds.GetRasterBand(1).GetNoDataValue()
- if nd is not None:
- gdaltest.post_reason('Got unexpected nodata value.')
- return 'fail'
+ assert nd is None, 'Got unexpected nodata value.'
md_dict = new_ds.GetMetadata()
- if md_dict['TEST_KEY'] != 'TestValue':
- gdaltest.post_reason('Missing metadata')
- return 'fail'
+ assert md_dict['TEST_KEY'] == 'TestValue', 'Missing metadata'
new_ds = None
gdaltest.tiff_drv.Delete('tmp/test_4.tif')
- return 'success'
-
###############################################################################
# Write a file with GCPs.
-def tiff_write_5():
+def test_tiff_write_5():
src_ds = gdal.Open('data/gcps.vrt')
new_ds = gdaltest.tiff_drv.CreateCopy('tmp/test_5.tif', src_ds)
- if new_ds.GetGCPProjection().find(
- 'AUTHORITY["EPSG","26711"]') == -1:
- gdaltest.post_reason('GCP Projection not set properly.')
- return 'fail'
+ assert (new_ds.GetGCPProjection().find(
+ 'AUTHORITY["EPSG","26711"]') != -1), 'GCP Projection not set properly.'
gcps = new_ds.GetGCPs()
- if len(gcps) != 4:
- gdaltest.post_reason('GCP count wrong.')
- return 'fail'
+ assert len(gcps) == 4, 'GCP count wrong.'
new_ds = None
@@ -246,26 +209,22 @@ def tiff_write_5():
new_ds = gdal.Open('tmp/test_5.tif')
gcps = new_ds.GetGCPs()
- if len(gcps) != 4:
- gdaltest.post_reason('GCP count wrong.')
- return 'fail'
+ assert len(gcps) == 4, 'GCP count wrong.'
new_ds = None
gdaltest.tiff_drv.Delete('tmp/test_5.tif')
- return 'success'
-
###############################################################################
# Test a mixture of reading and writing on a DEFLATE compressed file.
# May crash with libtiff <= 3.8.2, so skip it if BigTIFF is not supported
# (this is a sign of an older libtiff...)
-def tiff_write_6():
+def test_tiff_write_6():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
options = ['TILED=YES', 'BLOCKXSIZE=32', 'BLOCKYSIZE=32',
'COMPRESS=DEFLATE', 'PREDICTOR=2']
@@ -283,27 +242,24 @@ def tiff_write_6():
if buf_read != buf:
gdaltest.tiff_write_6_failed = True
- gdaltest.post_reason('did not get back expected data.')
- return 'fail'
+ pytest.fail('did not get back expected data.')
ds = None
gdaltest.tiff_write_6_failed = False
gdaltest.tiff_drv.Delete('tmp/test_6.tif')
- return 'success'
-
###############################################################################
# Test a mixture of reading and writing on a LZW compressed file.
# Will cause older libtiff versions (<=3.8.2 for sure) to crash, so skip it
# if BigTIFF is not supported (this is a sign of an older libtiff...)
-def tiff_write_7():
+def test_tiff_write_7():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
options = ['TILED=YES', 'COMPRESS=LZW', 'PREDICTOR=2']
ds = gdaltest.tiff_drv.Create('tmp/test_7.tif', 200, 200, 1,
@@ -318,21 +274,17 @@ def tiff_write_7():
ds.FlushCache()
buf_read = ds.ReadRaster(0, 0, 32, 32, buf_type=gdal.GDT_Byte)
- if buf_read != buf:
- gdaltest.post_reason('did not get back expected data.')
- return 'fail'
+ assert buf_read == buf, 'did not get back expected data.'
ds = None
gdaltest.tiff_drv.Delete('tmp/test_7.tif')
- return 'success'
-
###############################################################################
# Test a mixture of reading and writing on a PACKBITS compressed file.
-def tiff_write_8():
+def test_tiff_write_8():
options = ['TILED=YES', 'BLOCKXSIZE=32', 'BLOCKYSIZE=32', 'COMPRESS=PACKBITS']
ds = gdaltest.tiff_drv.Create('tmp/test_8.tif', 200, 200, 1,
@@ -348,21 +300,17 @@ def tiff_write_8():
buf_read = ds.ReadRaster(0, 0, 32, 32, buf_type=gdal.GDT_Byte)
- if buf_read != buf:
- gdaltest.post_reason('did not get back expected data.')
- return 'fail'
+ assert buf_read == buf, 'did not get back expected data.'
ds = None
gdaltest.tiff_drv.Delete('tmp/test_8.tif')
- return 'success'
-
###############################################################################
# Create a simple file by copying from an existing one.
-def tiff_write_9():
+def test_tiff_write_9():
src_ds = gdal.Open('data/byte.tif')
new_ds = gdaltest.tiff_drv.CreateCopy('tmp/test_9.tif', src_ds,
@@ -372,22 +320,18 @@ def tiff_write_9():
new_ds = gdal.Open('tmp/test_9.tif')
bnd = new_ds.GetRasterBand(1)
- if bnd.Checksum() != 5287:
- gdaltest.post_reason('Didnt get expected checksum on reopened file')
- return 'fail'
+ assert bnd.Checksum() == 5287, 'Didnt get expected checksum on reopened file'
bnd = None
new_ds = None
gdaltest.tiff_drv.Delete('tmp/test_9.tif')
- return 'success'
-
###############################################################################
# 1bit file but with band interleaving, and odd size (not multiple of 8) #1957
-def tiff_write_10():
+def test_tiff_write_10():
ut = gdaltest.GDALTest('GTiff', 'oddsize_1bit2b.tif', 2, 5918,
options=['NBITS=1', 'INTERLEAVE=BAND'])
@@ -397,7 +341,7 @@ def tiff_write_10():
# Simple 1 bit file, treated through the GTiffBitmapBand class.
-def tiff_write_11():
+def test_tiff_write_11():
ut = gdaltest.GDALTest('GTiff', 'oddsize1bit.tif', 1, 5918,
options=['NBITS=1', 'COMPRESS=CCITTFAX4'])
@@ -407,28 +351,25 @@ def tiff_write_11():
# Read JPEG Compressed YCbCr subsampled image.
-def tiff_write_12():
+def test_tiff_write_12():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
ds = gdal.Open('data/sasha.tif')
cs = ds.GetRasterBand(3).Checksum()
- if cs != 31952 and cs != 30145:
- return 'fail'
-
- return 'success'
+ assert cs == 31952 or cs == 30145
###############################################################################
# Write JPEG Compressed YCbCr subsampled image.
-def tiff_write_13():
+def test_tiff_write_13():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
src_ds = gdal.Open('data/sasha.tif')
ds = gdaltest.tiff_drv.CreateCopy('tmp/sasha.tif', src_ds, options=['PROFILE=BASELINE',
@@ -445,24 +386,17 @@ def tiff_write_13():
size = os.stat('tmp/sasha.tif').st_size
gdaltest.tiff_drv.Delete('tmp/sasha.tif')
- if cs != 17347 and cs != 14445:
- gdaltest.post_reason('fail: bad checksum')
- print(cs)
- return 'fail'
+ assert cs == 17347 or cs == 14445, 'fail: bad checksum'
if md['LIBTIFF'] == 'INTERNAL':
- if size > 22816:
- gdaltest.post_reason('fail: bad size')
- print(size)
- return 'fail'
-
- return 'success'
+ assert size <= 22816, 'fail: bad size'
+
###############################################################################
# Test creating an in memory copy.
-def tiff_write_14():
+def test_tiff_write_14():
tst = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672)
@@ -473,7 +407,7 @@ def tiff_write_14():
# Test that we can restrict metadata and georeferencing in the output
# file using the PROFILE creation option with CreateCopy()
-def tiff_write_15():
+def test_tiff_write_15():
ds_in = gdal.Open('data/byte.vrt')
@@ -485,14 +419,10 @@ def tiff_write_15():
ds = gdal.Open('tmp/tw_15.tif')
md = ds.GetMetadata()
- if 'test' not in md:
- gdaltest.post_reason('Metadata absent from .aux.xml file.')
- return 'fail'
+ assert 'test' in md, 'Metadata absent from .aux.xml file.'
md = ds.GetRasterBand(1).GetMetadata()
- if 'testBand' not in md:
- gdaltest.post_reason('Metadata absent from .aux.xml file.')
- return 'fail'
+ assert 'testBand' in md, 'Metadata absent from .aux.xml file.'
ds = None
@@ -500,32 +430,25 @@ def tiff_write_15():
ds = gdal.Open('tmp/tw_15.tif')
- if ds.GetGeoTransform() != (0.0, 1.0, 0.0, 0.0, 0.0, 1.0):
- gdaltest.post_reason('Got wrong geotransform, profile ignored?')
- return 'fail'
+ assert ds.GetGeoTransform() == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0), \
+ 'Got wrong geotransform, profile ignored?'
md = ds.GetMetadata()
- if 'test' in md:
- gdaltest.post_reason('Metadata written to BASELINE file.')
- return 'fail'
+ assert 'test' not in md, 'Metadata written to BASELINE file.'
md = ds.GetRasterBand(1).GetMetadata()
- if 'testBand' in md:
- gdaltest.post_reason('Metadata written to BASELINE file.')
- return 'fail'
+ assert 'testBand' not in md, 'Metadata written to BASELINE file.'
ds = None
gdaltest.tiff_drv.Delete('tmp/tw_15.tif')
- return 'success'
-
###############################################################################
# Test that we can restrict metadata and georeferencing in the output
# file using the PROFILE creation option with Create()
-def tiff_write_16():
+def test_tiff_write_16():
ds_in = gdal.Open('data/byte.vrt')
@@ -544,19 +467,14 @@ def tiff_write_16():
ds = None
ds = gdal.Open('tmp/tw_16.tif')
- if ds.GetGeoTransform() != (0.0, 1.0, 0.0, 0.0, 0.0, 1.0):
- gdaltest.post_reason('Got wrong geotransform, profile ignored?')
- return 'fail'
+ assert ds.GetGeoTransform() == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0), \
+ 'Got wrong geotransform, profile ignored?'
md = ds.GetMetadata()
- if 'test' not in md:
- gdaltest.post_reason('Metadata absent from .aux.xml file.')
- return 'fail'
+ assert 'test' in md, 'Metadata absent from .aux.xml file.'
md = ds.GetRasterBand(1).GetMetadata()
- if 'testBand' not in md:
- gdaltest.post_reason('Metadata absent from .aux.xml file.')
- return 'fail'
+ assert 'testBand' in md, 'Metadata absent from .aux.xml file.'
ds = None
@@ -566,32 +484,25 @@ def tiff_write_16():
try:
os.stat('tmp/tw_16.tif.aux.xml')
except OSError:
- gdaltest.post_reason('No .aux.xml file.')
- return 'fail'
+ pytest.fail('No .aux.xml file.')
ds = gdal.Open('tmp/tw_16.tif')
md = ds.GetMetadata()
- if 'test' in md:
- gdaltest.post_reason('Metadata written to BASELINE file.')
- return 'fail'
+ assert 'test' not in md, 'Metadata written to BASELINE file.'
md = ds.GetRasterBand(1).GetMetadata()
- if 'testBand' in md:
- gdaltest.post_reason('Metadata written to BASELINE file.')
- return 'fail'
+ assert 'testBand' not in md, 'Metadata written to BASELINE file.'
ds = None
gdaltest.tiff_drv.Delete('tmp/tw_16.tif')
- return 'success'
-
###############################################################################
# Test writing a TIFF with an RPC tag.
-def tiff_write_17():
+def test_tiff_write_17():
# Translate RPC controlled data to GeoTIFF.
@@ -605,24 +516,19 @@ def tiff_write_17():
ds = None
# Ensure there is no .aux.xml file which might hold the RPC.
- if gdal.VSIStatL(tmpfilename + '.aux.xml'):
- gdaltest.post_reason('unexpectedly found.aux.xml file')
- return 'fail'
+ assert not gdal.VSIStatL(tmpfilename + '.aux.xml'), \
+ 'unexpectedly found.aux.xml file'
# confirm there is no .rpb file created by default.
- if gdal.VSIStatL(tmpfilename + '.RPB'):
- gdaltest.post_reason('unexpectedly found .RPB file')
- return 'fail'
+ assert not gdal.VSIStatL(tmpfilename + '.RPB'), 'unexpectedly found .RPB file'
# confirm there is no _rpc.txt file created by default.
- if gdal.VSIStatL(tmpfilename + '_RPC.TXT'):
- gdaltest.post_reason('unexpectedly found _RPC.TXT file')
- return 'fail'
+ assert not gdal.VSIStatL(tmpfilename + '_RPC.TXT'), \
+ 'unexpectedly found _RPC.TXT file'
# Open the dataset, and confirm the RPC data is still intact.
ds = gdal.Open(tmpfilename)
- if not gdaltest.rpcs_equal(ds.GetMetadata('RPC'), rpc_md):
- return 'fail'
+ assert gdaltest.rpcs_equal(ds.GetMetadata('RPC'), rpc_md)
ds = None
# Modify the RPC
@@ -634,8 +540,7 @@ def tiff_write_17():
ds = None
ds = gdal.Open(tmpfilename)
- if not gdaltest.rpcs_equal(ds.GetMetadata('RPC'), modified_rpc):
- return 'fail'
+ assert gdaltest.rpcs_equal(ds.GetMetadata('RPC'), modified_rpc)
ds = None
# Unset the RPC
@@ -644,24 +549,20 @@ def tiff_write_17():
ds = None
ds = gdal.Open(tmpfilename)
- if ds.GetMetadata('RPC'):
- gdaltest.post_reason('got RPC, but was not expected')
- return 'fail'
+ assert not ds.GetMetadata('RPC'), 'got RPC, but was not expected'
ds = None
gdaltest.tiff_drv.Delete(tmpfilename)
- return 'success'
-
###############################################################################
# Test that above test still work with the optimization in the GDAL_DISABLE_READDIR_ON_OPEN
# case (#3996)
-def tiff_write_17_disable_readdir():
+def test_tiff_write_17_disable_readdir():
oldval = gdal.GetConfigOption('GDAL_DISABLE_READDIR_ON_OPEN')
gdal.SetConfigOption('GDAL_DISABLE_READDIR_ON_OPEN', 'TRUE')
- ret = tiff_write_17()
+ ret = test_tiff_write_17()
gdal.SetConfigOption('GDAL_DISABLE_READDIR_ON_OPEN', oldval)
return ret
@@ -669,7 +570,7 @@ def tiff_write_17_disable_readdir():
# Test writing a TIFF with an RPB file and IMD file.
-def tiff_write_18():
+def test_tiff_write_18():
# Translate RPC controlled data to GeoTIFF.
@@ -680,60 +581,42 @@ def tiff_write_18():
options=['PROFILE=BASELINE'])
# Ensure there is no .aux.xml file which might hold the RPC.
- if gdal.VSIStatL('tmp/tm_18.tif.aux.xml'):
- gdaltest.post_reason('unexpectedly found tm_18.tif.aux.xml file')
- return 'fail'
+ assert not gdal.VSIStatL('tmp/tm_18.tif.aux.xml'), \
+ 'unexpectedly found tm_18.tif.aux.xml file'
# confirm there is an .rpb and .imd file.
- if gdal.VSIStatL('tmp/tw_18.RPB') is None:
- gdaltest.post_reason('missing .RPB file.')
- return 'fail'
- if gdal.VSIStatL('tmp/tw_18.IMD') is None:
- gdaltest.post_reason('missing .IMD file.')
- return 'fail'
+ assert gdal.VSIStatL('tmp/tw_18.RPB') is not None, 'missing .RPB file.'
+ assert gdal.VSIStatL('tmp/tw_18.IMD') is not None, 'missing .IMD file.'
# confirm there is no _rpc.txt file created by default.
- if gdal.VSIStatL('tmp/tw_18_RPC.TXT'):
- gdaltest.post_reason('unexpectedly found _RPC.TXT file')
- return 'fail'
+ assert not gdal.VSIStatL('tmp/tw_18_RPC.TXT'), 'unexpectedly found _RPC.TXT file'
# Open the dataset, and confirm the RPC/IMD data is still intact.
ds = gdal.Open('tmp/tw_18.tif')
- if not gdaltest.rpcs_equal(ds.GetMetadata('RPC'), rpc_md):
- return 'fail'
+ assert gdaltest.rpcs_equal(ds.GetMetadata('RPC'), rpc_md)
imd_md = ds.GetMetadata('IMD')
- if imd_md['version'] != '"R"' \
- or imd_md['numColumns'] != '30324' \
- or imd_md['IMAGE_1.sunEl'] != '39.7':
- gdaltest.post_reason('IMD contents wrong?')
- print(imd_md)
- return 'fail'
+ assert imd_md['version'] == '"R"' and imd_md['numColumns'] == '30324' and imd_md['IMAGE_1.sunEl'] == '39.7', \
+ 'IMD contents wrong?'
ds = None
# Test deferred loading with GetMetadataItem()
ds = gdal.Open('tmp/tw_18.tif')
- if ds.GetMetadataItem('LINE_OFF', 'RPC') != '16201':
- gdaltest.post_reason("wrong value for GetMetadataItem('LINE_OFF', 'RPC')")
- return 'fail'
- if ds.GetMetadataItem('version', 'IMD') != '"R"':
- gdaltest.post_reason("wrong value for GetMetadataItem('version', 'IMD')")
- return 'fail'
+ assert ds.GetMetadataItem('LINE_OFF', 'RPC') == '16201', \
+ "wrong value for GetMetadataItem('LINE_OFF', 'RPC')"
+ assert ds.GetMetadataItem('version', 'IMD') == '"R"', \
+ "wrong value for GetMetadataItem('version', 'IMD')"
ds = None
gdaltest.tiff_drv.Delete('tmp/tw_18.tif')
# Confirm IMD and RPC files are cleaned up. If not likely the
# file list functionality is not working properly.
- if gdal.VSIStatL('tmp/tw_18.RPB'):
- gdaltest.post_reason('RPB did not get cleaned up.')
- return 'fail'
+ assert not gdal.VSIStatL('tmp/tw_18.RPB'), 'RPB did not get cleaned up.'
- if gdal.VSIStatL('tmp/tw_18.IMD'):
- gdaltest.post_reason('IMD did not get cleaned up.')
- return 'fail'
+ assert not gdal.VSIStatL('tmp/tw_18.IMD'), 'IMD did not get cleaned up.'
# Remove the RPC
gdaltest.tiff_drv.CreateCopy('tmp/tw_18.tif', ds_in,
@@ -741,23 +624,19 @@ def tiff_write_18():
ds = gdal.Open('tmp/tw_18.tif', gdal.GA_Update)
ds.SetMetadata(None, 'RPC')
ds = None
- if os.path.exists('tmp/tw_18.RPB'):
- gdaltest.post_reason('RPB did not get removed')
- return 'fail'
+ assert not os.path.exists('tmp/tw_18.RPB'), 'RPB did not get removed'
gdaltest.tiff_drv.Delete('tmp/tw_18.tif')
- return 'success'
-
###############################################################################
# Test that above test still work with the optimization in the GDAL_DISABLE_READDIR_ON_OPEN
# case (#3996)
-def tiff_write_18_disable_readdir():
+def test_tiff_write_18_disable_readdir():
oldval = gdal.GetConfigOption('GDAL_DISABLE_READDIR_ON_OPEN')
gdal.SetConfigOption('GDAL_DISABLE_READDIR_ON_OPEN', 'TRUE')
- ret = tiff_write_18()
+ ret = test_tiff_write_18()
gdal.SetConfigOption('GDAL_DISABLE_READDIR_ON_OPEN', oldval)
return ret
@@ -765,7 +644,7 @@ def tiff_write_18_disable_readdir():
# Test writing a TIFF with an _RPC.TXT
-def tiff_write_rpc_txt():
+def test_tiff_write_rpc_txt():
# Translate RPC controlled data to GeoTIFF.
@@ -792,24 +671,19 @@ def tiff_write_rpc_txt():
pass
# confirm there is no .RPB file created by default.
- try:
+ with pytest.raises(IOError, message='unexpectedly found .RPB file'):
open('tmp/tiff_write_rpc_txt.RPB').read()
- gdaltest.post_reason('unexpectedly found .RPB file')
- return 'fail'
- except IOError:
- pass
+
try:
open('tmp/tiff_write_rpc_txt_RPC.TXT').read()
except IOError:
- gdaltest.post_reason('missing _RPC.TXT file.')
- return 'fail'
+ pytest.fail('missing _RPC.TXT file.')
# Open the dataset, and confirm the RPC data is still intact.
ds = gdal.Open('tmp/tiff_write_rpc_txt.tif')
- if not gdaltest.rpcs_equal(ds.GetMetadata('RPC'), rpc_md):
- return 'fail'
+ assert gdaltest.rpcs_equal(ds.GetMetadata('RPC'), rpc_md)
ds = None
@@ -817,20 +691,16 @@ def tiff_write_rpc_txt():
# Confirm _RPC.TXT file is cleaned up. If not likely the
# file list functionality is not working properly.
- try:
+ with pytest.raises(IOError, message='_RPC.TXT did not get cleaned up.'):
open('tmp/tiff_write_rpc_txt_RPC.TXT').read()
- gdaltest.post_reason('_RPC.TXT did not get cleaned up.')
- return 'fail'
- except IOError:
- pass
-
- return 'success'
+
+
###############################################################################
# Test writing a TIFF with an RPC in .aux.xml
-def tiff_write_rpc_in_pam():
+def test_tiff_write_rpc_in_pam():
ds_in = gdal.Open('data/rpc.vrt')
rpc_md = ds_in.GetMetadata('RPC')
@@ -845,33 +715,26 @@ def tiff_write_rpc_in_pam():
try:
os.stat('tmp/tiff_write_rpc_in_pam.tif.aux.xml')
except OSError:
- gdaltest.post_reason('missing .aux.xml file.')
- return 'fail'
+ pytest.fail('missing .aux.xml file.')
# confirm there is no .RPB file created.
- try:
+ with pytest.raises(IOError, message='unexpectedly found .RPB file'):
open('tmp/tiff_write_rpc_txt.RPB').read()
- gdaltest.post_reason('unexpectedly found .RPB file')
- return 'fail'
- except IOError:
- pass
+
# Open the dataset, and confirm the RPC data is still intact.
ds = gdal.Open('tmp/tiff_write_rpc_in_pam.tif')
- if not gdaltest.rpcs_equal(ds.GetMetadata('RPC'), rpc_md):
- return 'fail'
+ assert gdaltest.rpcs_equal(ds.GetMetadata('RPC'), rpc_md)
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_rpc_in_pam.tif')
-
- return 'success'
###############################################################################
# Test the write of a pixel-interleaved image with NBITS = 7
-def tiff_write_19():
+def test_tiff_write_19():
src_ds = gdal.Open('data/contig_strip.tif')
@@ -883,26 +746,23 @@ def tiff_write_19():
# hopefully it's closed now!
new_ds = gdal.Open('tmp/contig_strip_7.tif')
- if new_ds.GetRasterBand(1).Checksum() != src_ds.GetRasterBand(1).Checksum() or \
- new_ds.GetRasterBand(2).Checksum() != src_ds.GetRasterBand(2).Checksum() or \
- new_ds.GetRasterBand(3).Checksum() != src_ds.GetRasterBand(3).Checksum():
- gdaltest.post_reason('Didnt get expected checksum on reopened file')
- return 'fail'
+ assert (new_ds.GetRasterBand(1).Checksum() == src_ds.GetRasterBand(1).Checksum() and \
+ new_ds.GetRasterBand(2).Checksum() == src_ds.GetRasterBand(2).Checksum() and \
+ new_ds.GetRasterBand(3).Checksum() == src_ds.GetRasterBand(3).Checksum()), \
+ 'Didnt get expected checksum on reopened file'
new_ds = None
src_ds = None
gdaltest.tiff_drv.Delete('tmp/contig_strip_7.tif')
- return 'success'
-
###############################################################################
# Test write and read of some TIFF tags
# Expected to fail (properly) with older libtiff versions (<=3.8.2 for sure)
# Also test unsetting those tags (#5619)
-def tiff_write_20():
+def test_tiff_write_20():
new_ds = gdaltest.tiff_drv.Create('tmp/tags.tif', 1, 1, 1)
@@ -927,23 +787,17 @@ def tiff_write_20():
# hopefully it's closed now!
- try:
+ with pytest.raises(OSError, message='did not expected .aux.xml file'):
os.stat('tmp/tags.tif.aux.xml')
- gdaltest.post_reason('did not expected .aux.xml file')
- return 'fail'
- except OSError:
- pass
+
new_ds = gdal.Open('tmp/tags.tif')
md = new_ds.GetMetadata()
for item in values:
- if item[0] not in md:
- gdaltest.post_reason('Could not find tag %s' % (item[0]))
- return 'fail'
+ assert item[0] in md, ('Could not find tag %s' % (item[0]))
- if md[item[0]] != item[1]:
- gdaltest.post_reason('For tag %s, got %s, expected %s' % (item[0], md[item[0]], item[1]))
- return 'fail'
+ assert md[item[0]] == item[1], \
+ ('For tag %s, got %s, expected %s' % (item[0], md[item[0]], item[1]))
new_ds = None
@@ -952,20 +806,15 @@ def tiff_write_20():
ds.SetMetadataItem('TIFFTAG_SOFTWARE', None)
ds = None
- try:
+ with pytest.raises(OSError, message='did not expected .aux.xml file'):
os.stat('tmp/tags.tif.aux.xml')
- gdaltest.post_reason('did not expected .aux.xml file')
- return 'fail'
- except OSError:
- pass
+
ds = gdal.Open('tmp/tags.tif')
- if ds.GetMetadataItem('TIFFTAG_SOFTWARE') is not None:
- gdaltest.post_reason('expected unset TIFFTAG_SOFTWARE but got %s' % ds.GetMetadataItem('TIFFTAG_SOFTWARE'))
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_DOCUMENTNAME') is None:
- gdaltest.post_reason('expected set TIFFTAG_DOCUMENTNAME but got None')
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_SOFTWARE') is None, \
+ ('expected unset TIFFTAG_SOFTWARE but got %s' % ds.GetMetadataItem('TIFFTAG_SOFTWARE'))
+ assert ds.GetMetadataItem('TIFFTAG_DOCUMENTNAME') is not None, \
+ 'expected set TIFFTAG_DOCUMENTNAME but got None'
ds = None
# Test unsetting all the remaining items
@@ -977,20 +826,15 @@ def tiff_write_20():
got_md = ds.GetMetadata()
ds = None
- if got_md != {}:
- gdaltest.post_reason('expected empty metadata list, but got some')
- print(got_md)
- return 'fail'
+ assert got_md == {}, 'expected empty metadata list, but got some'
gdaltest.tiff_drv.Delete('tmp/tags.tif')
- return 'success'
-
###############################################################################
# Test RGBA images with TIFFTAG_EXTRASAMPLES=EXTRASAMPLE_ASSOCALPHA
-def tiff_write_21():
+def test_tiff_write_21():
src_ds = gdal.Open('data/stefan_full_rgba.tif')
@@ -999,26 +843,21 @@ def tiff_write_21():
new_ds = None
new_ds = gdal.Open('tmp/stefan_full_rgba.tif')
- if new_ds.RasterCount != 4:
- return 'fail'
+ assert new_ds.RasterCount == 4
for i in range(4):
- if new_ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != src_ds.GetRasterBand(i + 1).GetRasterColorInterpretation():
- return 'fail'
- if new_ds.GetRasterBand(i + 1).Checksum() != src_ds.GetRasterBand(i + 1).Checksum():
- return 'fail'
+ assert new_ds.GetRasterBand(i + 1).GetRasterColorInterpretation() == src_ds.GetRasterBand(i + 1).GetRasterColorInterpretation()
+ assert new_ds.GetRasterBand(i + 1).Checksum() == src_ds.GetRasterBand(i + 1).Checksum()
new_ds = None
src_ds = None
gdaltest.tiff_drv.Delete('tmp/stefan_full_rgba.tif')
- return 'success'
-
###############################################################################
# Test RGBA images with TIFFTAG_EXTRASAMPLES=EXTRASAMPLE_UNSPECIFIED
-def tiff_write_22():
+def test_tiff_write_22():
src_ds = gdal.Open('data/stefan_full_rgba_photometric_rgb.tif')
@@ -1027,26 +866,21 @@ def tiff_write_22():
new_ds = None
new_ds = gdal.Open('tmp/stefan_full_rgba_photometric_rgb.tif')
- if new_ds.RasterCount != 4:
- return 'fail'
+ assert new_ds.RasterCount == 4
for i in range(4):
- if new_ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != src_ds.GetRasterBand(i + 1).GetRasterColorInterpretation():
- return 'fail'
- if new_ds.GetRasterBand(i + 1).Checksum() != src_ds.GetRasterBand(i + 1).Checksum():
- return 'fail'
+ assert new_ds.GetRasterBand(i + 1).GetRasterColorInterpretation() == src_ds.GetRasterBand(i + 1).GetRasterColorInterpretation()
+ assert new_ds.GetRasterBand(i + 1).Checksum() == src_ds.GetRasterBand(i + 1).Checksum()
new_ds = None
src_ds = None
gdaltest.tiff_drv.Delete('tmp/stefan_full_rgba_photometric_rgb.tif')
- return 'success'
-
###############################################################################
# Test grey+alpha images with ALPHA=YES
-def tiff_write_23():
+def test_tiff_write_23():
src_ds = gdal.Open('data/stefan_full_greyalpha.tif')
@@ -1055,26 +889,21 @@ def tiff_write_23():
new_ds = None
new_ds = gdal.Open('tmp/stefan_full_greyalpha.tif')
- if new_ds.RasterCount != 2:
- return 'fail'
+ assert new_ds.RasterCount == 2
for i in range(2):
- if new_ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != src_ds.GetRasterBand(i + 1).GetRasterColorInterpretation():
- return 'fail'
- if new_ds.GetRasterBand(i + 1).Checksum() != src_ds.GetRasterBand(i + 1).Checksum():
- return 'fail'
+ assert new_ds.GetRasterBand(i + 1).GetRasterColorInterpretation() == src_ds.GetRasterBand(i + 1).GetRasterColorInterpretation()
+ assert new_ds.GetRasterBand(i + 1).Checksum() == src_ds.GetRasterBand(i + 1).Checksum()
new_ds = None
src_ds = None
gdaltest.tiff_drv.Delete('tmp/stefan_full_greyalpha.tif')
- return 'success'
-
###############################################################################
# Test grey+alpha images without ALPHA=YES
-def tiff_write_24():
+def test_tiff_write_24():
src_ds = gdal.Open('data/stefan_full_greyalpha.tif')
@@ -1083,55 +912,39 @@ def tiff_write_24():
new_ds = None
new_ds = gdal.Open('tmp/stefan_full_greyunspecified.tif')
- if new_ds.RasterCount != 2:
- return 'fail'
+ assert new_ds.RasterCount == 2
for i in range(2):
- if new_ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != src_ds.GetRasterBand(i + 1).GetRasterColorInterpretation():
- return 'fail'
- if new_ds.GetRasterBand(i + 1).Checksum() != src_ds.GetRasterBand(i + 1).Checksum():
- return 'fail'
+ assert new_ds.GetRasterBand(i + 1).GetRasterColorInterpretation() == src_ds.GetRasterBand(i + 1).GetRasterColorInterpretation()
+ assert new_ds.GetRasterBand(i + 1).Checksum() == src_ds.GetRasterBand(i + 1).Checksum()
new_ds = None
src_ds = None
gdaltest.tiff_drv.Delete('tmp/stefan_full_greyunspecified.tif')
- return 'success'
-
###############################################################################
# Read a CIELAB image to test the RGBA image TIFF interface
-def tiff_write_25():
+def test_tiff_write_25():
src_ds = gdal.Open('data/cielab.tif')
- if src_ds.RasterCount != 4:
- return 'fail'
- if src_ds.GetRasterBand(1).Checksum() != 6:
- return 'fail'
- if src_ds.GetRasterBand(2).Checksum() != 3:
- return 'fail'
- if src_ds.GetRasterBand(3).Checksum() != 0:
- return 'fail'
- if src_ds.GetRasterBand(4).Checksum() != 3:
- return 'fail'
- if src_ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_RedBand:
- return 'fail'
- if src_ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_GreenBand:
- return 'fail'
- if src_ds.GetRasterBand(3).GetRasterColorInterpretation() != gdal.GCI_BlueBand:
- return 'fail'
- if src_ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- return 'fail'
+ assert src_ds.RasterCount == 4
+ assert src_ds.GetRasterBand(1).Checksum() == 6
+ assert src_ds.GetRasterBand(2).Checksum() == 3
+ assert src_ds.GetRasterBand(3).Checksum() == 0
+ assert src_ds.GetRasterBand(4).Checksum() == 3
+ assert src_ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_RedBand
+ assert src_ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_GreenBand
+ assert src_ds.GetRasterBand(3).GetRasterColorInterpretation() == gdal.GCI_BlueBand
+ assert src_ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_AlphaBand
src_ds = None
- return 'success'
-
###############################################################################
# Test color table in a 8 bit image
-def tiff_write_26():
+def test_tiff_write_26():
ds = gdaltest.tiff_drv.Create('tmp/ct8.tif', 1, 1, 1, gdal.GDT_Byte)
@@ -1149,26 +962,22 @@ def tiff_write_26():
ds = gdal.Open('tmp/ct8.tif')
ct = ds.GetRasterBand(1).GetRasterColorTable()
- if ct.GetCount() != 256 or \
- ct.GetColorEntry(0) != (255, 255, 255, 255) or \
- ct.GetColorEntry(1) != (255, 255, 0, 255) or \
- ct.GetColorEntry(2) != (255, 0, 255, 255) or \
- ct.GetColorEntry(3) != (0, 255, 255, 255):
- gdaltest.post_reason('Wrong color table entry.')
- return 'fail'
+ assert (ct.GetCount() == 256 and \
+ ct.GetColorEntry(0) == (255, 255, 255, 255) and \
+ ct.GetColorEntry(1) == (255, 255, 0, 255) and \
+ ct.GetColorEntry(2) == (255, 0, 255, 255) and \
+ ct.GetColorEntry(3) == (0, 255, 255, 255)), 'Wrong color table entry.'
ct = None
ds = None
gdaltest.tiff_drv.Delete('tmp/ct8.tif')
- return 'success'
-
###############################################################################
# Test color table in a 16 bit image
-def tiff_write_27():
+def test_tiff_write_27():
ds = gdaltest.tiff_drv.Create('tmp/ct16.tif', 1, 1, 1, gdal.GDT_UInt16)
@@ -1191,13 +1000,11 @@ def tiff_write_27():
ds = gdal.Open('tmp/ct16_copy.tif')
ct = ds.GetRasterBand(1).GetRasterColorTable()
- if ct.GetCount() != 65536 or \
- ct.GetColorEntry(0) != (255, 255, 255, 255) or \
- ct.GetColorEntry(1) != (255, 255, 0, 255) or \
- ct.GetColorEntry(2) != (255, 0, 255, 255) or \
- ct.GetColorEntry(3) != (0, 255, 255, 255):
- gdaltest.post_reason('Wrong color table entry.')
- return 'fail'
+ assert (ct.GetCount() == 65536 and \
+ ct.GetColorEntry(0) == (255, 255, 255, 255) and \
+ ct.GetColorEntry(1) == (255, 255, 0, 255) and \
+ ct.GetColorEntry(2) == (255, 0, 255, 255) and \
+ ct.GetColorEntry(3) == (0, 255, 255, 255)), 'Wrong color table entry.'
ct = None
ds = None
@@ -1205,135 +1012,94 @@ def tiff_write_27():
gdaltest.tiff_drv.Delete('tmp/ct16.tif')
gdaltest.tiff_drv.Delete('tmp/ct16_copy.tif')
- return 'success'
-
###############################################################################
# Test SetRasterColorInterpretation on a 2 channel image
-def tiff_write_28():
+def test_tiff_write_28():
ds = gdaltest.tiff_drv.Create('tmp/greyalpha.tif', 1, 1, 2)
- if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_Undefined:
- return 'fail'
+ assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_Undefined
ds.GetRasterBand(2).SetRasterColorInterpretation(gdal.GCI_AlphaBand)
- if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- return 'fail'
+ assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_AlphaBand
ds = None
ds = gdal.Open('tmp/greyalpha.tif')
- if ds.GetRasterBand(2).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- return 'fail'
+ assert ds.GetRasterBand(2).GetRasterColorInterpretation() == gdal.GCI_AlphaBand
ds = None
gdaltest.tiff_drv.Delete('tmp/greyalpha.tif')
- return 'success'
-
###############################################################################
# Test SetRasterColorInterpretation on a 4 channel image
-def tiff_write_29():
+def test_tiff_write_29():
# When creating a 4 channel image with PHOTOMETRIC=RGB,
# TIFFTAG_EXTRASAMPLES=EXTRASAMPLE_UNSPECIFIED
ds = gdaltest.tiff_drv.Create('/vsimem/rgba.tif', 1, 1, 4, options=['PHOTOMETRIC=RGB'])
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '0':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
- if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_Undefined:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '0'
+ assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_Undefined
# Now turn on alpha
ds.GetRasterBand(4).SetRasterColorInterpretation(gdal.GCI_AlphaBand)
- if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '2':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
+ assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_AlphaBand
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '2'
ds = None
- if gdal.VSIStatL('/vsimem/rgba.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/rgba.tif.aux.xml') is None
ds = gdal.Open('/vsimem/rgba.tif')
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '2':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
- if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '2'
+ assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_AlphaBand
# Test cancelling alpha
gdaltest.tiff_drv.CreateCopy('/vsimem/rgb_no_alpha.tif', ds, options=['ALPHA=NO'])
ds = None
- if gdal.VSIStatL('/vsimem/rgb_no_alpha.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/rgb_no_alpha.tif.aux.xml') is None
ds = gdal.Open('/vsimem/rgb_no_alpha.tif')
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '0':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
- if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_Undefined:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '0'
+ assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_Undefined
# Test re-adding alpha
gdaltest.tiff_drv.CreateCopy('/vsimem/rgb_added_alpha.tif', ds, options=['ALPHA=YES'])
ds = None
- if gdal.VSIStatL('/vsimem/rgb_added_alpha.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/rgb_added_alpha.tif.aux.xml') is None
ds = gdal.Open('/vsimem/rgb_added_alpha.tif')
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '2':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
- if ds.GetRasterBand(4).GetRasterColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '2'
+ assert ds.GetRasterBand(4).GetRasterColorInterpretation() == gdal.GCI_AlphaBand
ds = None
gdaltest.tiff_drv.Delete('/vsimem/rgba.tif')
gdaltest.tiff_drv.Delete('/vsimem/rgb_no_alpha.tif')
gdaltest.tiff_drv.Delete('/vsimem/rgb_added_alpha.tif')
- return 'success'
-
###############################################################################
# Create a BigTIFF image with BigTIFF=YES
-def tiff_write_30():
+def test_tiff_write_30():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/bigtiff.tif', 1, 1, 1, options=['BigTIFF=YES'])
ds = None
ds = gdal.Open('tmp/bigtiff.tif')
- if ds is None:
- return 'fail'
+ assert ds is not None
ds = None
fileobj = open('tmp/bigtiff.tif', mode='rb')
@@ -1344,29 +1110,25 @@ def tiff_write_30():
gdaltest.tiff_drv.Delete('tmp/bigtiff.tif')
# Check BigTIFF signature
- if ((binvalues[2] != 0x2B or binvalues[3] != 0) and
- (binvalues[3] != 0x2B or binvalues[2] != 0)):
- return 'fail'
-
- return 'success'
+ assert (not ((binvalues[2] != 0x2B or binvalues[3] != 0) and
+ (binvalues[3] != 0x2B or binvalues[2] != 0)))
###############################################################################
# Create a BigTIFF image implicitly (more than 4Gb).
-def tiff_write_31():
+def test_tiff_write_31():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/bigtiff.tif', 100000, 100000, 1,
options=['SPARSE_OK=TRUE'])
ds = None
ds = gdal.Open('tmp/bigtiff.tif')
- if ds is None:
- return 'fail'
+ assert ds is not None
ds = None
fileobj = open('tmp/bigtiff.tif', mode='rb')
@@ -1377,17 +1139,14 @@ def tiff_write_31():
gdaltest.tiff_drv.Delete('tmp/bigtiff.tif')
# Check BigTIFF signature
- if ((binvalues[2] != 0x2B or binvalues[3] != 0) and
- (binvalues[3] != 0x2B or binvalues[2] != 0)):
- return 'fail'
-
- return 'success'
+ assert (not ((binvalues[2] != 0x2B or binvalues[3] != 0) and
+ (binvalues[3] != 0x2B or binvalues[2] != 0)))
###############################################################################
# Create a rotated image
-def tiff_write_32():
+def test_tiff_write_32():
ds_in = gdal.Open('data/byte.vrt')
@@ -1414,22 +1173,19 @@ def tiff_write_32():
print('')
print(('old = ', gt))
print(('new = ', new_gt))
- gdaltest.post_reason('Geotransform differs.')
- return 'fail'
+ pytest.fail('Geotransform differs.')
ds = None
gdaltest.tiff_drv.Delete('tmp/byte_rotated.tif')
gdaltest.tiff_drv.Delete('tmp/byte_rotated_copy.tif')
- return 'success'
-
###############################################################################
# Test that metadata is written in .aux.xml file in GeoTIFF profile with CreateCopy
# (BASELINE is tested by tiff_write_15)
-def tiff_write_33():
+def test_tiff_write_33():
ds_in = gdal.Open('data/byte.vrt')
@@ -1442,14 +1198,10 @@ def tiff_write_33():
ds = gdal.Open('tmp/tw_33.tif')
md = ds.GetMetadata()
- if 'test' not in md:
- gdaltest.post_reason('Metadata absent from .aux.xml file.')
- return 'fail'
+ assert 'test' in md, 'Metadata absent from .aux.xml file.'
md = ds.GetRasterBand(1).GetMetadata()
- if 'testBand' not in md:
- gdaltest.post_reason('Metadata absent from .aux.xml file.')
- return 'fail'
+ assert 'testBand' in md, 'Metadata absent from .aux.xml file.'
ds = None
@@ -1459,33 +1211,26 @@ def tiff_write_33():
try:
os.stat('tmp/tw_33.tif.aux.xml')
except OSError:
- gdaltest.post_reason('No .aux.xml file.')
- return 'fail'
+ pytest.fail('No .aux.xml file.')
ds = gdal.Open('tmp/tw_33.tif')
md = ds.GetMetadata()
- if 'test' in md:
- gdaltest.post_reason('Metadata written to GeoTIFF file.')
- return 'fail'
+ assert 'test' not in md, 'Metadata written to GeoTIFF file.'
md = ds.GetRasterBand(1).GetMetadata()
- if 'testBand' in md:
- gdaltest.post_reason('Metadata written to GeoTIFF file.')
- return 'fail'
+ assert 'testBand' not in md, 'Metadata written to GeoTIFF file.'
ds = None
gdaltest.tiff_drv.Delete('tmp/tw_33.tif')
- return 'success'
-
###############################################################################
# Test that metadata is written in .aux.xml file in GeoTIFF profile with Create
# (BASELINE is tested by tiff_write_16)
-def tiff_write_34():
+def test_tiff_write_34():
ds = gdaltest.tiff_drv.Create('tmp/tw_34.tif', 1, 1, gdal.GDT_Byte,
options=['PROFILE=GeoTIFF'])
@@ -1497,14 +1242,10 @@ def tiff_write_34():
ds = gdal.Open('tmp/tw_34.tif')
md = ds.GetMetadata()
- if 'test' not in md:
- gdaltest.post_reason('Metadata absent from .aux.xml file.')
- return 'fail'
+ assert 'test' in md, 'Metadata absent from .aux.xml file.'
md = ds.GetRasterBand(1).GetMetadata()
- if 'testBand' not in md:
- gdaltest.post_reason('Metadata absent from .aux.xml file.')
- return 'fail'
+ assert 'testBand' in md, 'Metadata absent from .aux.xml file.'
ds = None
@@ -1514,33 +1255,26 @@ def tiff_write_34():
try:
os.stat('tmp/tw_34.tif.aux.xml')
except OSError:
- gdaltest.post_reason('No .aux.xml file.')
- return 'fail'
+ pytest.fail('No .aux.xml file.')
ds = gdal.Open('tmp/tw_34.tif')
md = ds.GetMetadata()
- if 'test' in md:
- gdaltest.post_reason('Metadata written to GeoTIFF file.')
- return 'fail'
+ assert 'test' not in md, 'Metadata written to GeoTIFF file.'
md = ds.GetRasterBand(1).GetMetadata()
- if 'testBand' in md:
- gdaltest.post_reason('Metadata written to GeoTIFF file.')
- return 'fail'
+ assert 'testBand' not in md, 'Metadata written to GeoTIFF file.'
ds = None
gdaltest.tiff_drv.Delete('tmp/tw_34.tif')
- return 'success'
-
###############################################################################
# Test fallback from internal storage of Geotiff metadata to PAM storage
# when metadata is too big to fit into the GDALGeotiff tag
-def tiff_write_35():
+def test_tiff_write_35():
# I've no idea why this works, and why this rolled in a
# loop doesn't work... Python gurus please fix that !
@@ -1576,24 +1310,19 @@ def tiff_write_35():
try:
os.stat('tmp/tw_35.tif.aux.xml')
except OSError:
- gdaltest.post_reason('No .aux.xml file.')
- return 'fail'
+ pytest.fail('No .aux.xml file.')
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('tmp/tw_35.tif')
gdal.PopErrorHandler()
md = ds.GetMetadata()
- if 'test' not in md or len(md['test']) != 32768:
- gdaltest.post_reason('Did not get expected metadata.')
- return 'fail'
+ assert 'test' in md and len(md['test']) == 32768, 'Did not get expected metadata.'
ds = None
gdaltest.tiff_drv.Delete('tmp/tw_35.tif')
- return 'success'
-
###############################################################################
# Generic functions for the 8 following tests
@@ -1610,97 +1339,84 @@ def tiff_write_big_odd_bits(vrtfilename, tmpfilename, nbits, interleaving):
ds = gdal.Open(tmpfilename)
bnd = ds.GetRasterBand(1)
cs = bnd.Checksum()
- if cs != 4672:
- gdaltest.post_reason('Didnt get expected checksum on band 1')
- print(cs)
- return 'fail'
+ assert cs == 4672, 'Didnt get expected checksum on band 1'
md = bnd.GetMetadata('IMAGE_STRUCTURE')
- if md['NBITS'] != str(nbits):
- gdaltest.post_reason('Didnt get expected NBITS value')
- return 'fail'
+ assert md['NBITS'] == str(nbits), 'Didnt get expected NBITS value'
bnd = ds.GetRasterBand(2)
- if bnd.Checksum() != 4672:
- gdaltest.post_reason('Didnt get expected checksum on band 2')
- return 'fail'
+ assert bnd.Checksum() == 4672, 'Didnt get expected checksum on band 2'
bnd = ds.GetRasterBand(3)
- if bnd.Checksum() != 4672:
- gdaltest.post_reason('Didnt get expected checksum on band 3')
- return 'fail'
+ assert bnd.Checksum() == 4672, 'Didnt get expected checksum on band 3'
bnd = None
md = ds.GetMetadata('IMAGE_STRUCTURE')
- if md['INTERLEAVE'] != interleaving:
- gdaltest.post_reason('Didnt get expected interleaving')
- return 'fail'
+ assert md['INTERLEAVE'] == interleaving, 'Didnt get expected interleaving'
ds = None
gdaltest.tiff_drv.Delete(tmpfilename)
- return 'success'
-
###############################################################################
# Test copy with NBITS=9, INTERLEAVE=PIXEL
-def tiff_write_36():
+def test_tiff_write_36():
return tiff_write_big_odd_bits('data/uint16_3band.vrt', 'tmp/tw_36.tif', 9, 'PIXEL')
###############################################################################
# Test copy with NBITS=9, INTERLEAVE=BAND
-def tiff_write_37():
+def test_tiff_write_37():
return tiff_write_big_odd_bits('data/uint16_3band.vrt', 'tmp/tw_37.tif', 9, 'BAND')
###############################################################################
# Test copy with NBITS=12, INTERLEAVE=PIXEL
-def tiff_write_38():
+def test_tiff_write_38():
return tiff_write_big_odd_bits('data/uint16_3band.vrt', 'tmp/tw_38.tif', 12, 'PIXEL')
###############################################################################
# Test copy with NBITS=12, INTERLEAVE=BAND
-def tiff_write_39():
+def test_tiff_write_39():
return tiff_write_big_odd_bits('data/uint16_3band.vrt', 'tmp/tw_39.tif', 12, 'BAND')
###############################################################################
# Test copy with NBITS=17, INTERLEAVE=PIXEL
-def tiff_write_40():
+def test_tiff_write_40():
return tiff_write_big_odd_bits('data/uint32_3band.vrt', 'tmp/tw_40tif', 17, 'PIXEL')
###############################################################################
# Test copy with NBITS=17, INTERLEAVE=BAND
-def tiff_write_41():
+def test_tiff_write_41():
return tiff_write_big_odd_bits('data/uint32_3band.vrt', 'tmp/tw_41.tif', 17, 'BAND')
###############################################################################
# Test copy with NBITS=24, INTERLEAVE=PIXEL
-def tiff_write_42():
+def test_tiff_write_42():
return tiff_write_big_odd_bits('data/uint32_3band.vrt', 'tmp/tw_42.tif', 24, 'PIXEL')
###############################################################################
# Test copy with NBITS=24, INTERLEAVE=BAND
-def tiff_write_43():
+def test_tiff_write_43():
return tiff_write_big_odd_bits('data/uint32_3band.vrt', 'tmp/tw_43.tif', 24, 'BAND')
###############################################################################
# Test create with NBITS=9 and preservation through CreateCopy of NBITS
-def tiff_write_44():
+def test_tiff_write_44():
ds = gdaltest.tiff_drv.Create('tmp/tw_44.tif', 1, 1, 1, gdal.GDT_UInt16, options=['NBITS=9'])
ds = None
@@ -1708,9 +1424,7 @@ def tiff_write_44():
bnd = ds.GetRasterBand(1)
md = bnd.GetMetadata('IMAGE_STRUCTURE')
bnd = None
- if md['NBITS'] != '9':
- gdaltest.post_reason('Didnt get expected NBITS value')
- return 'fail'
+ assert md['NBITS'] == '9', 'Didnt get expected NBITS value'
ds2 = gdaltest.tiff_drv.CreateCopy('tmp/tw_44_copy.tif', ds)
ds2 = None
@@ -1719,9 +1433,7 @@ def tiff_write_44():
bnd = ds2.GetRasterBand(1)
md = bnd.GetMetadata('IMAGE_STRUCTURE')
bnd = None
- if md['NBITS'] != '9':
- gdaltest.post_reason('Didnt get expected NBITS value')
- return 'fail'
+ assert md['NBITS'] == '9', 'Didnt get expected NBITS value'
ds = None
ds2 = None
@@ -1729,13 +1441,11 @@ def tiff_write_44():
gdaltest.tiff_drv.Delete('tmp/tw_44.tif')
gdaltest.tiff_drv.Delete('tmp/tw_44_copy.tif')
- return 'success'
-
###############################################################################
# Test create with NBITS=17 and preservation through CreateCopy of NBITS
-def tiff_write_45():
+def test_tiff_write_45():
ds = gdaltest.tiff_drv.Create('tmp/tw_45.tif', 1, 1, 1, gdal.GDT_UInt32, options=['NBITS=17'])
ds = None
@@ -1743,9 +1453,7 @@ def tiff_write_45():
bnd = ds.GetRasterBand(1)
md = bnd.GetMetadata('IMAGE_STRUCTURE')
bnd = None
- if md['NBITS'] != '17':
- gdaltest.post_reason('Didnt get expected NBITS value')
- return 'fail'
+ assert md['NBITS'] == '17', 'Didnt get expected NBITS value'
ds2 = gdaltest.tiff_drv.CreateCopy('tmp/tw_45_copy.tif', ds)
ds2 = None
@@ -1754,9 +1462,7 @@ def tiff_write_45():
bnd = ds2.GetRasterBand(1)
md = bnd.GetMetadata('IMAGE_STRUCTURE')
bnd = None
- if md['NBITS'] != '17':
- gdaltest.post_reason('Didnt get expected NBITS value')
- return 'fail'
+ assert md['NBITS'] == '17', 'Didnt get expected NBITS value'
ds = None
ds2 = None
@@ -1764,13 +1470,11 @@ def tiff_write_45():
gdaltest.tiff_drv.Delete('tmp/tw_45.tif')
gdaltest.tiff_drv.Delete('tmp/tw_45_copy.tif')
- return 'success'
-
###############################################################################
# Test correct round-tripping of ReadBlock/WriteBlock
-def tiff_write_46():
+def test_tiff_write_46():
import struct
with gdaltest.SetCacheMax(0):
@@ -1798,9 +1502,7 @@ def tiff_write_46():
# We expect (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
got = struct.unpack('B' * 10, data)
for g in got:
- if g != 1:
- print(got)
- return 'fail'
+ assert g == 1, got
ds = None
ds2 = None
@@ -1809,23 +1511,21 @@ def tiff_write_46():
gdaltest.tiff_drv.Delete('tmp/tiff_write_46_2.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_46_3.tif')
- return 'success'
-
###############################################################################
# Test #2457
-def tiff_write_47():
+def test_tiff_write_47():
with gdaltest.SetCacheMax(0):
- ret = tiff_write_3()
+ ret = test_tiff_write_3()
return ret
###############################################################################
# Test #2457 with nYOff of RasterIO not aligned on the block height
-def tiff_write_48():
+def test_tiff_write_48():
with gdaltest.SetCacheMax(0):
@@ -1839,21 +1539,17 @@ def tiff_write_48():
new_ds = None
new_ds = gdal.Open('tmp/tiff_write_48.tif')
- if new_ds.GetRasterBand(1).Checksum() != 50054:
- gdaltest.post_reason('Didnt get expected checksum ')
- return 'fail'
+ assert new_ds.GetRasterBand(1).Checksum() == 50054, 'Didnt get expected checksum '
new_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_48.tif')
- return 'success'
-
###############################################################################
# Test copying a CMYK TIFF into another CMYK TIFF
-def tiff_write_49():
+def test_tiff_write_49():
# We open the source as RAW to get the CMYK bands
src_ds = gdal.Open('GTIFF_RAW:data/rgbsmall_cmyk.tif')
@@ -1861,32 +1557,27 @@ def tiff_write_49():
new_ds = gdal.GetDriverByName("GTiff").CreateCopy('tmp/tiff_write_49.tif', src_ds, options=['PHOTOMETRIC=CMYK'])
# At this point, for the purpose of the copy, the dataset will have been opened as RAW
- if new_ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_CyanBand:
- gdaltest.post_reason('Wrong color interpretation.')
- print(new_ds.GetRasterBand(1).GetRasterColorInterpretation())
- return 'fail'
+ assert new_ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_CyanBand, \
+ 'Wrong color interpretation.'
new_ds = None
new_ds = gdal.Open('GTIFF_RAW:tmp/tiff_write_49.tif')
for i in range(4):
- if new_ds.GetRasterBand(i + 1).Checksum() != src_ds.GetRasterBand(i + 1).Checksum():
- gdaltest.post_reason('Didnt get expected checksum ')
- return 'fail'
+ assert new_ds.GetRasterBand(i + 1).Checksum() == src_ds.GetRasterBand(i + 1).Checksum(), \
+ 'Didnt get expected checksum '
src_ds = None
new_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_49.tif')
- return 'success'
-
###############################################################################
# Test creating a CMYK TIFF from another CMYK TIFF
-def tiff_write_50():
+def test_tiff_write_50():
# We open the source as RAW to get the CMYK bands
src_ds = gdal.Open('GTIFF_RAW:data/rgbsmall_cmyk.tif')
@@ -1896,33 +1587,28 @@ def tiff_write_50():
data = src_ds.GetRasterBand(i + 1).ReadRaster(0, 0, src_ds.RasterXSize, src_ds.RasterYSize)
new_ds.GetRasterBand(i + 1).WriteRaster(0, 0, src_ds.RasterXSize, src_ds.RasterYSize, data)
- if new_ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_CyanBand:
- gdaltest.post_reason('Wrong color interpretation.')
- print(new_ds.GetRasterBand(1).GetRasterColorInterpretation())
- return 'fail'
+ assert new_ds.GetRasterBand(1).GetRasterColorInterpretation() == gdal.GCI_CyanBand, \
+ 'Wrong color interpretation.'
new_ds = None
new_ds = gdal.Open('GTIFF_RAW:tmp/tiff_write_50.tif')
for i in range(4):
- if new_ds.GetRasterBand(i + 1).Checksum() != src_ds.GetRasterBand(i + 1).Checksum():
- gdaltest.post_reason('Didnt get expected checksum ')
- return 'fail'
+ assert new_ds.GetRasterBand(i + 1).Checksum() == src_ds.GetRasterBand(i + 1).Checksum(), \
+ 'Didnt get expected checksum '
src_ds = None
new_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_50.tif')
- return 'success'
-
###############################################################################
# Test proper clearing of existing GeoTIFF tags when updating the projection.
# http://trac.osgeo.org/gdal/ticket/2546
-def tiff_write_51():
+def test_tiff_write_51():
shutil.copyfile('data/utmsmall.tif', 'tmp/tiff_write_51.tif')
ds = gdal.Open('tmp/tiff_write_51.tif', gdal.GA_Update)
@@ -1946,28 +1632,22 @@ def tiff_write_51():
expected_wkt = ds.GetProjection()
ds = None
- if wkt.find('NAD') != -1 or wkt.find('North Am') != -1:
- gdaltest.post_reason('It appears the NAD27 datum was not properly cleared.')
- return 'fail'
+ assert wkt.find('NAD') == -1 and wkt.find('North Am') == -1, \
+ 'It appears the NAD27 datum was not properly cleared.'
- if wkt != expected_wkt or wkt.find('WGS 84 / UTM zone 1N') == -1:
- print(wkt)
- print(expected_wkt)
- gdaltest.post_reason('coordinate system does not exactly match.')
- return 'fail'
+ assert wkt == expected_wkt and wkt.find('WGS 84 / UTM zone 1N') != -1, \
+ 'coordinate system does not exactly match.'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_51.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_51_ref.tif')
- return 'success'
-
###############################################################################
# Test the ability to update a paletted TIFF files color table.
-def tiff_write_52():
+def test_tiff_write_52():
shutil.copyfile('data/test_average_palette.tif', 'tmp/tiff_write_52.tif')
test_ct_data = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255, 0)]
@@ -1983,23 +1663,18 @@ def tiff_write_52():
ds = gdal.Open('tmp/tiff_write_52.tif')
ct = ds.GetRasterBand(1).GetRasterColorTable()
- if ct.GetColorEntry(0) != (255, 0, 0, 255):
- print((ct.GetColorEntry(0)))
- gdaltest.post_reason('Did not get expected color 0.')
- return 'fail'
+ assert ct.GetColorEntry(0) == (255, 0, 0, 255), 'Did not get expected color 0.'
ct = None
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_52.tif')
- return 'success'
-
###############################################################################
# Test the ability to create a paletted image and then update later.
-def tiff_write_53():
+def test_tiff_write_53():
test_ct_data = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255, 0)]
test_ct = gdal.ColorTable()
@@ -2019,24 +1694,19 @@ def tiff_write_53():
ds = gdal.Open('tmp/tiff_write_53.tif')
ct = ds.GetRasterBand(1).GetRasterColorTable()
- if ct.GetColorEntry(0) != (255, 0, 0, 255):
- print((ct.GetColorEntry(0)))
- gdaltest.post_reason('Did not get expected color 0.')
- return 'fail'
+ assert ct.GetColorEntry(0) == (255, 0, 0, 255), 'Did not get expected color 0.'
ct = None
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_53.tif')
- return 'success'
-
###############################################################################
# Same as before except we create an overview before reopening the file and
# adding the color table
-def tiff_write_53_bis():
+def test_tiff_write_53_bis():
test_ct_data = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255, 0)]
test_ct = gdal.ColorTable()
@@ -2057,28 +1727,23 @@ def tiff_write_53_bis():
ds = gdal.Open('tmp/tiff_write_53_bis.tif')
ct = ds.GetRasterBand(1).GetRasterColorTable()
- if ct.GetColorEntry(0) != (255, 0, 0, 255):
- print((ct.GetColorEntry(0)))
- gdaltest.post_reason('Did not get expected color 0.')
- return 'fail'
+ assert ct.GetColorEntry(0) == (255, 0, 0, 255), 'Did not get expected color 0.'
ct = None
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_53_bis.tif')
- return 'success'
-
###############################################################################
# Test the ability to create a JPEG compressed TIFF, with PHOTOMETRIC=YCBCR
# and write data into it without closing it and re-opening it (#2645)
-def tiff_write_54():
+def test_tiff_write_54():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_54.tif',
256, 256, 3,
@@ -2093,18 +1758,13 @@ def tiff_write_54():
gdaltest.tiff_drv.Delete('tmp/tiff_write_54.tif')
- if cs == 0:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs != 0, 'did not get expected checksum'
###############################################################################
# Test creating and reading an equirectangular file with all parameters (#2706)
-def tiff_write_55():
+def test_tiff_write_55():
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_55.tif',
256, 256, 1)
@@ -2119,25 +1779,21 @@ def tiff_write_55():
srs = ds.GetProjectionRef()
ds = None
- if srs != srs_expected:
- print(srs)
- gdaltest.post_reason('failed to preserve Equirectangular projection as expected, old libgeotiff?')
- return 'fail'
+ assert srs == srs_expected, \
+ 'failed to preserve Equirectangular projection as expected, old libgeotiff?'
gdaltest.tiff_drv.Delete('tmp/tiff_write_55.tif')
- return 'success'
-
###############################################################################
# Test clearing the colormap from an existing paletted TIFF file.
-def tiff_write_56():
+def test_tiff_write_56():
md = gdaltest.tiff_drv.GetMetadata()
# Expected to fail with libtiff < 4.0 as it needs TIFFUnsetField, so skip it
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
test_ct_data = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255, 0)]
@@ -2160,27 +1816,23 @@ def tiff_write_56():
ds = gdal.Open('tmp/tiff_write_56.tif')
ct = ds.GetRasterBand(1).GetRasterColorTable()
- if ct is not None:
- gdaltest.post_reason('color table seemingly not cleared.')
- return 'fail'
+ assert ct is None, 'color table seemingly not cleared.'
ct = None
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_56.tif')
- return 'success'
-
###############################################################################
# Test replacing normal norm up georef with rotated georef (#2625)
-def tiff_write_57():
+def test_tiff_write_57():
md = gdaltest.tiff_drv.GetMetadata()
# Expected to fail with libtiff < 4.0 as it needs TIFFUnsetField, so skip it
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
# copy a file to tmp dir to modify.
open('tmp/tiff57.tif', 'wb').write(open('data/byte.tif', 'rb').read())
@@ -2195,20 +1847,16 @@ def tiff_write_57():
gt = ds.GetGeoTransform()
ds = None
- if gt != (100, 1, 3, 200, 3, 1):
- print(gt)
- gdaltest.post_reason('did not get expected geotransform, perhaps unset is not working?')
- return 'fail'
+ assert gt == (100, 1, 3, 200, 3, 1), \
+ 'did not get expected geotransform, perhaps unset is not working?'
gdaltest.tiff_drv.Delete('tmp/tiff57.tif')
- return 'success'
-
###############################################################################
# Test writing partial end strips (#2748)
-def tiff_write_58():
+def test_tiff_write_58():
md = gdaltest.tiff_drv.GetMetadata()
@@ -2220,22 +1868,19 @@ def tiff_write_58():
ds = None
ds = gdal.Open('tmp/tiff_write_58.tif')
- if ds.GetRasterBand(1).Checksum() != 65241:
- gdaltest.post_reason('wrong checksum')
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 65241, 'wrong checksum'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_58.tif')
else:
print(('Skipping compression method %s' % compression))
- return 'success'
-
+
###############################################################################
# Test fix for #2759
-def tiff_write_59():
+def test_tiff_write_59():
import struct
ret = 'success'
@@ -2285,7 +1930,7 @@ def tiff_write_59():
# Test fix for #2760
-def tiff_write_60():
+def test_tiff_write_60():
tuples = [('TFW=YES', 'tmp/tiff_write_60.tfw'),
('WORLDFILE=YES', 'tmp/tiff_write_60.wld')]
@@ -2300,19 +1945,14 @@ def tiff_write_60():
with gdaltest.error_handler():
ds = gdal.Open('tmp/tiff_write_60.tif')
- if ds.GetGeoTransform() != gt:
- gdaltest.post_reason('case1: %s != %s' % (ds.GetGeoTransform(), gt))
- return 'fail'
+ assert ds.GetGeoTransform() == gt, ('case1: %s != %s' % (ds.GetGeoTransform(), gt))
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_60.tif')
- try:
+ with pytest.raises(OSError, message='%s should have been deleted' % options_tuple[1]):
os.stat(options_tuple[1])
- gdaltest.post_reason('%s should have been deleted' % options_tuple[1])
- return 'fail'
- except OSError:
- pass
+
# CreateCopy case
src_ds = gdal.Open('data/byte.tif')
@@ -2324,39 +1964,33 @@ def tiff_write_60():
gdal.Unlink('tmp/tiff_write_60.tif.aux.xml')
ds = gdal.Open('tmp/tiff_write_60.tif')
- if ds.GetGeoTransform() != gt:
- gdaltest.post_reason('case2: %s != %s' % (ds.GetGeoTransform(), gt))
- return 'fail'
+ assert ds.GetGeoTransform() == gt, \
+ ('case2: %s != %s' % (ds.GetGeoTransform(), gt))
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_60.tif')
- try:
+ with pytest.raises(OSError, message='%s should have been deleted' % options_tuple[1]):
os.stat(options_tuple[1])
- gdaltest.post_reason('%s should have been deleted' % options_tuple[1])
- return 'fail'
- except OSError:
- pass
-
- return 'success'
+
+
###############################################################################
# Test BigTIFF=IF_NEEDED creation option
-def tiff_write_61():
+def test_tiff_write_61():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/bigtiff.tif', 50000, 50000, 1,
options=['BIGTIFF=IF_NEEDED', 'SPARSE_OK=TRUE'])
ds = None
ds = gdal.Open('tmp/bigtiff.tif')
- if ds is None:
- return 'fail'
+ assert ds is not None
ds = None
fileobj = open('tmp/bigtiff.tif', mode='rb')
@@ -2367,29 +2001,25 @@ def tiff_write_61():
gdaltest.tiff_drv.Delete('tmp/bigtiff.tif')
# Check classical TIFF signature
- if ((binvalues[2] != 0x2A or binvalues[3] != 0) and
- (binvalues[3] != 0x2A or binvalues[2] != 0)):
- return 'fail'
-
- return 'success'
+ assert (not ((binvalues[2] != 0x2A or binvalues[3] != 0) and
+ (binvalues[3] != 0x2A or binvalues[2] != 0)))
###############################################################################
# Test BigTIFF=IF_SAFER creation option
-def tiff_write_62():
+def test_tiff_write_62():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/bigtiff.tif', 50000, 50000, 1,
options=['BIGTIFF=IF_SAFER', 'SPARSE_OK=TRUE'])
ds = None
ds = gdal.Open('tmp/bigtiff.tif')
- if ds is None:
- return 'fail'
+ assert ds is not None
ds = None
fileobj = open('tmp/bigtiff.tif', mode='rb')
@@ -2400,23 +2030,20 @@ def tiff_write_62():
gdaltest.tiff_drv.Delete('tmp/bigtiff.tif')
# Check BigTIFF signature
- if ((binvalues[2] != 0x2B or binvalues[3] != 0) and
- (binvalues[3] != 0x2B or binvalues[2] != 0)):
- return 'fail'
-
- return 'success'
+ assert (not ((binvalues[2] != 0x2B or binvalues[3] != 0) and
+ (binvalues[3] != 0x2B or binvalues[2] != 0)))
###############################################################################
# Test BigTIFF=NO creation option when creating a BigTIFF file would be required
-def tiff_write_63():
+def test_tiff_write_63():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if int(gdal.VersionInfo('VERSION_NUM')) < 1700:
- return 'skip'
+ pytest.skip()
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdaltest.tiff_drv.Create('tmp/bigtiff.tif', 150000, 150000, 1,
@@ -2424,15 +2051,15 @@ def tiff_write_63():
gdal.PopErrorHandler()
if ds is None:
- return 'success'
+ return
- return 'fail'
+ pytest.fail()
###############################################################################
# Test returned projection in WKT format for a WGS84 GeoTIFF (#2787)
-def tiff_write_64():
+def test_tiff_write_64():
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_64.tif', 1, 1, 1)
srs = osr.SpatialReference()
@@ -2446,21 +2073,15 @@ def tiff_write_64():
expected_wkt = """GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]]"""
- if wkt != expected_wkt:
- print(wkt)
- print(expected_wkt)
- gdaltest.post_reason('coordinate system does not exactly match.')
- return 'fail'
+ assert wkt == expected_wkt, 'coordinate system does not exactly match.'
gdaltest.tiff_drv.Delete('tmp/tiff_write_64.tif')
- return 'success'
-
###############################################################################
# Verify that we can write XML metadata.
-def tiff_write_65():
+def test_tiff_write_65():
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_65.tif', 10, 10)
@@ -2473,75 +2094,61 @@ def tiff_write_65():
md = ds.GetMetadata('xml:test')
ds = None
- if len(md) != 1 or md[0] != doc:
- gdaltest.post_reason('did not get xml back clean')
- return 'fail'
+ assert len(md) == 1 and md[0] == doc, 'did not get xml back clean'
gdaltest.tiff_drv.Delete('tmp/tiff_write_65.tif')
- return 'success'
-
###############################################################################
# Verify that we can write and read a band-interleaved GeoTIFF with 65535 bands (#2838)
-def tiff_write_66():
+def test_tiff_write_66():
if gdal.GetConfigOption('SKIP_MEM_INTENSIVE_TEST') is not None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_66.tif', 1, 1, 65535, options=['INTERLEAVE=BAND'])
ds = None
ds = gdal.Open('tmp/tiff_write_66.tif')
- if ds.RasterCount != 65535:
- return 'fail'
+ assert ds.RasterCount == 65535
- if ds.GetRasterBand(1).Checksum() != 0:
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 0
- if ds.GetRasterBand(65535).Checksum() != 0:
- return 'fail'
+ assert ds.GetRasterBand(65535).Checksum() == 0
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_66.tif')
- return 'success'
-
###############################################################################
# Verify that we can write and read a pixel-interleaved GeoTIFF with 65535 bands (#2838)
-def tiff_write_67():
+def test_tiff_write_67():
if gdal.GetConfigOption('SKIP_MEM_INTENSIVE_TEST') is not None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_67.tif', 1, 1, 65535, options=['INTERLEAVE=PIXEL'])
ds = None
ds = gdal.Open('tmp/tiff_write_67.tif')
- if ds.RasterCount != 65535:
- return 'fail'
+ assert ds.RasterCount == 65535
- if ds.GetRasterBand(1).Checksum() != 0:
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 0
- if ds.GetRasterBand(65535).Checksum() != 0:
- return 'fail'
+ assert ds.GetRasterBand(65535).Checksum() == 0
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_67.tif')
- return 'success'
-
###############################################################################
# Verify that we can set the color table after a Create() (scenario hit by map.tif in #2820)
-def tiff_write_68():
+def test_tiff_write_68():
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_68.tif', 151, 161, options=['COMPRESS=LZW'])
ct = gdal.ColorTable()
@@ -2554,38 +2161,31 @@ def tiff_write_68():
ds = None
ds = gdal.Open('tmp/tiff_write_68.tif')
- if ds.GetRasterBand(1).Checksum() == 0:
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() != 0
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_68.tif')
- return 'success'
-
###############################################################################
# Verify GTiffRasterBand::NullBlock() when reading empty block without any nodata value set
-def tiff_write_69():
+def test_tiff_write_69():
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_69.tif', 32, 32, 1, gdal.GDT_Int16, options=['SPARSE_OK=YES'])
ds = None
ds = gdal.Open('tmp/tiff_write_69.tif')
- if ds.GetRasterBand(1).Checksum() != 0:
- print((ds.GetRasterBand(1).Checksum()))
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 0
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_69.tif')
- return 'success'
-
###############################################################################
# Verify GTiffRasterBand::NullBlock() when reading empty block with nodata value set
-def tiff_write_70():
+def test_tiff_write_70():
ref_ds = gdaltest.tiff_drv.Create('tmp/tiff_write_70_ref.tif', 32, 32, 1, gdal.GDT_Int16)
ref_ds.GetRasterBand(1).Fill(-32768)
@@ -2597,10 +2197,8 @@ def tiff_write_70():
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_70.tif', 32, 32, 1, gdal.GDT_Int16, options=['SPARSE_OK=YES'])
ds.GetRasterBand(1).SetNoDataValue(0)
- if os.stat('tmp/tiff_write_70.tif').st_size > 8:
- gdaltest.post_reason('directory should not be crystallized')
- print(os.stat('tmp/tiff_write_70.tif').st_size)
- return 'fail'
+ assert os.stat('tmp/tiff_write_70.tif').st_size <= 8, \
+ 'directory should not be crystallized'
ds = None
ds = gdal.Open('tmp/tiff_write_70.tif', gdal.GA_Update)
@@ -2608,56 +2206,41 @@ def tiff_write_70():
ds = None
ds = gdal.Open('tmp/tiff_write_70.tif')
- if ds.GetRasterBand(1).Checksum() != expected_cs:
- gdaltest.post_reason('wrong checksum')
- print((ds.GetRasterBand(1).Checksum()))
- print(expected_cs)
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == expected_cs, 'wrong checksum'
ds = None
ds = gdal.Open('tmp/tiff_write_70.tif', gdal.GA_Update)
- if ds.GetRasterBand(1).DeleteNoDataValue() != 0:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetNoDataValue() is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).DeleteNoDataValue() == 0
+ assert ds.GetRasterBand(1).GetNoDataValue() is None
ds = None
- try:
+ with pytest.raises(OSError):
os.stat('tmp/tiff_write_70.tif.aux.xml')
- gdaltest.post_reason('fail')
- return 'fail'
- except OSError:
- pass
+
ds = gdal.Open('tmp/tiff_write_70.tif')
- if ds.GetRasterBand(1).GetNoDataValue() is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetNoDataValue() is None
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_70.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_70_ref.tif')
- return 'success'
-
###############################################################################
# Test reading in a real BigTIFF file (on filesystems supporting sparse files)
-def tiff_write_71():
+def test_tiff_write_71():
import struct
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
# Determine if the filesystem supports sparse files (we don't want to create a real 10 GB
# file !
if not gdaltest.filesystem_supports_sparse_files('tmp'):
- return 'skip'
+ pytest.skip()
header = open('data/bigtiff_header_extract.tif', 'rb').read()
@@ -2682,20 +2265,17 @@ def tiff_write_71():
ds = gdal.Open('tmp/tiff_write_71.tif')
data = ds.GetRasterBand(1).ReadRaster(99999, 99999, 1, 1)
- if struct.unpack('b', data)[0] != 0x78:
- return 'fail'
+ assert struct.unpack('b', data)[0] == 0x78
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_71.tif')
- return 'success'
-
###############################################################################
# With CreateCopy(), check that TIFF directory is in the first bytes of the file
# and has not been rewritten later (#3021)
-def tiff_write_72():
+def test_tiff_write_72():
shutil.copyfile('data/byte.tif', 'tmp/byte.tif')
ds = gdal.Open('tmp/byte.tif', gdal.GA_Update)
@@ -2718,21 +2298,18 @@ def tiff_write_72():
fileobj.close()
# Directory should be at offset 8 of the file
- if not (binvalues[0] == 0x08 and binvalues[1] == 0x00 and binvalues[2] == 0x00 and binvalues[3] == 0x00):
- gdaltest.post_reason('Failed with profile %s' % profile)
- return 'fail'
+ assert (binvalues[0] == 0x08 and binvalues[1] == 0x00 and binvalues[2] == 0x00 and binvalues[3] == 0x00), \
+ ('Failed with profile %s' % profile)
gdaltest.tiff_drv.Delete('tmp/byte.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_72.tif')
- return 'success'
-
###############################################################################
# With Create(), check that TIFF directory is in the first bytes of the file
# and has not been rewritten later (#3021)
-def tiff_write_73():
+def test_tiff_write_73():
out_ds = gdaltest.tiff_drv.Create('tmp/tiff_write_73.tif', 10, 10, options=['ENDIANNESS=LITTLE'])
out_ds.SetGeoTransform([1, 0.01, 0, 1, 0, -0.01])
@@ -2754,8 +2331,7 @@ def tiff_write_73():
fileobj.close()
# Directory should be at offset 8 of the file
- if not (binvalues[0] == 0x08 and binvalues[1] == 0x00 and binvalues[2] == 0x00 and binvalues[3] == 0x00):
- return 'fail'
+ assert (binvalues[0] == 0x08 and binvalues[1] == 0x00 and binvalues[2] == 0x00 and binvalues[3] == 0x00)
# Re-open the file and modify the pixel content
out_ds = gdal.Open('tmp/tiff_write_73.tif', gdal.GA_Update)
@@ -2772,22 +2348,19 @@ def tiff_write_73():
fileobj.close()
# Directory should be at offset 8 of the file
- if not (binvalues[0] == 0x08 and binvalues[1] == 0x00 and binvalues[2] == 0x00 and binvalues[3] == 0x00):
- return 'fail'
+ assert (binvalues[0] == 0x08 and binvalues[1] == 0x00 and binvalues[2] == 0x00 and binvalues[3] == 0x00)
gdaltest.tiff_drv.Delete('tmp/tiff_write_73.tif')
- return 'success'
-
###############################################################################
# Verify we can write 12bit jpeg encoded tiff.
-def tiff_write_74():
+def test_tiff_write_74():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
old_accum = gdal.GetConfigOption('CPL_ACCUM_ERROR_MSG', 'OFF')
gdal.SetConfigOption('CPL_ACCUM_ERROR_MSG', 'ON')
@@ -2806,7 +2379,7 @@ def tiff_write_74():
if gdal.GetLastErrorMsg().find(
'Unsupported JPEG data precision 12') != -1:
sys.stdout.write('(12bit jpeg not available) ... ')
- return 'skip'
+ pytest.skip()
for photometric in ('YCBCR', 'RGB'):
@@ -2821,10 +2394,8 @@ def tiff_write_74():
stats = dst_ds.GetRasterBand(1).GetStatistics(0, 1)
if stats[2] < 2150 or stats[2] > 2180:
- gdaltest.post_reason('did not get expected mean for band1.')
- print(stats)
print(photometric)
- return 'fail'
+ pytest.fail('did not get expected mean for band1.')
try:
compression = dst_ds.GetMetadataItem('COMPRESSION', 'IMAGE_STRUCTURE')
@@ -2834,10 +2405,8 @@ def tiff_write_74():
if (photometric == 'YCBCR' and compression != 'YCbCr JPEG') or \
(photometric == 'RGB' and compression != 'JPEG'):
- gdaltest.post_reason('did not get expected COMPRESSION value')
print(('COMPRESSION="%s"' % compression))
- print(photometric)
- return 'fail'
+ pytest.fail('did not get expected COMPRESSION value')
try:
nbits = dst_ds.GetRasterBand(3).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE')
@@ -2846,21 +2415,19 @@ def tiff_write_74():
nbits = md['NBITS']
if nbits != '12':
- gdaltest.post_reason('did not get expected NBITS value')
print(photometric)
- return 'fail'
+ pytest.fail('did not get expected NBITS value')
dst_ds = None
gdaltest.tiff_drv.Delete('tmp/test_74.tif')
- return 'success'
-
+
###############################################################################
# Verify that FlushCache() alone doesn't cause crash (#3067 )
-def tiff_write_75():
+def test_tiff_write_75():
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_75.tif', 1, 1, 1)
ds.FlushCache()
@@ -2868,13 +2435,11 @@ def tiff_write_75():
gdaltest.tiff_drv.Delete('tmp/tiff_write_75.tif')
- return 'success'
-
###############################################################################
# Test generating a G4 band to use the TIFFWriteScanline()
-def tiff_write_76():
+def test_tiff_write_76():
src_ds = gdal.Open('data/slim_g4.tif')
compression = src_ds.GetMetadata('IMAGE_STRUCTURE')['COMPRESSION']
@@ -2883,23 +2448,18 @@ def tiff_write_76():
new_ds = gdal.Open('tmp/tiff_write_76.tif')
cs = new_ds.GetRasterBand(1).Checksum()
- if cs != 3322:
- print(cs)
- gdaltest.post_reason('Got wrong checksum')
- return 'fail'
+ assert cs == 3322, 'Got wrong checksum'
src_ds = None
new_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_76.tif')
- return 'success'
-
###############################################################################
# Test generating & reading a 8bit all-in-one-strip multiband TIFF (#3904)
-def tiff_write_77():
+def test_tiff_write_77():
src_ds = gdaltest.tiff_drv.Create('tmp/tiff_write_77_src.tif', 1, 5000, 3)
src_ds.GetRasterBand(2).Fill(255)
@@ -2921,19 +2481,13 @@ def tiff_write_77():
expected_cs = 255 % 7
else:
expected_cs = 0 % 7
- if cs != expected_cs:
- print(cs)
- gdaltest.post_reason('Got wrong checksum')
- return 'fail'
+ assert cs == expected_cs, 'Got wrong checksum'
# Test whole bands
for i in range(3):
cs = new_ds.GetRasterBand(i + 1).Checksum()
expected_cs = src_ds.GetRasterBand(i + 1).Checksum()
- if cs != expected_cs:
- print(cs)
- gdaltest.post_reason('Got wrong checksum')
- return 'fail'
+ assert cs == expected_cs, 'Got wrong checksum'
if attempt == 0:
new_ds = None
@@ -2946,17 +2500,15 @@ def tiff_write_77():
src_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_77_src.tif')
- return 'success'
-
###############################################################################
# Test generating & reading a YCbCr JPEG all-in-one-strip multiband TIFF (#3259)
-def tiff_write_78():
+def test_tiff_write_78():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
src_ds = gdaltest.tiff_drv.Create('tmp/tiff_write_78_src.tif', 16, 2048, 3)
src_ds.GetRasterBand(2).Fill(255)
@@ -2991,11 +2543,8 @@ def tiff_write_78():
# this ends up being 1
expected_cs = 1 % 7
if cs != expected_cs:
- print(cs)
- print(expected_cs)
print(band_line)
- gdaltest.post_reason('Got wrong checksum')
- return 'fail'
+ pytest.fail('Got wrong checksum')
# Test whole bands
for i in range(3):
@@ -3005,10 +2554,7 @@ def tiff_write_78():
# We should expect 0, but due to JPEG YCbCr compression & decompression,
# this ends up being 32768
expected_cs = 32768
- if cs != expected_cs:
- print(cs)
- gdaltest.post_reason('Got wrong checksum')
- return 'fail'
+ assert cs == expected_cs, 'Got wrong checksum'
new_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_78.tif')
@@ -3016,13 +2562,11 @@ def tiff_write_78():
src_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_78_src.tif')
- return 'success'
-
###############################################################################
# Test reading & updating GDALMD_AREA_OR_POINT (#3522)
-def tiff_write_79():
+def test_tiff_write_79():
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_79.tif', 1, 1)
srs = osr.SpatialReference()
@@ -3037,10 +2581,8 @@ def tiff_write_79():
if do_projection_ref:
ds.GetProjectionRef()
mdi = ds.GetMetadataItem('AREA_OR_POINT')
- if mdi != 'Area':
- gdaltest.post_reason('(1) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
- print(mdi)
- return 'fail'
+ assert mdi == 'Area', \
+ ('(1) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
ds = None
# Still read-only.
@@ -3049,23 +2591,18 @@ def tiff_write_79():
ds.GetProjectionRef()
ds.SetMetadataItem('AREA_OR_POINT', 'Point')
ds = None
- try:
+ with pytest.raises(OSError, message='got to PAM'):
# check that it doesn't go to PAM
os.stat('tmp/tiff_write_79.tif.aux.xml')
- gdaltest.post_reason('got to PAM')
- return 'fail'
- except OSError:
- pass
+
# So should get 'Area'
ds = gdal.Open('tmp/tiff_write_79.tif')
if do_projection_ref:
ds.GetProjectionRef()
mdi = ds.GetMetadataItem('AREA_OR_POINT')
- if mdi != 'Area':
- gdaltest.post_reason('(2) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
- print(mdi)
- return 'fail'
+ assert mdi == 'Area', \
+ ('(2) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
ds = None
# Now update to 'Point'
@@ -3075,28 +2612,21 @@ def tiff_write_79():
ds.SetMetadataItem('AREA_OR_POINT', 'Point')
if check_just_after:
mdi = ds.GetMetadataItem('AREA_OR_POINT')
- if mdi != 'Point':
- gdaltest.post_reason('(3) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
- print(mdi)
- return 'fail'
+ assert mdi == 'Point', \
+ ('(3) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
ds = None
- try:
+ with pytest.raises(OSError, message='got to PAM'):
# check that it doesn't go to PAM
os.stat('tmp/tiff_write_79.tif.aux.xml')
- gdaltest.post_reason('got to PAM')
- return 'fail'
- except OSError:
- pass
+
# Now should get 'Point'
ds = gdal.Open('tmp/tiff_write_79.tif')
if do_projection_ref:
ds.GetProjectionRef()
mdi = ds.GetMetadataItem('AREA_OR_POINT')
- if mdi != 'Point':
- gdaltest.post_reason('(4) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
- print(mdi)
- return 'fail'
+ assert mdi == 'Point', \
+ ('(4) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
ds = None
# Now update back to 'Area' through SetMetadata()
@@ -3108,10 +2638,8 @@ def tiff_write_79():
ds.SetMetadata(md)
if check_just_after:
mdi = ds.GetMetadataItem('AREA_OR_POINT')
- if mdi != 'Area':
- gdaltest.post_reason('(5) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
- print(mdi)
- return 'fail'
+ assert mdi == 'Area', \
+ ('(5) did not get expected value. do_projection_ref = %d, check_just_after = %d' % (do_projection_ref, check_just_after))
ds = None
# Now should get 'Area'
@@ -3119,21 +2647,16 @@ def tiff_write_79():
if do_projection_ref:
ds.GetProjectionRef()
mdi = ds.GetMetadataItem('AREA_OR_POINT')
- if mdi != 'Area':
- gdaltest.post_reason('(6) did not get expected value')
- print(mdi)
- return 'fail'
+ assert mdi == 'Area', '(6) did not get expected value'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_79.tif')
- return 'success'
-
###############################################################################
# Test SetOffset() & SetScale()
-def tiff_write_80():
+def test_tiff_write_80():
# First part : test storing and retrieving scale & offsets from internal metadata
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_80.tif', 1, 1)
@@ -3141,22 +2664,16 @@ def tiff_write_80():
ds.GetRasterBand(1).SetOffset(1000)
ds = None
- try:
+ with pytest.raises(OSError, message='got to PAM, but not expected...'):
# check that it doesn't go to PAM
os.stat('tmp/tiff_write_80.tif.aux.xml')
- gdaltest.post_reason('got to PAM, but not expected...')
- return 'fail'
- except OSError:
- pass
+
ds = gdal.Open('tmp/tiff_write_80.tif')
scale = ds.GetRasterBand(1).GetScale()
offset = ds.GetRasterBand(1).GetOffset()
- if scale != 100 or offset != 1000:
- gdaltest.post_reason('did not get expected values in internal case (1)')
- print(scale)
- print(offset)
- return 'fail'
+ assert scale == 100 and offset == 1000, \
+ 'did not get expected values in internal case (1)'
ds = None
# Test CreateCopy()
@@ -3167,11 +2684,7 @@ def tiff_write_80():
ds = gdal.Open('tmp/tiff_write_80_copy.tif')
scale = ds.GetRasterBand(1).GetScale()
offset = ds.GetRasterBand(1).GetOffset()
- if scale != 100 or offset != 1000:
- gdaltest.post_reason('did not get expected values in copy')
- print(scale)
- print(offset)
- return 'fail'
+ assert scale == 100 and offset == 1000, 'did not get expected values in copy'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_80_copy.tif')
@@ -3184,20 +2697,16 @@ def tiff_write_80():
ds = gdal.Open('tmp/tiff_write_80.tif')
scale = ds.GetRasterBand(1).GetScale()
offset = ds.GetRasterBand(1).GetOffset()
- if scale != 1 or offset != 0:
- gdaltest.post_reason('did not get expected values in internal case (2)')
- print(scale)
- print(offset)
- return 'fail'
+ assert scale == 1 and offset == 0, \
+ 'did not get expected values in internal case (2)'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_80.tif')
# Third part : test storing and retrieving scale & offsets from PAM metadata
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_80_bis.tif', 1, 1)
- if ds.GetRasterBand(1).GetScale() is not None or ds.GetRasterBand(1).GetOffset() is not None:
- gdaltest.post_reason('expected None values')
- return 'fail'
+ assert ds.GetRasterBand(1).GetScale() is None and ds.GetRasterBand(1).GetOffset() is None, \
+ 'expected None values'
ds = None
ds = gdal.Open('tmp/tiff_write_80_bis.tif')
@@ -3209,17 +2718,13 @@ def tiff_write_80():
# check that it *goes* to PAM
os.stat('tmp/tiff_write_80_bis.tif.aux.xml')
except OSError:
- gdaltest.post_reason('did not go to PAM as expected')
- return 'fail'
+ pytest.fail('did not go to PAM as expected')
ds = gdal.Open('tmp/tiff_write_80_bis.tif')
scale = ds.GetRasterBand(1).GetScale()
offset = ds.GetRasterBand(1).GetOffset()
- if scale != -100 or offset != -1000:
- gdaltest.post_reason('did not get expected values in PAM case (1)')
- print(scale)
- print(offset)
- return 'fail'
+ assert scale == -100 and offset == -1000, \
+ 'did not get expected values in PAM case (1)'
ds = None
# Fourth part : test unsetting scale & offsets from PAM metadata
@@ -3228,33 +2733,24 @@ def tiff_write_80():
ds.GetRasterBand(1).SetOffset(0)
ds = None
- try:
+ with pytest.raises(OSError, message='PAM file should be deleted'):
# check that there is no more any PAM file
os.stat('tmp/tiff_write_80_bis.tif.aux.xml')
- gdaltest.post_reason('PAM file should be deleted')
- return 'fail'
- except OSError:
- pass
+
ds = gdal.Open('tmp/tiff_write_80_bis.tif')
scale = ds.GetRasterBand(1).GetScale()
offset = ds.GetRasterBand(1).GetOffset()
- if scale != 1 or offset != 0:
- gdaltest.post_reason('did not get expected values in PAM case (2)')
- print(scale)
- print(offset)
- return 'fail'
+ assert scale == 1 and offset == 0, 'did not get expected values in PAM case (2)'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_80_bis.tif')
- return 'success'
-
###############################################################################
# Test retrieving GCP from PAM
-def tiff_write_81():
+def test_tiff_write_81():
shutil.copyfile('data/byte.tif', 'tmp/tiff_write_81.tif')
f = open('tmp/tiff_write_81.tif.aux.xml', 'wt')
@@ -3271,27 +2767,21 @@ def tiff_write_81():
ds = gdal.Open('tmp/tiff_write_81.tif')
- if ds.GetGCPProjection().find(
- 'AUTHORITY["EPSG","26711"]') == -1:
- gdaltest.post_reason('GCP Projection not set properly.')
- return 'fail'
+ assert (ds.GetGCPProjection().find(
+ 'AUTHORITY["EPSG","26711"]') != -1), 'GCP Projection not set properly.'
gcps = ds.GetGCPs()
- if len(gcps) != 4:
- gdaltest.post_reason('GCP count wrong.')
- return 'fail'
+ assert len(gcps) == 4, 'GCP count wrong.'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_81.tif')
- return 'success'
-
###############################################################################
# Test writing & reading a signedbyte 8 bit geotiff
-def tiff_write_82():
+def test_tiff_write_82():
src_ds = gdal.Open('data/byte.tif')
ds = gdaltest.tiff_drv.CreateCopy('tmp/tiff_write_82.tif', src_ds, options=['PIXELTYPE=SIGNEDBYTE'])
@@ -3300,20 +2790,16 @@ def tiff_write_82():
ds = gdal.Open('tmp/tiff_write_82.tif')
md = ds.GetRasterBand(1).GetMetadata('IMAGE_STRUCTURE')
- if md['PIXELTYPE'] != 'SIGNEDBYTE':
- gdaltest.post_reason('did not get SIGNEDBYTE')
- return 'fail'
+ assert md['PIXELTYPE'] == 'SIGNEDBYTE', 'did not get SIGNEDBYTE'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_82.tif')
- return 'success'
-
###############################################################################
# Test writing & reading an indexed GeoTIFF with an extra transparency band (#3547)
-def tiff_write_83():
+def test_tiff_write_83():
# Test Create() method
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_83.tif', 1, 1, 2)
@@ -3332,40 +2818,33 @@ def tiff_write_83():
ds = gdal.Open('tmp/tiff_write_83_2.tif')
ct2 = ds.GetRasterBand(1).GetRasterColorTable()
- if ct2.GetColorEntry(127) != (255, 255, 255, 255):
- gdaltest.post_reason('did not get expected color table')
- return 'fail'
+ assert ct2.GetColorEntry(127) == (255, 255, 255, 255), \
+ 'did not get expected color table'
ct2 = None
cs1 = ds.GetRasterBand(1).Checksum()
- if cs1 != 127 % 7:
- gdaltest.post_reason('did not get expected checksum for band 1')
- return 'fail'
+ assert cs1 == 127 % 7, 'did not get expected checksum for band 1'
cs2 = ds.GetRasterBand(2).Checksum()
- if cs2 != 255 % 7:
- gdaltest.post_reason('did not get expected checksum for band 2')
- return 'fail'
+ assert cs2 == 255 % 7, 'did not get expected checksum for band 2'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_83.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_83_2.tif')
- return 'success'
-
###############################################################################
# Test propagation of non-standard JPEG quality when the current directory
# changes in the midst of encoding of tiles (#3539)
-def tiff_write_84():
+def test_tiff_write_84():
md = gdaltest.tiff_drv.GetMetadata()
# Crashes with libtiff < 4.0
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
with gdaltest.SetCacheMax(0):
ds = gdal.GetDriverByName('GTiff').Create('tmp/tiff_write_84.tif', 128, 128, 3)
@@ -3387,38 +2866,27 @@ def tiff_write_84():
gdaltest.tiff_drv.Delete('tmp/tiff_write_84.tif')
- if cs != 0:
- print(cs)
- gdaltest.post_reason('did not get expected checksum')
- return 'fail'
-
- return 'success'
+ assert cs == 0, 'did not get expected checksum'
###############################################################################
# Test SetUnitType()
-def tiff_write_85():
+def test_tiff_write_85():
# First part : test storing and retrieving unittype from internal metadata
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_85.tif', 1, 1)
ds.GetRasterBand(1).SetUnitType('ft')
ds = None
- try:
+ with pytest.raises(OSError, message='got to PAM, but not expected...'):
# check that it doesn't go to PAM
os.stat('tmp/tiff_write_85.tif.aux.xml')
- gdaltest.post_reason('got to PAM, but not expected...')
- return 'fail'
- except OSError:
- pass
+
ds = gdal.Open('tmp/tiff_write_85.tif')
unittype = ds.GetRasterBand(1).GetUnitType()
- if unittype != 'ft':
- gdaltest.post_reason('did not get expected values in internal case (1)')
- print(unittype)
- return 'fail'
+ assert unittype == 'ft', 'did not get expected values in internal case (1)'
ds = None
# Test CreateCopy()
@@ -3428,10 +2896,7 @@ def tiff_write_85():
ds = None
ds = gdal.Open('tmp/tiff_write_85_copy.tif')
unittype = ds.GetRasterBand(1).GetUnitType()
- if unittype != 'ft':
- gdaltest.post_reason('did not get expected values in copy')
- print(unittype)
- return 'fail'
+ assert unittype == 'ft', 'did not get expected values in copy'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_85_copy.tif')
@@ -3442,19 +2907,14 @@ def tiff_write_85():
ds = gdal.Open('tmp/tiff_write_85.tif')
unittype = ds.GetRasterBand(1).GetUnitType()
- if unittype != '':
- gdaltest.post_reason('did not get expected values in internal case (2)')
- print(unittype)
- return 'fail'
+ assert unittype == '', 'did not get expected values in internal case (2)'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_85.tif')
# Third part : test storing and retrieving unittype from PAM metadata
ds = gdaltest.tiff_drv.Create('tmp/tiff_write_85_bis.tif', 1, 1)
- if ds.GetRasterBand(1).GetUnitType():
- gdaltest.post_reason('expected None values')
- return 'fail'
+ assert not ds.GetRasterBand(1).GetUnitType(), 'expected None values'
ds = None
ds = gdal.Open('tmp/tiff_write_85_bis.tif')
@@ -3465,15 +2925,11 @@ def tiff_write_85():
# check that it *goes* to PAM
os.stat('tmp/tiff_write_85_bis.tif.aux.xml')
except OSError:
- gdaltest.post_reason('did not go to PAM as expected')
- return 'fail'
+ pytest.fail('did not go to PAM as expected')
ds = gdal.Open('tmp/tiff_write_85_bis.tif')
unittype = ds.GetRasterBand(1).GetUnitType()
- if unittype != 'ft':
- gdaltest.post_reason('did not get expected values in PAM case (1)')
- print(unittype)
- return 'fail'
+ assert unittype == 'ft', 'did not get expected values in PAM case (1)'
ds = None
# Fourth part : test unsetting unittype from PAM metadata
@@ -3481,26 +2937,18 @@ def tiff_write_85():
ds.GetRasterBand(1).SetUnitType(None)
ds = None
- try:
+ with pytest.raises(OSError, message='PAM file should be deleted'):
# check that there is no more any PAM file
os.stat('tmp/tiff_write_85_bis.tif.aux.xml')
- gdaltest.post_reason('PAM file should be deleted')
- return 'fail'
- except OSError:
- pass
+
ds = gdal.Open('tmp/tiff_write_85_bis.tif')
unittype = ds.GetRasterBand(1).GetUnitType()
- if unittype != '':
- gdaltest.post_reason('did not get expected values in PAM case (2)')
- print(unittype)
- return 'fail'
+ assert unittype == '', 'did not get expected values in PAM case (2)'
ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_85_bis.tif')
- return 'success'
-
###############################################################################
# Test special handling of xml:ESRI domain. When the ESRI_XML_PAM config
# option is set we want to write this to PAM, not into the geotiff itself.
@@ -3508,7 +2956,7 @@ def tiff_write_85():
# properly with earlier versions of ArcGIS, requested by ESRI.
-def tiff_write_86():
+def test_tiff_write_86():
gdal.SetConfigOption('ESRI_XML_PAM', 'YES')
@@ -3520,14 +2968,12 @@ def tiff_write_86():
# Is the xml:ESRI data available?
ds = gdal.Open('tmp/tiff_write_86.tif')
- if ds.GetMetadata('xml:ESRI') != ['\n']:
- print(ds.GetMetadata('xml:ESRI'))
- gdaltest.post_reason('did not get expected xml:ESRI metadata.')
- return 'fail'
+ assert ds.GetMetadata('xml:ESRI') == ['\n'], \
+ 'did not get expected xml:ESRI metadata.'
if ds.GetMetadataItem('BaseTest') != 'Value':
gdaltest.post_value('missing metadata(1)')
- return 'fail'
+ pytest.fail()
ds = None
# After removing the pam file is it gone, but the conventional
@@ -3537,14 +2983,11 @@ def tiff_write_86():
'tmp/tiff_write_86.tif.aux.xml.hidden')
ds = gdal.Open('tmp/tiff_write_86.tif')
- if ds.GetMetadata('xml:ESRI') is not None:
- print(ds.GetMetadata('xml:ESRI'))
- gdaltest.post_reason('unexpectedly got xml:ESRI metadata')
- return 'fail'
+ assert ds.GetMetadata('xml:ESRI') is None, 'unexpectedly got xml:ESRI metadata'
if ds.GetMetadataItem('BaseTest') != 'Value':
gdaltest.post_value('missing metadata(2)')
- return 'fail'
+ pytest.fail()
ds = None
@@ -3560,14 +3003,12 @@ def tiff_write_86():
# Is the xml:ESRI data available?
ds = gdal.Open('tmp/tiff_write_86_cc.tif')
- if ds.GetMetadata('xml:ESRI') != ['\n']:
- print(ds.GetMetadata('xml:ESRI'))
- gdaltest.post_reason('did not get expected xml:ESRI metadata (cc).')
- return 'fail'
+ assert ds.GetMetadata('xml:ESRI') == ['\n'], \
+ 'did not get expected xml:ESRI metadata (cc).'
if ds.GetMetadataItem('BaseTest') != 'Value':
gdaltest.post_value('missing metadata(1cc)')
- return 'fail'
+ pytest.fail()
ds = None
# After removing the pam file is it gone, but the conventional
@@ -3576,14 +3017,11 @@ def tiff_write_86():
os.remove('tmp/tiff_write_86_cc.tif.aux.xml')
ds = gdal.Open('tmp/tiff_write_86_cc.tif')
- if ds.GetMetadata('xml:ESRI') is not None:
- print(ds.GetMetadata('xml:ESRI'))
- gdaltest.post_reason('unexpectedly got xml:ESRI metadata(2)')
- return 'fail'
+ assert ds.GetMetadata('xml:ESRI') is None, 'unexpectedly got xml:ESRI metadata(2)'
if ds.GetMetadataItem('BaseTest') != 'Value':
gdaltest.post_value('missing metadata(2cc)')
- return 'fail'
+ pytest.fail()
ds = None
@@ -3594,13 +3032,11 @@ def tiff_write_86():
gdaltest.tiff_drv.Delete('tmp/tiff_write_86.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_86_cc.tif')
- return 'success'
-
###############################################################################
# Test COPY_SRC_OVERVIEWS creation option
-def tiff_write_87():
+def test_tiff_write_87():
gdal.Translate('tmp/tiff_write_87_src.tif', 'data/utmsmall.tif', options='-a_nodata 0')
@@ -3629,48 +3065,29 @@ def tiff_write_87():
import validate_cloud_optimized_geotiff
try:
_, errors, _ = validate_cloud_optimized_geotiff.validate('tmp/tiff_write_87_dst.tif', check_tiled=False)
- if errors:
- gdaltest.post_reason('validate_cloud_optimized_geotiff failed')
- print(errors)
- return 'fail'
+ assert not errors, 'validate_cloud_optimized_geotiff failed'
except OSError:
- gdaltest.post_reason('validate_cloud_optimized_geotiff failed')
- return 'fail'
+ pytest.fail('validate_cloud_optimized_geotiff failed')
gdaltest.tiff_drv.Delete('tmp/tiff_write_87_src.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_87_dst.tif')
# Check checksums
- if cs1 != expected_cs1 or cs2 != expected_cs2:
- gdaltest.post_reason('did not get expected checksums')
- print(cs1)
- print(cs2)
- print(expected_cs1)
- print(expected_cs2)
- return 'fail'
-
- if nodata_ovr_0 != 0 or nodata_ovr_1 != 0:
- gdaltest.post_reason('did not get expected nodata values')
- print(nodata_ovr_0)
- print(nodata_ovr_1)
- return 'fail'
+ assert cs1 == expected_cs1 and cs2 == expected_cs2, 'did not get expected checksums'
- if ifd_main != 8 and not(ifd_main < ifd_ovr_0 and ifd_ovr_0 < ifd_ovr_1 and ifd_ovr_1 < data_ovr_1 and data_ovr_1 < data_ovr_0 and data_ovr_0 < data_main):
- gdaltest.post_reason('failure')
- print(ifd_main, ifd_ovr_0, ifd_ovr_1, data_ovr_1, data_ovr_0, data_main)
- return 'fail'
+ assert nodata_ovr_0 == 0 and nodata_ovr_1 == 0, 'did not get expected nodata values'
- return 'success'
+ assert ifd_main == 8 or(ifd_main < ifd_ovr_0 and ifd_ovr_0 < ifd_ovr_1 and ifd_ovr_1 < data_ovr_1 and data_ovr_1 < data_ovr_0 and data_ovr_0 < data_main)
###############################################################################
# Test that COPY_SRC_OVERVIEWS creation option has an influence
# on BIGTIFF creation
-def tiff_write_88():
+def test_tiff_write_88():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
# The file would be > 4.2 GB without SPARSE_OK
src_ds = gdaltest.tiff_drv.Create('tmp/tiff_write_88_src.tif', 60000, 60000, 1,
@@ -3715,28 +3132,21 @@ def tiff_write_88():
import struct
ar = struct.unpack('B' * 8, data)
- if ar[2] != 43:
- gdaltest.post_reason('not a BIGTIFF file')
- print(ar)
- return 'fail'
- if ar[4] != 8 or ar[5] != 0 or ar[6] != 0 or ar[7] != 0:
- gdaltest.post_reason('first IFD is not at offset 8')
- print(ar)
- return 'fail'
-
- return 'success'
+ assert ar[2] == 43, 'not a BIGTIFF file'
+ assert ar[4] == 8 and ar[5] == 0 and ar[6] == 0 and ar[7] == 0, \
+ 'first IFD is not at offset 8'
###############################################################################
# Test JPEG_QUALITY propagation while creating a (default compressed) mask band
-def tiff_write_89():
+def test_tiff_write_89():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
last_size = 0
for quality in [90, 75, 30]:
@@ -3772,29 +3182,23 @@ def tiff_write_89():
# print('quality = %d, size = %d' % (quality, size))
if quality != 90:
- if size >= last_size:
- gdaltest.post_reason('did not get decreasing file sizes')
- print(size)
- print(last_size)
- return 'fail'
+ assert size < last_size, 'did not get decreasing file sizes'
last_size = size
gdaltest.tiff_drv.Delete('tmp/tiff_write_89.tif')
- return 'success'
-
###############################################################################
# Test JPEG_QUALITY propagation while creating (internal) overviews
-def tiff_write_90():
+def test_tiff_write_90():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
last_size = 0
for quality in [90, 75, 30]:
@@ -3820,29 +3224,23 @@ def tiff_write_90():
# print('quality = %d, size = %d' % (quality, size))
if quality != 90:
- if size >= last_size:
- gdaltest.post_reason('did not get decreasing file sizes')
- print(size)
- print(last_size)
- return 'fail'
+ assert size < last_size, 'did not get decreasing file sizes'
last_size = size
gdaltest.tiff_drv.Delete('tmp/tiff_write_90.tif')
- return 'success'
-
###############################################################################
# Test JPEG_QUALITY propagation while creating (internal) overviews after re-opening
-def tiff_write_91():
+def test_tiff_write_91():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
last_size = 0
for quality in [90, 75, 30]:
@@ -3873,30 +3271,24 @@ def tiff_write_91():
# print('quality = %d, size = %d' % (quality, size))
if quality != 90:
- if size >= last_size:
- gdaltest.post_reason('did not get decreasing file sizes')
- print(size)
- print(last_size)
- return 'fail'
+ assert size < last_size, 'did not get decreasing file sizes'
last_size = size
gdaltest.tiff_drv.Delete('tmp/tiff_write_91.tif')
- return 'success'
-
###############################################################################
# Test the effect of JPEG_QUALITY_OVERVIEW while creating (internal) overviews after re-opening
# This will test that we correctly guess the quality of the main dataset
-def tiff_write_92():
+def test_tiff_write_92():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
last_size = 0
quality = 30
@@ -3929,35 +3321,25 @@ def tiff_write_92():
# print('quality = %d, size = %d' % (quality, size))
if jpeg_quality_overview == 30:
- if size != last_size:
- gdaltest.post_reason('did not get equal file sizes')
- print(size)
- print(last_size)
- return 'fail'
+ assert size == last_size, 'did not get equal file sizes'
elif jpeg_quality_overview == 40:
- if size <= last_size:
- gdaltest.post_reason('did not get growing file sizes')
- print(size)
- print(last_size)
- return 'fail'
+ assert size > last_size, 'did not get growing file sizes'
last_size = size
gdaltest.tiff_drv.Delete('tmp/tiff_write_92.tif')
- return 'success'
-
###############################################################################
# Test JPEG_QUALITY_OVERVIEW propagation while creating external overviews
-def tiff_write_93():
+def test_tiff_write_93():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
src_ds = gdal.Open('../gdrivers/data/utm.tif')
ds = gdal.GetDriverByName('GTiff').Create('tmp/tiff_write_93.tif', 1024, 1024, 3,
@@ -3997,35 +3379,27 @@ def tiff_write_93():
# print('quality = %d, size = %d' % (quality, size))
if quality != 90:
- if size >= last_size:
- gdaltest.post_reason('did not get decreasing file sizes')
- print(size)
- print(last_size)
- return 'fail'
+ assert size < last_size, 'did not get decreasing file sizes'
- if quality == 30 and size >= 83000:
- gdaltest.post_reason('file larger than expected. should be about 69100. perhaps jpeg quality is not well propagated')
- print(size)
- return 'fail'
+ assert not (quality == 30 and size >= 83000), \
+ 'file larger than expected. should be about 69100. perhaps jpeg quality is not well propagated'
last_size = size
gdaltest.tiff_drv.Delete('tmp/tiff_write_93.tif')
- return 'success'
-
###############################################################################
# Test CreateCopy() of a dataset with a mask into a JPEG compressed dataset
# and check JPEG_QUALITY propagation without warning
-def tiff_write_94():
+def test_tiff_write_94():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
src_ds = gdal.GetDriverByName('GTiff').Create('tmp/tiff_write_94_src.tif', 1024, 1024, 3)
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK', 'YES')
@@ -4048,19 +3422,14 @@ def tiff_write_94():
gdaltest.tiff_drv.Delete('tmp/tiff_write_94_src.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_94_dst.tif')
- if cs != 3:
- print(cs)
- gdaltest.post_reason('wrong checksum')
- return 'fail'
-
- return 'success'
+ assert cs == 3, 'wrong checksum'
###############################################################################
# Test that COPY_SRC_OVERVIEWS deal well with rounding issues when computing
# overview levels from the overview size
-def tiff_write_95():
+def test_tiff_write_95():
src_ds = gdaltest.tiff_drv.Create('tmp/tiff_write_95_src.tif', 7171, 6083, options=['SPARSE_OK=YES'])
src_ds.BuildOverviews('NONE', overviewlist=[2, 4, 8, 16, 32, 64])
@@ -4074,16 +3443,13 @@ def tiff_write_95():
gdaltest.tiff_drv.Delete('tmp/tiff_write_95_src.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_95_dst.tif')
- if not ok:
- return 'fail'
-
- return 'success'
+ assert ok
###############################################################################
# Test that COPY_SRC_OVERVIEWS combined with GDAL_TIFF_INTERNAL_MASK=YES work well
-def tiff_write_96():
+def test_tiff_write_96():
gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK', 'YES')
src_ds = gdaltest.tiff_drv.Create('tmp/tiff_write_96_src.tif', 100, 100)
@@ -4120,20 +3486,15 @@ def tiff_write_96():
gdaltest.tiff_drv.Delete('tmp/tiff_write_96_src.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_96_dst.tif')
- if [expected_cs, expected_cs_mask, expected_cs_ovr_1, expected_cs_ovr_mask_1, expected_cs_ovr_2, expected_cs_ovr_mask_2] != \
- [cs, cs_mask, cs_ovr_1, cs_ovr_mask_1, cs_ovr_2, cs_ovr_mask_2]:
- gdaltest.post_reason('did not get expected checksums')
- print(expected_cs, expected_cs_mask, expected_cs_ovr_1, expected_cs_ovr_mask_1, expected_cs_ovr_2, expected_cs_ovr_mask_2)
- print(cs, cs_mask, cs_ovr_1, cs_ovr_mask_1, cs_ovr_2, cs_ovr_mask_2)
- return 'fail'
-
- return 'success'
+ assert [expected_cs, expected_cs_mask, expected_cs_ovr_1, expected_cs_ovr_mask_1, expected_cs_ovr_2, expected_cs_ovr_mask_2] == \
+ [cs, cs_mask, cs_ovr_1, cs_ovr_mask_1, cs_ovr_2, cs_ovr_mask_2], \
+ 'did not get expected checksums'
###############################################################################
# Create a simple file by copying from an existing one - PixelIsPoint
-def tiff_write_97():
+def test_tiff_write_97():
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', 'FALSE')
@@ -4147,14 +3508,9 @@ def tiff_write_97():
gt_expected = (440690.0, 60.0, 0.0, 3751350.0, 0.0, -60.0)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform')
- return 'fail'
+ assert gt == gt_expected, 'did not get expected geotransform'
- if md != 'Point':
- gdaltest.post_reason('did not get expected AREA_OR_POINT value')
- return 'fail'
+ assert md == 'Point', 'did not get expected AREA_OR_POINT value'
gdaltest.tiff_drv.Delete('tmp/test_97.tif')
@@ -4171,14 +3527,10 @@ def tiff_write_97():
gt_expected = (440690.0, 60.0, 0.0, 3751350.0, 0.0, -60.0)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform when ignoring PixelIsPoint')
- return 'fail'
+ assert gt == gt_expected, \
+ 'did not get expected geotransform when ignoring PixelIsPoint'
- if md != 'Point':
- gdaltest.post_reason('did not get expected AREA_OR_POINT value')
- return 'fail'
+ assert md == 'Point', 'did not get expected AREA_OR_POINT value'
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', None)
@@ -4192,24 +3544,18 @@ def tiff_write_97():
gt_expected = (440660.0, 60.0, 0.0, 3751380.0, 0.0, -60.0)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform when ignoring PixelIsPoint (2)')
- return 'fail'
+ assert gt == gt_expected, \
+ 'did not get expected geotransform when ignoring PixelIsPoint (2)'
- if md != 'Point':
- gdaltest.post_reason('did not get expected AREA_OR_POINT value')
- return 'fail'
+ assert md == 'Point', 'did not get expected AREA_OR_POINT value'
gdaltest.tiff_drv.Delete('tmp/test_97_2.tif')
- return 'success'
-
###############################################################################
# Create a rotated geotiff file (uses a geomatrix) with - PixelIsPoint
-def tiff_write_98():
+def test_tiff_write_98():
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', 'FALSE')
@@ -4226,14 +3572,9 @@ def tiff_write_98():
gt_expected = (1841001.75, 1.5, -5.0, 1144003.25, -5.0, -1.5)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform')
- return 'fail'
+ assert gt == gt_expected, 'did not get expected geotransform'
- if md != 'Point':
- gdaltest.post_reason('did not get expected AREA_OR_POINT value')
- return 'fail'
+ assert md == 'Point', 'did not get expected AREA_OR_POINT value'
gdal.SetConfigOption('GTIFF_POINT_GEO_IGNORE', 'FALSE')
@@ -4246,24 +3587,17 @@ def tiff_write_98():
gt_expected = (1841003.5, 1.5, -5.0, 1144006.5, -5.0, -1.5)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform (2)')
- return 'fail'
+ assert gt == gt_expected, 'did not get expected geotransform (2)'
- if md != 'Point':
- gdaltest.post_reason('did not get expected AREA_OR_POINT value')
- return 'fail'
+ assert md == 'Point', 'did not get expected AREA_OR_POINT value'
gdaltest.tiff_drv.Delete('tmp/test_98.tif')
- return 'success'
-
###############################################################################
# Create copy into a RGB JPEG-IN-TIFF (#3887)
-def tiff_write_99():
+def test_tiff_write_99():
src_ds = gdal.Open('data/rgbsmall.tif')
new_ds = gdaltest.tiff_drv.CreateCopy('tmp/test_99.tif', src_ds, options=['COMPRESS=JPEG'])
@@ -4278,17 +3612,13 @@ def tiff_write_99():
gdaltest.tiff_drv.Delete('tmp/test_99.tif')
- if (cs1, cs2, cs3) != (21629, 21651, 21371):
- print('%d,%d,%d' % (cs1, cs2, cs3))
- return 'fail'
-
- return 'success'
+ assert (cs1, cs2, cs3) == (21629, 21651, 21371), ('%d,%d,%d' % (cs1, cs2, cs3))
###############################################################################
# Create copy into a 2 band JPEG-IN-TIFF (#3887)
-def tiff_write_100():
+def test_tiff_write_100():
src_ds = gdaltest.tiff_drv.Create('/vsimem/test_100_src.tif', 16, 16, 2)
src_ds.GetRasterBand(1).Fill(255)
@@ -4304,11 +3634,7 @@ def tiff_write_100():
gdaltest.tiff_drv.Delete('/vsimem/test_100_src.tif')
gdaltest.tiff_drv.Delete('/vsimem/test_100_dst.tif')
- if (cs1, cs2) != (3118, 0):
- print('%d,%d' % (cs1, cs2))
- return 'fail'
-
- return 'success'
+ assert (cs1, cs2) == (3118, 0), ('%d,%d' % (cs1, cs2))
###############################################################################
# Test CHUNKY_STRIP_READ_SUPPORT (#3894)
@@ -4316,14 +3642,14 @@ def tiff_write_100():
# reloading. tiff_write_78 doesn't produce enough big data to trigger this...
-def tiff_write_101():
+def test_tiff_write_101():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if sys.platform.startswith('linux'):
# Much faster to use /dev/urandom than python random generator !
@@ -4377,24 +3703,21 @@ def tiff_write_101():
if error_msg != '':
src_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_101.bin')
- return 'fail'
+ pytest.fail()
if compression_method != 'JPEG' and cs != expected_cs:
- gdaltest.post_reason('for compression method %s, got %d instead of %d' % (compression_method, cs, expected_cs))
src_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_101.bin')
- return 'fail'
+ pytest.fail('for compression method %s, got %d instead of %d' % (compression_method, cs, expected_cs))
src_ds = None
gdaltest.tiff_drv.Delete('tmp/tiff_write_101.bin')
- return 'success'
-
###############################################################################
# Test writing and reading back COMPD_CS
-def tiff_write_102():
+def test_tiff_write_102():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_102.tif', 1, 1)
sr = osr.SpatialReference()
@@ -4416,34 +3739,26 @@ def tiff_write_102():
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_102.tif')
- if wkt1.find('COMPD_CS') != 0:
- gdaltest.post_reason('expected COMPD_CS, but got something else')
- print(wkt1)
- return 'fail'
+ assert wkt1.find('COMPD_CS') == 0, 'expected COMPD_CS, but got something else'
- if wkt2.find('COMPD_CS') == 0:
- gdaltest.post_reason('got COMPD_CS, but did not expected it')
- print(wkt2)
- return 'fail'
+ assert wkt2.find('COMPD_CS') != 0, 'got COMPD_CS, but did not expected it'
sr2 = osr.SpatialReference()
sr2.SetFromUserInput(wkt1)
got_name = sr2.GetAttrValue('COMPD_CS')
if got_name != name:
- gdaltest.post_reason('dit not get expected COMPD_CS name')
print(wkt2)
- return 'fail'
-
- return 'success'
+ pytest.fail('dit not get expected COMPD_CS name')
+
###############################################################################
# Test -co COPY_SRC_OVERVIEWS=YES on a multiband source with external overviews (#3938)
-def tiff_write_103():
+def test_tiff_write_103():
import test_cli_utilities
if test_cli_utilities.get_gdaladdo_path() is None:
- return 'skip'
+ pytest.skip()
gdal.Translate('tmp/tiff_write_103_src.tif', 'data/rgbsmall.tif', options='-outsize 260 260')
gdaltest.runexternal(test_cli_utilities.get_gdaladdo_path() + ' -ro tmp/tiff_write_103_src.tif 2')
@@ -4459,20 +3774,14 @@ def tiff_write_103():
gdaltest.tiff_drv.Delete('tmp/tiff_write_103_src.tif')
gdaltest.tiff_drv.Delete('tmp/tiff_write_103_dst.tif')
- if src_cs != dst_cs:
- gdaltest.post_reason('did not get expected checksum')
- print(src_cs)
- print(dst_cs)
- return 'fail'
-
- return 'success'
+ assert src_cs == dst_cs, 'did not get expected checksum'
###############################################################################
# Confirm as best we can that we can write geotiff files with detailed
# projection parameters with the correct linear units set. (#3901)
-def tiff_write_104():
+def test_tiff_write_104():
src_ds = gdal.Open('data/spaf27_correct.tif')
dst_ds = gdaltest.tiff_drv.CreateCopy('tmp/test_104.tif', src_ds)
@@ -4486,25 +3795,21 @@ def tiff_write_104():
srs = osr.SpatialReference(wkt)
fe = srs.GetProjParm(osr.SRS_PP_FALSE_EASTING)
- if abs(fe - 2000000.0) > 0.001:
- gdaltest.post_reason('did not get expected false easting')
- return 'fail'
+ assert abs(fe - 2000000.0) <= 0.001, 'did not get expected false easting'
gdaltest.tiff_drv.Delete('tmp/test_104.tif')
- return 'success'
-
###############################################################################
# Confirm as best we can that we can write geotiff files with detailed
# projection parameters with the correct linear units set. (#3901)
-def tiff_write_105():
+def test_tiff_write_105():
# This hangs forever with libtiff 3.8.2, so skip it
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
shutil.copyfile('data/bug4468.tif', 'tmp/bug4468.tif')
@@ -4518,28 +3823,24 @@ def tiff_write_105():
ds = gdal.Open('tmp/bug4468.tif')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 2923:
- gdaltest.post_reason('Did not get expected checksum, got %d.' % cs)
- return 'fail'
+ assert cs == 2923, ('Did not get expected checksum, got %d.' % cs)
ds = None
gdaltest.tiff_drv.Delete('tmp/bug4468.tif')
- return 'success'
-
###############################################################################
# Test the direct copy mechanism of JPEG source
-def tiff_write_106(filename='../gdrivers/data/byte_with_xmp.jpg', options=None, check_cs=True):
+def test_tiff_write_106(filename='../gdrivers/data/byte_with_xmp.jpg', options=None, check_cs=True):
if options is None:
options = ['COMPRESS=JPEG']
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
src_ds = gdal.Open(filename)
nbands = src_ds.RasterCount
@@ -4560,68 +3861,61 @@ def tiff_write_106(filename='../gdrivers/data/byte_with_xmp.jpg', options=None,
if check_cs:
for i in range(nbands):
- if cs[i] != src_cs[i]:
- gdaltest.post_reason('did not get expected checksum')
- print(cs[i])
- print(src_cs[i])
- return 'fail'
+ assert cs[i] == src_cs[i], 'did not get expected checksum'
else:
for i in range(nbands):
- if cs[i] == 0:
- gdaltest.post_reason('did not get expected checksum')
- return 'fail'
+ assert cs[i] != 0, 'did not get expected checksum'
- return 'success'
+
+def test_tiff_write_107():
+ return test_tiff_write_106(options=['COMPRESS=JPEG', 'BLOCKYSIZE=8'])
-def tiff_write_107():
- return tiff_write_106(options=['COMPRESS=JPEG', 'BLOCKYSIZE=8'])
+def test_tiff_write_108():
+ return test_tiff_write_106(options=['COMPRESS=JPEG', 'BLOCKYSIZE=20'])
-def tiff_write_108():
- return tiff_write_106(options=['COMPRESS=JPEG', 'BLOCKYSIZE=20'])
-
-def tiff_write_109():
- return tiff_write_106(options=['COMPRESS=JPEG', 'TILED=YES', 'BLOCKYSIZE=16', 'BLOCKXSIZE=16'])
+def test_tiff_write_109():
+ return test_tiff_write_106(options=['COMPRESS=JPEG', 'TILED=YES', 'BLOCKYSIZE=16', 'BLOCKXSIZE=16'])
# Strip organization of YCbCr does *NOT* give exact pixels w.r.t. original image
-def tiff_write_110():
- return tiff_write_106(filename='../gdrivers/data/albania.jpg', check_cs=False)
+def test_tiff_write_110():
+ return test_tiff_write_106(filename='../gdrivers/data/albania.jpg', check_cs=False)
# Whole copy of YCbCr *DOES* give exact pixels w.r.t. original image
-def tiff_write_111():
- return tiff_write_106(filename='../gdrivers/data/albania.jpg', options=['COMPRESS=JPEG', 'BLOCKYSIZE=260'])
+def test_tiff_write_111():
+ return test_tiff_write_106(filename='../gdrivers/data/albania.jpg', options=['COMPRESS=JPEG', 'BLOCKYSIZE=260'])
-def tiff_write_111_bis():
- return tiff_write_106(filename='../gdrivers/data/albania.jpg', options=['COMPRESS=JPEG', 'BLOCKYSIZE=260', 'INTERLEAVE=PIXEL'])
+def test_tiff_write_111_bis():
+ return test_tiff_write_106(filename='../gdrivers/data/albania.jpg', options=['COMPRESS=JPEG', 'BLOCKYSIZE=260', 'INTERLEAVE=PIXEL'])
-def tiff_write_111_ter():
- return tiff_write_106(filename='../gdrivers/data/albania.jpg', options=['COMPRESS=JPEG', 'BLOCKYSIZE=260', 'INTERLEAVE=BAND'], check_cs=False)
+def test_tiff_write_111_ter():
+ return test_tiff_write_106(filename='../gdrivers/data/albania.jpg', options=['COMPRESS=JPEG', 'BLOCKYSIZE=260', 'INTERLEAVE=BAND'], check_cs=False)
# Tiled organization of YCbCr does *NOT* give exact pixels w.r.t. original image
-def tiff_write_112():
- return tiff_write_106(filename='../gdrivers/data/albania.jpg', options=['COMPRESS=JPEG', 'TILED=YES'], check_cs=False)
+def test_tiff_write_112():
+ return test_tiff_write_106(filename='../gdrivers/data/albania.jpg', options=['COMPRESS=JPEG', 'TILED=YES'], check_cs=False)
# The source is a JPEG in RGB colorspace (usually it is YCbCr).
-def tiff_write_113():
- return tiff_write_106(filename='../gdrivers/data/rgbsmall_rgb.jpg', options=['COMPRESS=JPEG', 'BLOCKYSIZE=8'])
+def test_tiff_write_113():
+ return test_tiff_write_106(filename='../gdrivers/data/rgbsmall_rgb.jpg', options=['COMPRESS=JPEG', 'BLOCKYSIZE=8'])
###############################################################################
# Test CreateCopy() interruption
-def tiff_write_114():
+def test_tiff_write_114():
tst = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672)
@@ -4631,17 +3925,16 @@ def tiff_write_114():
# Test writing a pixel interleaved RGBA JPEG-compressed TIFF
-def tiff_write_115():
+def test_tiff_write_115():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
tmpfilename = '/vsimem/tiff_write_115.tif'
src_ds = gdal.Open('data/stefan_full_rgba.tif')
ds = gdaltest.tiff_drv.CreateCopy(tmpfilename, src_ds, options=['COMPRESS=JPEG'])
- if ds is None:
- return 'fail'
+ assert ds is not None
ds = None
src_ds = None
@@ -4649,51 +3942,45 @@ def tiff_write_115():
if f is not None:
gdal.VSIFCloseL(f)
gdal.Unlink(tmpfilename)
- return 'fail'
+ pytest.fail()
ds = gdal.Open(tmpfilename)
md = ds.GetMetadata('IMAGE_STRUCTURE')
if md['INTERLEAVE'] != 'PIXEL':
- gdaltest.post_reason('failed')
ds = None
gdal.Unlink(tmpfilename)
- return 'fail'
+ pytest.fail()
expected_cs = [16404, 62700, 37913, 14174]
for i in range(4):
cs = ds.GetRasterBand(i + 1).Checksum()
if cs != expected_cs[i]:
- gdaltest.post_reason('failed')
ds = None
gdal.Unlink(tmpfilename)
- return 'fail'
+ pytest.fail()
if ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != gdal.GCI_RedBand + i:
- gdaltest.post_reason('failed')
ds = None
gdal.Unlink(tmpfilename)
- return 'fail'
+ pytest.fail()
ds = None
gdal.Unlink(tmpfilename)
- return 'success'
-
###############################################################################
# Test writing a band interleaved RGBA JPEG-compressed TIFF
-def tiff_write_116():
+def test_tiff_write_116():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
tmpfilename = '/vsimem/tiff_write_116.tif'
src_ds = gdal.Open('data/stefan_full_rgba.tif')
ds = gdaltest.tiff_drv.CreateCopy(tmpfilename, src_ds, options=['COMPRESS=JPEG', 'INTERLEAVE=BAND'])
- if ds is None:
- return 'fail'
+ assert ds is not None
ds = None
src_ds = None
@@ -4701,46 +3988,41 @@ def tiff_write_116():
if f is not None:
gdal.VSIFCloseL(f)
gdal.Unlink(tmpfilename)
- return 'fail'
+ pytest.fail()
ds = gdal.Open(tmpfilename)
md = ds.GetMetadata('IMAGE_STRUCTURE')
if md['INTERLEAVE'] != 'BAND':
- gdaltest.post_reason('failed')
ds = None
gdal.Unlink(tmpfilename)
- return 'fail'
+ pytest.fail()
expected_cs = [16404, 62700, 37913, 14174]
for i in range(4):
cs = ds.GetRasterBand(i + 1).Checksum()
if cs != expected_cs[i]:
- gdaltest.post_reason('failed')
ds = None
gdal.Unlink(tmpfilename)
- return 'fail'
+ pytest.fail()
if ds.GetRasterBand(i + 1).GetRasterColorInterpretation() != gdal.GCI_RedBand + i:
- gdaltest.post_reason('failed')
ds = None
gdal.Unlink(tmpfilename)
- return 'fail'
+ pytest.fail()
ds = None
gdal.Unlink(tmpfilename)
- return 'success'
-
###############################################################################
# Test bugfix for ticket #4771 (rewriting of a deflate compressed tile, libtiff bug)
-def tiff_write_117():
+def test_tiff_write_117():
# This will also fail with a libtiff 4.x older than 2012-08-13
# Might be good to be able to test internal libtiff presence
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
import random
@@ -4778,17 +4060,14 @@ def tiff_write_117():
gdal.Unlink('/vsimem/tiff_write_117.tif')
- if data is None:
- gdaltest.post_reason('if GDAL is configured with external libtiff 4.x, it can fail if it is older than 4.0.3. With internal libtiff, should not fail')
- return 'fail'
-
- return 'success'
+ assert data is not None, \
+ 'if GDAL is configured with external libtiff 4.x, it can fail if it is older than 4.0.3. With internal libtiff, should not fail'
###############################################################################
# Test bugfix for ticket #4816
-def tiff_write_118():
+def test_tiff_write_118():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_write_118.tif', 1, 1)
# Should be rejected in a non-XML domain
@@ -4801,17 +4080,13 @@ def tiff_write_118():
gdal.Unlink('/vsimem/tiff_write_118.tif')
- if md:
- print(md)
- return 'fail'
-
- return 'success'
+ assert not md
###############################################################################
# Test bugfix for ticket #4816
-def tiff_write_119():
+def test_tiff_write_119():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_write_119.tif', 1, 1)
ds.SetMetadata('foo=bar', 'foo')
@@ -4823,17 +4098,13 @@ def tiff_write_119():
gdal.Unlink('/vsimem/tiff_write_119.tif')
- if md['foo'] != 'bar':
- print(md)
- return 'fail'
-
- return 'success'
+ assert md['foo'] == 'bar'
###############################################################################
# Test bugfix for ticket #4816
-def tiff_write_120():
+def test_tiff_write_120():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/tiff_write_120.tif', 1, 1)
ds.SetMetadata('', 'xml:foo')
@@ -4845,20 +4116,14 @@ def tiff_write_120():
gdal.Unlink('/vsimem/tiff_write_120.tif')
- if len(md) != 1:
- print(md)
- return 'fail'
- if md[0] != '':
- print(md)
- return 'fail'
-
- return 'success'
+ assert len(md) == 1
+ assert md[0] == ''
###############################################################################
# Test error cases of COPY_SRC_OVERVIEWS creation option
-def tiff_write_121():
+def test_tiff_write_121():
# Test when the overview band is NULL
src_ds = gdal.Open("""
@@ -4876,9 +4141,7 @@ def tiff_write_121():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_121.tif', src_ds, options=['COPY_SRC_OVERVIEWS=YES'])
gdal.PopErrorHandler()
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
src_ds = None
# Test when the overview count isn't the same on all base bands
@@ -4903,9 +4166,7 @@ def tiff_write_121():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_121.tif', src_ds, options=['COPY_SRC_OVERVIEWS=YES'])
gdal.PopErrorHandler()
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
src_ds = None
# Test when the overview bands of same level have not the same dimensions
@@ -4934,20 +4195,16 @@ def tiff_write_121():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_121.tif', src_ds, options=['COPY_SRC_OVERVIEWS=YES'])
gdal.PopErrorHandler()
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
src_ds = None
- return 'success'
-
###############################################################################
# Test write and read of some TIFFTAG_RESOLUTIONUNIT tags where '*'/'' is
# specified (gdalwarp conflicts)
# Expected to fail (properly) with older libtiff versions (<=3.8.2 for sure)
-def tiff_write_122():
+def test_tiff_write_122():
new_ds = gdaltest.tiff_drv.Create('tmp/tags122.tif', 1, 1, 1)
new_ds.SetMetadata({
@@ -4961,24 +4218,20 @@ def tiff_write_122():
md = new_ds.GetMetadata()
if 'TIFFTAG_RESOLUTIONUNIT' not in md:
- gdaltest.post_reason('Couldnt find tag TIFFTAG_RESOLUTIONUNIT')
- return 'fail'
+ pytest.fail('Couldnt find tag TIFFTAG_RESOLUTIONUNIT')
elif md['TIFFTAG_RESOLUTIONUNIT'] != '1 (unitless)':
- gdaltest.post_reason("Got unexpected tag TIFFTAG_RESOLUTIONUNIT='%s' (expected ='1 (unitless)')" % md['TIFFTAG_RESOLUTIONUNIT'])
- return 'fail'
+ pytest.fail("Got unexpected tag TIFFTAG_RESOLUTIONUNIT='%s' (expected ='1 (unitless)')" % md['TIFFTAG_RESOLUTIONUNIT'])
new_ds = None
gdaltest.tiff_drv.Delete('tmp/tags122.tif')
- return 'success'
-
###############################################################################
# Test implicit photometric interpretation
-def tiff_write_123():
+def test_tiff_write_123():
src_ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_123_src.tif', 1, 1, 5, gdal.GDT_Int16)
src_ds.GetRasterBand(2).SetColorInterpretation(gdal.GCI_GreenBand)
@@ -4987,54 +4240,27 @@ def tiff_write_123():
src_ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_RedBand)
src_ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_123_src.tif.aux.xml', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is not None:
- gdaltest.post_reason('did not expect PAM file')
- return 'fail'
+ assert statBuf is None, 'did not expect PAM file'
src_ds = gdal.Open('/vsimem/tiff_write_123_src.tif')
- if src_ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is not None:
- gdaltest.post_reason('did not expect a TIFFTAG_GDAL_METADATA tag')
- return 'fail'
- if src_ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') != '2':
- gdaltest.post_reason('fail')
- print(src_ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_'))
- return 'fail'
- if src_ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if src_ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_Undefined:
- gdaltest.post_reason('fail')
- return 'fail'
- if src_ds.GetRasterBand(5).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if src_ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '0,2':
- gdaltest.post_reason('fail')
- print(src_ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
+ assert src_ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is None, \
+ 'did not expect a TIFFTAG_GDAL_METADATA tag'
+ assert src_ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') == '2'
+ assert src_ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand
+ assert src_ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_Undefined
+ assert src_ds.GetRasterBand(5).GetColorInterpretation() == gdal.GCI_AlphaBand
+ assert src_ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '0,2'
new_ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_123.tif', src_ds)
del new_ds
statBuf = gdal.VSIStatL('/vsimem/tiff_write_123.tif.aux.xml', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is not None:
- gdaltest.post_reason('did not expect PAM file')
- return 'fail'
+ assert statBuf is None, 'did not expect PAM file'
ds = gdal.Open('/vsimem/tiff_write_123.tif')
- if ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is not None:
- gdaltest.post_reason('did not expect a TIFFTAG_GDAL_METADATA tag')
- return 'fail'
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if src_ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_Undefined:
- gdaltest.post_reason('fail')
- return 'fail'
- if src_ds.GetRasterBand(5).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '0,2':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is None, \
+ 'did not expect a TIFFTAG_GDAL_METADATA tag'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand
+ assert src_ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_Undefined
+ assert src_ds.GetRasterBand(5).GetColorInterpretation() == gdal.GCI_AlphaBand
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '0,2'
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_src.tif')
@@ -5042,47 +4268,24 @@ def tiff_write_123():
# From implicit RGB to BGR (with Photometric = MinIsBlack)
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_123_bgr.tif', 1, 1, 3, gdal.GDT_Byte)
- if ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') != '2':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_'))
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') is not None:
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') == '2'
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') is None
ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_BlueBand)
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_BlueBand:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_BlueBand
ds.GetRasterBand(2).SetColorInterpretation(gdal.GCI_GreenBand)
ds.GetRasterBand(3).SetColorInterpretation(gdal.GCI_RedBand)
ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_123_bgr.tif.aux.xml',
gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is not None:
- gdaltest.post_reason('did not expect a PAM file')
- return 'fail'
+ assert statBuf is None, 'did not expect a PAM file'
ds = gdal.Open('/vsimem/tiff_write_123_bgr.tif')
- if ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') != '1':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_'))
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '0,0':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is None:
- gdaltest.post_reason('expected a TIFFTAG_GDAL_METADATA tag')
- return 'fail'
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_BlueBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GreenBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') == '1'
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '0,0'
+ assert ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is not None, \
+ 'expected a TIFFTAG_GDAL_METADATA tag'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_BlueBand
+ assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GreenBand
+ assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_RedBand
ds = None
# Test overriding internal color interpretation with PAM one (read-only mode)
@@ -5091,19 +4294,11 @@ def tiff_write_123():
ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_123_bgr.tif.aux.xml',
gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is None:
- gdaltest.post_reason('expected a PAM file')
- return 'fail'
+ assert statBuf is not None, 'expected a PAM file'
ds = gdal.Open('/vsimem/tiff_write_123_bgr.tif')
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GreenBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand
+ assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GreenBand
+ assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_RedBand
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_bgr.tif')
@@ -5116,54 +4311,27 @@ def tiff_write_123():
ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_123_bgr.tif.aux.xml',
gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is None:
- gdaltest.post_reason('expected a PAM file')
- return 'fail'
+ assert statBuf is not None, 'expected a PAM file'
ds = gdal.Open('/vsimem/tiff_write_123_bgr.tif')
- if ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is not None:
- gdaltest.post_reason('did not expect a TIFFTAG_GDAL_METADATA tag')
- return 'fail'
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_BlueBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_GreenBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(3).GetColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is None, \
+ 'did not expect a TIFFTAG_GDAL_METADATA tag'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_BlueBand
+ assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_GreenBand
+ assert ds.GetRasterBand(3).GetColorInterpretation() == gdal.GCI_RedBand
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_bgr.tif')
# From implicit RGBA to MINISBLACK
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_123_rgba.tif', 1, 1, 4, gdal.GDT_Byte)
- if ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') != '2':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_'))
- return 'fail'
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '2':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') == '2'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand
+ assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '2'
ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_Undefined)
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_Undefined:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') != '1':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_'))
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') != '0,0,2':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_Undefined
+ assert ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') == '1'
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') == '0,0,2'
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_rgba.tif')
@@ -5177,19 +4345,12 @@ def tiff_write_123():
ds.GetRasterBand(4).SetColorInterpretation(gdal.GCI_AlphaBand)
ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_123_guua.tif.aux.xml', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is not None:
- gdaltest.post_reason('did not expect PAM file')
- return 'fail'
+ assert statBuf is None, 'did not expect PAM file'
ds = gdal.Open('/vsimem/tiff_write_123_guua.tif')
- if ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is not None:
- gdaltest.post_reason('did not expect TIFFTAG_GDAL_METADATA tag')
- return 'fail'
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GrayIndex:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_GDAL_METADATA', '_DEBUG_') is None, \
+ 'did not expect TIFFTAG_GDAL_METADATA tag'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_GrayIndex
+ assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_AlphaBand
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_guua.tif')
@@ -5198,14 +4359,8 @@ def tiff_write_123():
1, 1, 3, gdal.GDT_UInt16, options=['PHOTOMETRIC=RGB'])
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_123_rgb.tif', src_ds)
src_ds = None
- if ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') != '2':
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_'))
- return 'fail'
- if ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') is not None:
- gdaltest.post_reason('fail')
- print(ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_'))
- return 'fail'
+ assert ds.GetMetadataItem('TIFFTAG_PHOTOMETRIC', '_DEBUG_') == '2'
+ assert ds.GetMetadataItem('TIFFTAG_EXTRASAMPLES', '_DEBUG_') is None
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_rgb_src.tif')
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_rgb.tif')
@@ -5216,9 +4371,7 @@ def tiff_write_123():
gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_123_rgb.tif', src_ds,
options=['PHOTOMETRIC=RGB'])
ds = gdal.Open('/vsimem/tiff_write_123_rgb.tif')
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_rgb.tif')
@@ -5227,15 +4380,9 @@ def tiff_write_123():
gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_123_rgbua.tif', src_ds,
options=['PHOTOMETRIC=RGB'])
ds = gdal.Open('/vsimem/tiff_write_123_rgbua.tif')
- if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_RedBand:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_Undefined:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(5).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_RedBand
+ assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_Undefined
+ assert ds.GetRasterBand(5).GetColorInterpretation() == gdal.GCI_AlphaBand
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_rgbua.tif')
@@ -5246,23 +4393,17 @@ def tiff_write_123():
ds.GetRasterBand(4).SetColorInterpretation(gdal.GCI_Undefined)
ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_123_rgba_to_undefined.tif.aux.xml', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is not None:
- gdaltest.post_reason('did not expect PAM file')
- return 'fail'
+ assert statBuf is None, 'did not expect PAM file'
ds = gdal.Open('/vsimem/tiff_write_123_rgba_to_undefined.tif')
- if ds.GetRasterBand(4).GetColorInterpretation() != gdal.GCI_Undefined:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(4).GetColorInterpretation() == gdal.GCI_Undefined
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_123_rgba_to_undefined.tif')
- return 'success'
-
###############################################################################
# Test error cases with palette creation
-def tiff_write_124():
+def test_tiff_write_124():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_124.tif', 1, 1, 3, gdal.GDT_Byte)
@@ -5270,15 +4411,13 @@ def tiff_write_124():
# Test "SetColorTable() can only be called on band 1"
ret = ds.GetRasterBand(2).SetColorTable(gdal.ColorTable())
gdal.PopErrorHandler()
- if ret == 0:
- return 'fail'
+ assert ret != 0
gdal.PushErrorHandler('CPLQuietErrorHandler')
# Test "SetColorTable() not supported for multi-sample TIFF files"
ret = ds.GetRasterBand(1).SetColorTable(gdal.ColorTable())
gdal.PopErrorHandler()
- if ret == 0:
- return 'fail'
+ assert ret != 0
ds = None
@@ -5287,8 +4426,7 @@ def tiff_write_124():
# Test "SetColorTable() only supported for Byte or UInt16 bands in TIFF format."
ret = ds.GetRasterBand(1).SetColorTable(gdal.ColorTable())
gdal.PopErrorHandler()
- if ret == 0:
- return 'fail'
+ assert ret != 0
ds = None
gdal.PushErrorHandler('CPLQuietErrorHandler')
@@ -5299,16 +4437,14 @@ def tiff_write_124():
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_124.tif')
- return 'success'
-
###############################################################################
# Test out-of-memory conditions with SplitBand and SplitBitmapBand
-def tiff_write_125():
+def test_tiff_write_125():
if gdal.GetConfigOption('SKIP_MEM_INTENSIVE_TEST') is not None:
- return 'skip'
+ pytest.skip()
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_125.tif', 2147000000, 5000, 65535, options=['SPARSE_OK=YES', 'BLOCKYSIZE=5000', 'COMPRESS=LZW', 'BIGTIFF=NO'])
ds = None
@@ -5332,17 +4468,15 @@ def tiff_write_125():
gdal.Unlink('/vsimem/tiff_write_125.tif')
- return 'success'
-
###############################################################################
# Test implicit JPEG-in-TIFF overviews
-def tiff_write_126():
+def test_tiff_write_126():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
src_ds = gdal.Open('../gdrivers/data/small_world_400pct.vrt')
@@ -5367,50 +4501,21 @@ def tiff_write_126():
ds = gdal.Open('/vsimem/tiff_write_126.tif')
# Officially we have 0 public overviews...
- if ds.GetRasterBand(1).GetOverviewCount() != 0:
- print(options)
- print(ds.GetRasterBand(1).GetOverviewCount())
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 0, options
# But they do exist...
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs not in cs1:
- print(options)
- print(cs)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert cs in cs1, options
cs = ds.GetRasterBand(2).GetOverview(0).Checksum()
- if cs not in cs2:
- print(options)
- print(cs)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert cs in cs2, options
cs = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs not in cs3:
- print(options)
- print(cs)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert cs in cs3, options
cs = ds.GetRasterBand(1).GetOverview(2).Checksum()
- if cs not in cs4:
- print(options)
- print(cs)
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetOverview(-1) is not None:
- print(options)
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetOverview(3) is not None:
- print(options)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert cs in cs4, options
+ assert ds.GetRasterBand(1).GetOverview(-1) is None, options
+ assert ds.GetRasterBand(1).GetOverview(3) is None, options
ovr_1_data = ds.GetRasterBand(1).GetOverview(1).GetDataset().ReadRaster(0, 0, 400, 200)
subsampled_data = ds.ReadRaster(0, 0, 1600, 800, 400, 200)
- if ovr_1_data != subsampled_data:
- print(options)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ovr_1_data == subsampled_data, options
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_126.tif')
@@ -5431,36 +4536,17 @@ def tiff_write_126():
ds = gdal.Open('/vsimem/tiff_write_126.tif')
# Officially we have 0 public overviews...
- if ds.GetRasterBand(1).GetOverviewCount() != 0:
- print(options)
- print(ds.GetRasterBand(1).GetOverviewCount())
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 0, options
# But they do exist...
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs not in cs1:
- print(options)
- print(cs)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert cs in cs1, options
cs = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs not in cs3:
- print(options)
- print(cs)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert cs in cs3, options
cs = ds.GetRasterBand(1).GetOverview(2).Checksum()
- if cs not in cs4:
- print(options)
- print(cs)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert cs in cs4, options
ovr_1_data = ds.GetRasterBand(1).GetOverview(1).GetDataset().ReadRaster(0, 0, 400, 200)
subsampled_data = ds.ReadRaster(0, 0, 1600, 800, 400, 200)
- if ovr_1_data != subsampled_data:
- print(options)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ovr_1_data == subsampled_data, options
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_126.tif')
@@ -5474,16 +4560,11 @@ def tiff_write_126():
ds = None
ds = gdal.Open('/vsimem/tiff_write_126.tif')
- if ds.GetRasterBand(1).GetBlockSize() != [8, 1]:
- print(ds.GetRasterBand(1).GetBlockSize())
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetBlockSize() == [8, 1]
ovr_ds = ds.GetRasterBand(1).GetOverview(1).GetDataset()
ovr_1_data = ovr_ds.ReadRaster(0, 0, ovr_ds.RasterXSize, ovr_ds.RasterYSize, 1, 1)
subsampled_data = ds.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, 1, 1)
- if ovr_1_data != subsampled_data:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ovr_1_data == subsampled_data
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_126.tif')
@@ -5491,25 +4572,17 @@ def tiff_write_126():
# We need libtiff 4.0.4 (unreleased at that time)
if md['LIBTIFF'] != 'INTERNAL':
print('skipping tests that will fail without internal libtiff')
- return 'success'
+ return
# Test with completely sparse file
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_126.tif', 1024, 1024, options=['COMPRESS=JPEG', 'SPARSE_OK=YES'])
ds = None
ds = gdal.Open('/vsimem/tiff_write_126.tif')
- if ds.GetRasterBand(1).GetOverview(0) is None:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('JPEGTABLES', 'TIFF') is None:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_0', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_0', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverview(0) is not None
+ assert ds.GetRasterBand(1).GetMetadataItem('JPEGTABLES', 'TIFF') is not None
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_0', 'TIFF') is None
+ assert ds.GetRasterBand(1).GetMetadataItem('BLOCK_SIZE_0_0', 'TIFF') is None
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_126.tif')
@@ -5521,20 +4594,15 @@ def tiff_write_126():
ds = gdal.Open('/vsimem/tiff_write_126.tif')
cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs != 0:
- print(cs)
- gdaltest.post_reason('fail')
- return 'fail'
+ assert cs == 0
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_126.tif')
- return 'success'
-
###############################################################################
# Test setting/unsetting metadata in update mode (#5628)
-def tiff_write_127():
+def test_tiff_write_127():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_127.tif', 1, 1)
ds = None
@@ -5550,62 +4618,48 @@ def tiff_write_127():
ds = gdal.Open('/vsimem/tiff_write_127.tif', gdal.GA_Update)
obj = ds if i == 0 else ds.GetRasterBand(1)
if obj.GetMetadataItem('key') != 'value':
- gdaltest.post_reason('fail')
print(i)
- print(obj.GetMetadata())
- return 'fail'
+ pytest.fail(obj.GetMetadata())
obj.SetMetadata({})
obj = None
ds = None
ds = gdal.Open('/vsimem/tiff_write_127.tif', gdal.GA_Update)
obj = ds if i == 0 else ds.GetRasterBand(1)
- if obj.GetMetadata():
- gdaltest.post_reason('fail')
- print(i)
- return 'fail'
+ assert not obj.GetMetadata(), i
obj.SetMetadataItem('key', 'value')
obj = None
ds = None
ds = gdal.Open('/vsimem/tiff_write_127.tif', gdal.GA_Update)
obj = ds if i == 0 else ds.GetRasterBand(1)
- if obj.GetMetadataItem('key') != 'value':
- gdaltest.post_reason('fail')
- print(i)
- return 'fail'
+ assert obj.GetMetadataItem('key') == 'value', i
obj.SetMetadataItem('key', None)
obj = None
ds = None
ds = gdal.Open('/vsimem/tiff_write_127.tif', gdal.GA_Update)
obj = ds if i == 0 else ds.GetRasterBand(1)
- if obj.GetMetadata():
- gdaltest.post_reason('fail')
- print(i)
- return 'fail'
+ assert not obj.GetMetadata(), i
obj = None
ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_127.tif.aux.xml')
if statBuf is not None:
- gdaltest.post_reason('unexpected PAM file')
print(i)
- return 'fail'
+ pytest.fail('unexpected PAM file')
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_127.tif')
- return 'success'
-
###############################################################################
# Test lossless copying of a CMYK JPEG into JPEG-in-TIFF (#5712)
-def tiff_write_128():
+def test_tiff_write_128():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
gdal.SetConfigOption('GDAL_JPEG_TO_RGB', 'NO')
src_ds = gdal.Open('../gdrivers/data/rgb_ntf_cmyk.jpg')
@@ -5621,12 +4675,8 @@ def tiff_write_128():
# We need to reopen in raw to avoig automatic CMYK->RGBA to trigger
ds = gdal.Open('GTIFF_RAW:/vsimem/tiff_write_128.tif')
for i in range(4):
- if src_ds.GetRasterBand(i + 1).GetColorInterpretation() != ds.GetRasterBand(i + 1).GetColorInterpretation():
- gdaltest.post_reason('fail')
- return 'fail'
- if src_ds.GetRasterBand(i + 1).Checksum() != ds.GetRasterBand(i + 1).Checksum():
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_ds.GetRasterBand(i + 1).GetColorInterpretation() == ds.GetRasterBand(i + 1).GetColorInterpretation()
+ assert src_ds.GetRasterBand(i + 1).Checksum() == ds.GetRasterBand(i + 1).Checksum()
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_128.tif')
@@ -5641,12 +4691,8 @@ def tiff_write_128():
# We need to reopen in raw to avoig automatic CMYK->RGBA to trigger
ds = gdal.Open('GTIFF_RAW:/vsimem/tiff_write_128.tif')
for i in range(4):
- if src_ds.GetRasterBand(i + 1).GetColorInterpretation() != ds.GetRasterBand(i + 1).GetColorInterpretation():
- gdaltest.post_reason('fail')
- return 'fail'
- if src_ds.GetRasterBand(i + 1).Checksum() != ds.GetRasterBand(i + 1).Checksum():
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_ds.GetRasterBand(i + 1).GetColorInterpretation() == ds.GetRasterBand(i + 1).GetColorInterpretation()
+ assert src_ds.GetRasterBand(i + 1).Checksum() == ds.GetRasterBand(i + 1).Checksum()
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_128.tif')
@@ -5662,29 +4708,23 @@ def tiff_write_128():
ds = gdal.Open('/vsimem/tiff_write_128.tif')
for i in range(4):
# The color interpretation will NOT be CMYK
- if src_ds.GetRasterBand(i + 1).GetColorInterpretation() == ds.GetRasterBand(i + 1).GetColorInterpretation():
- gdaltest.post_reason('fail')
- return 'fail'
- if src_ds.GetRasterBand(i + 1).Checksum() != ds.GetRasterBand(i + 1).Checksum():
- gdaltest.post_reason('fail')
- return 'fail'
+ assert src_ds.GetRasterBand(i + 1).GetColorInterpretation() != ds.GetRasterBand(i + 1).GetColorInterpretation()
+ assert src_ds.GetRasterBand(i + 1).Checksum() == ds.GetRasterBand(i + 1).Checksum()
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_128.tif')
- return 'success'
-
###############################################################################
# Check effective guessing of existing JPEG quality
-def tiff_write_129():
+def test_tiff_write_129():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
for jpegtablesmode in ['1', '3']:
for photometric in ['RGB', 'YCBCR']:
@@ -5712,108 +4752,85 @@ def tiff_write_129():
if i == 0:
cs_ref = cs
elif cs != cs_ref:
- gdaltest.post_reason('fail')
- print(jpegtablesmode)
print(photometric)
print(i)
- return 'fail'
-
- return 'success'
+ pytest.fail(jpegtablesmode)
+
###############################################################################
# Test cases where JPEG quality will fail
-def tiff_write_130():
+def test_tiff_write_130():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
shutil.copyfile('data/byte_jpg_unusual_jpegtable.tif', 'tmp/byte_jpg_unusual_jpegtable.tif')
ds = gdal.Open('tmp/byte_jpg_unusual_jpegtable.tif', gdal.GA_Update)
- if ds.GetRasterBand(1).Checksum() != 4771:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).Checksum())
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4771
src_ds = gdal.Open('data/byte.tif', gdal.GA_Update)
ds.WriteRaster(0, 0, 20, 20, src_ds.ReadRaster())
src_ds = None
ds = None
ds = gdal.Open('tmp/byte_jpg_unusual_jpegtable.tif')
- if ds.GetRasterBand(1).Checksum() != 4743:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).Checksum())
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4743
ds = None
os.unlink('tmp/byte_jpg_unusual_jpegtable.tif')
shutil.copyfile('data/byte_jpg_tablesmodezero.tif', 'tmp/byte_jpg_tablesmodezero.tif')
ds = gdal.Open('tmp/byte_jpg_tablesmodezero.tif', gdal.GA_Update)
- if ds.GetRasterBand(1).Checksum() != 4743:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).Checksum())
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4743
src_ds = gdal.Open('data/byte.tif', gdal.GA_Update)
ds.WriteRaster(0, 0, 20, 20, src_ds.ReadRaster())
src_ds = None
ds = None
ds = gdal.Open('tmp/byte_jpg_tablesmodezero.tif')
- if ds.GetRasterBand(1).Checksum() != 4743:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).Checksum())
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4743
ds = None
os.unlink('tmp/byte_jpg_tablesmodezero.tif')
- return 'success'
-
###############################################################################
# Test LZMA compression
-def tiff_write_131(level=1):
+def test_tiff_write_131(level=1):
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LZMA') == -1:
- return 'skip'
+ pytest.skip()
filename = '/vsimem/tiff_write_131.tif'
src_ds = gdal.Open('data/byte.tif')
ds = gdaltest.tiff_drv.CreateCopy(filename, src_ds,
options=['COMPRESS=LZMA', 'LZMA_PRESET=' + str(level)])
- if ds.GetRasterBand(1).Checksum() != 4672:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672
ds = None
# LZMA requires an howful amount of memory even on small files
if gdal.GetLastErrorMsg().find('cannot allocate memory') >= 0:
gdal.Unlink(filename)
- return 'skip'
+ pytest.skip()
ds = gdal.Open(filename)
- if ds.GetRasterBand(1).Checksum() != 4672:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4672
ds = None
gdal.Unlink(filename)
- return 'success'
-
-def tiff_write_131_level_9():
- return tiff_write_131(level=9)
+def test_tiff_write_131_level_9():
+ return test_tiff_write_131(level=9)
###############################################################################
# Test that PAM metadata is cleared when internal metadata is set (#5807)
-def tiff_write_132():
+def test_tiff_write_132():
for i in range(2):
@@ -5827,9 +4844,7 @@ def tiff_write_132():
ds = None
# Check that PAM file exists
- if gdal.VSIStatL('/vsimem/tiff_write_132.tif.aux.xml') is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_132.tif.aux.xml') is not None
# Open in read-write
ds = gdal.Open('/vsimem/tiff_write_132.tif', gdal.GA_Update)
@@ -5842,26 +4857,20 @@ def tiff_write_132():
ds = None
# Check that PAM file no longer exists
- if gdal.VSIStatL('/vsimem/tiff_write_132.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- print(i)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_132.tif.aux.xml') is None, i
ds = gdal.Open('/vsimem/tiff_write_132.tif')
- if ds.GetMetadataItem('FOO') != 'BAZ' or ds.GetRasterBand(1).GetMetadataItem('FOO') != 'BAZ':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('FOO') == 'BAZ' and ds.GetRasterBand(1).GetMetadataItem('FOO') == 'BAZ'
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_132.tif')
- return 'success'
-
+
###############################################################################
# Test streaming capabilities
-def tiff_write_133():
+def test_tiff_write_133():
src_ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_133.tif', 1024, 1000, 3, options=['STREAMABLE_OUTPUT=YES'])
src_ds.SetGeoTransform([1, 2, 0, 3, 0, -2])
@@ -5878,45 +4887,31 @@ def tiff_write_133():
gdal.PushErrorHandler()
ret = src_ds.SetProjection(srs.ExportToWkt())
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
gdal.PushErrorHandler()
ret = src_ds.SetGeoTransform([1, 2, 0, 3, 0, -4])
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
gdal.PushErrorHandler()
ret = src_ds.SetMetadataItem('FOO', 'BAZ')
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
gdal.PushErrorHandler()
ret = src_ds.SetMetadata({})
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
gdal.PushErrorHandler()
ret = src_ds.GetRasterBand(1).SetMetadataItem('FOO', 'BAZ')
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
gdal.PushErrorHandler()
ret = src_ds.GetRasterBand(1).SetMetadata({})
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
gdal.PushErrorHandler()
ret = src_ds.GetRasterBand(1).SetNoDataValue(0)
gdal.PopErrorHandler()
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
# Pixel interleaved
out_ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_133_dst.tif', src_ds, options=['STREAMABLE_OUTPUT=YES', 'BLOCKYSIZE=32'])
@@ -5925,34 +4920,22 @@ def tiff_write_133():
gdal.SetConfigOption('TIFF_READ_STREAMING', 'YES')
ds = gdal.Open('/vsimem/tiff_write_133_dst.tif')
gdal.SetConfigOption('TIFF_READ_STREAMING', None)
- if ds.GetProjectionRef().find('32601') < 0:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGeoTransform() != (1.0, 2.0, 0.0, 3.0, 0.0, -2.0):
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('FOO') != 'BAR':
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetProjectionRef().find('32601') >= 0
+ assert ds.GetGeoTransform() == (1.0, 2.0, 0.0, 3.0, 0.0, -2.0)
+ assert ds.GetMetadataItem('FOO') == 'BAR'
+ assert ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') is None
with gdaltest.SetCacheMax(0):
for y in range(1000):
got_data = ds.ReadRaster(0, y, 1024, 1)
- if got_data is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_data is not None
ds.FlushCache()
for y in range(1000):
gdal.PushErrorHandler()
got_data = ds.ReadRaster(0, y, 1024, 1)
gdal.PopErrorHandler()
- if got_data is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_data is None
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_133_dst.tif')
@@ -5963,18 +4946,10 @@ def tiff_write_133():
gdal.SetConfigOption('TIFF_READ_STREAMING', 'YES')
ds = gdal.Open('/vsimem/tiff_write_133_dst.tif')
gdal.SetConfigOption('TIFF_READ_STREAMING', None)
- if ds.GetProjectionRef().find('32601') < 0:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGeoTransform() != (1.0, 2.0, 0.0, 3.0, 0.0, -2.0):
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('FOO') != 'BAR':
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetProjectionRef().find('32601') >= 0
+ assert ds.GetGeoTransform() == (1.0, 2.0, 0.0, 3.0, 0.0, -2.0)
+ assert ds.GetMetadataItem('FOO') == 'BAR'
+ assert ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') is None
with gdaltest.SetCacheMax(0):
for yblock in range(int((1000 + 256 - 1) / 256)):
@@ -5988,9 +4963,7 @@ def tiff_write_133():
if x + xsize > ds.RasterXSize:
xsize = ds.RasterXSize - x
got_data = ds.ReadRaster(x, y, xsize, ysize)
- if got_data is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_data is not None
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_133_dst.tif')
@@ -6002,17 +4975,13 @@ def tiff_write_133():
gdal.SetConfigOption('TIFF_READ_STREAMING', 'YES')
ds = gdal.Open('/vsimem/tiff_write_133_dst.tif')
gdal.SetConfigOption('TIFF_READ_STREAMING', None)
- if ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') is None
with gdaltest.SetCacheMax(0):
for band in range(3):
for y in range(1000):
got_data = ds.GetRasterBand(band + 1).ReadRaster(0, y, 1024, 1)
- if got_data is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_data is not None
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_133_dst.tif')
@@ -6025,16 +4994,12 @@ def tiff_write_133():
gdal.SetConfigOption('TIFF_READ_STREAMING', 'YES')
ds = gdal.Open('/vsimem/tiff_write_133_dst.tif')
gdal.SetConfigOption('TIFF_READ_STREAMING', None)
- if ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') is None
with gdaltest.SetCacheMax(0):
for y in range(1000):
got_data = ds.ReadRaster(0, y, 1024, 1)
- if got_data is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_data is not None
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_133_dst.tif')
@@ -6043,22 +5008,16 @@ def tiff_write_133():
gdal.PushErrorHandler()
out_ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_133_dst.tif', src_ds, options=['STREAMABLE_OUTPUT=YES', 'COMPRESS=DEFLATE'])
gdal.PopErrorHandler()
- if out_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert out_ds is None
# Test writing into a non authorized file
ds = gdaltest.tiff_drv.Create('/foo/bar', 1024, 1000, 3, options=['STREAMABLE_OUTPUT=YES', 'BLOCKYSIZE=1'])
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
gdal.PushErrorHandler()
out_ds = gdaltest.tiff_drv.CreateCopy('/foo/bar', src_ds, options=['STREAMABLE_OUTPUT=YES'])
gdal.PopErrorHandler()
- if out_ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert out_ds is None
src_ds = None
@@ -6068,9 +5027,7 @@ def tiff_write_133():
ds = gdal.Open('data/byte.tif')
gdal.PopErrorHandler()
gdal.SetConfigOption('TIFF_READ_STREAMING', None)
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
# BigTIFF with IFD not at offset 16
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') >= 0:
@@ -6085,9 +5042,7 @@ def tiff_write_133():
ds = gdal.Open('/vsimem/tiff_write_133.tif')
gdal.PopErrorHandler()
gdal.SetConfigOption('TIFF_READ_STREAMING', None)
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
# Test reading strips in not increasing order
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_133.tif', 1024, 1000, 3, options=['BLOCKYSIZE=1'])
@@ -6101,16 +5056,12 @@ def tiff_write_133():
ds = gdal.Open('/vsimem/tiff_write_133.tif')
gdal.PopErrorHandler()
gdal.SetConfigOption('TIFF_READ_STREAMING', None)
- if ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') != 'YES':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetMetadataItem('UNORDERED_BLOCKS', 'TIFF') == 'YES'
with gdaltest.SetCacheMax(0):
for y in range(1000):
got_data = ds.ReadRaster(0, 1000 - y - 1, 1024, 1)
- if got_data is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert got_data is not None
# Test writing strips in not increasing order in a streamable output
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_133.tif', 1024, 1000, 3, options=['STREAMABLE_OUTPUT=YES', 'BLOCKYSIZE=1'])
@@ -6119,9 +5070,7 @@ def tiff_write_133():
ret = ds.WriteRaster(0, 999, 1024, 1, 'a' * (3 * 1024))
ds.FlushCache()
gdal.PopErrorHandler()
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() != ''
ds = None
# Test writing tiles in not increasing order in a streamable output
@@ -6131,20 +5080,16 @@ def tiff_write_133():
ret = ds.WriteRaster(256, 256, 256, 256, 'a' * (3 * 256 * 256))
ds.FlushCache()
gdal.PopErrorHandler()
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() != ''
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_133.tif')
- return 'success'
-
###############################################################################
# Test DISCARD_LSB
-def tiff_write_134():
+def test_tiff_write_134():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_134.tif', 1, 1, 3, options=['DISCARD_LSB=0,1,3'])
ds.GetRasterBand(1).Fill(127)
@@ -6155,12 +5100,7 @@ def tiff_write_134():
cs1 = ds.GetRasterBand(1).Checksum()
cs2 = ds.GetRasterBand(2).Checksum()
cs3 = ds.GetRasterBand(3).Checksum()
- if cs1 != 1 or cs2 != 0 or cs3 != 5:
- gdaltest.post_reason('fail')
- print(cs1)
- print(cs2)
- print(cs3)
- return 'fail'
+ assert cs1 == 1 and cs2 == 0 and cs3 == 5
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_134.tif')
@@ -6174,12 +5114,7 @@ def tiff_write_134():
cs1 = ds.GetRasterBand(1).Checksum()
cs2 = ds.GetRasterBand(2).Checksum()
cs3 = ds.GetRasterBand(3).Checksum()
- if cs1 != 1 or cs2 != 0 or cs3 != 5:
- gdaltest.post_reason('fail')
- print(cs1)
- print(cs2)
- print(cs3)
- return 'fail'
+ assert cs1 == 1 and cs2 == 0 and cs3 == 5
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_134_src.tif')
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_134.tif')
@@ -6193,22 +5128,15 @@ def tiff_write_134():
cs1 = ds.GetRasterBand(1).Checksum()
cs2 = ds.GetRasterBand(2).Checksum()
cs3 = ds.GetRasterBand(3).Checksum()
- if cs1 != 5 or cs2 != 5 or cs3 != 5:
- gdaltest.post_reason('fail')
- print(cs1)
- print(cs2)
- print(cs3)
- return 'fail'
+ assert cs1 == 5 and cs2 == 5 and cs3 == 5
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_134.tif')
- return 'success'
-
###############################################################################
# Test clearing GCPs (#5945)
-def tiff_write_135():
+def test_tiff_write_135():
# Simple clear
src_ds = gdal.Open('data/gcps.vrt')
@@ -6220,12 +5148,8 @@ def tiff_write_135():
ds = None
ds = gdal.Open('/vsimem/tiff_write_135.tif')
- if ds.GetGCPs():
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGCPProjection() != '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert not ds.GetGCPs()
+ assert ds.GetGCPProjection() == ''
ds = None
# Double clear
@@ -6239,12 +5163,8 @@ def tiff_write_135():
ds = None
ds = gdal.Open('/vsimem/tiff_write_135.tif')
- if ds.GetGCPs():
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGCPProjection() != '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert not ds.GetGCPs()
+ assert ds.GetGCPProjection() == ''
ds = None
# Clear + set geotransform and new projection
@@ -6261,26 +5181,18 @@ def tiff_write_135():
ds = None
ds = gdal.Open('/vsimem/tiff_write_135.tif')
- if ds.GetGCPs():
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGeoTransform() != (1, 2, 3, 4, 5, -6):
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetProjectionRef().find('32601') < 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert not ds.GetGCPs()
+ assert ds.GetGeoTransform() == (1, 2, 3, 4, 5, -6)
+ assert ds.GetProjectionRef().find('32601') >= 0
ds = None
gdal.Unlink('/vsimem/tiff_write_135.tif')
- return 'success'
-
###############################################################################
# Test writing a single-strip mono-bit dataset
-def tiff_write_136():
+def test_tiff_write_136():
src_ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_136_src.tif', 8, 2001)
src_ds.GetRasterBand(1).Fill(1)
@@ -6290,23 +5202,17 @@ def tiff_write_136():
ds = None
ds = gdal.Open('/vsimem/tiff_write_136.tif')
cs = ds.GetRasterBand(1).Checksum()
- if cs != expected_cs:
- gdaltest.post_reason('fail')
- print(cs)
- print(expected_cs)
- return 'fail'
+ assert cs == expected_cs
gdal.Unlink('/vsimem/tiff_write_136_src.tif')
gdal.Unlink('/vsimem/tiff_write_136.tif')
gdal.Unlink('/vsimem/tiff_write_136.tif.aux.xml')
- return 'success'
-
###############################################################################
# Test multi-threaded writing
-def tiff_write_137():
+def test_tiff_write_137():
src_ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_137_src.tif', 4000, 4000)
src_ds.GetRasterBand(1).Fill(1)
@@ -6321,11 +5227,7 @@ def tiff_write_137():
ds = gdal.Open('/vsimem/tiff_write_137.tif')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != expected_cs:
- gdaltest.post_reason('fail')
- print(cs)
- print(expected_cs)
- return 'fail'
+ assert cs == expected_cs
# Test NUM_THREADS as creation option with Create()
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_137.tif', 4000, 4000, 1,
@@ -6335,11 +5237,7 @@ def tiff_write_137():
ds = gdal.Open('/vsimem/tiff_write_137.tif')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != expected_cs:
- gdaltest.post_reason('fail')
- print(cs)
- print(expected_cs)
- return 'fail'
+ assert cs == expected_cs
# Test NUM_THREADS as open option
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_137.tif', 4000, 4000,
@@ -6351,11 +5249,7 @@ def tiff_write_137():
ds = gdal.Open('/vsimem/tiff_write_137.tif')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != expected_cs:
- gdaltest.post_reason('fail')
- print(cs)
- print(expected_cs)
- return 'fail'
+ assert cs == expected_cs
# Ask data immediately while the block is compressed
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_137.tif', 4000, 4000,
@@ -6363,10 +5257,7 @@ def tiff_write_137():
ds.WriteRaster(0, 0, 1, 1, 'A')
ds.FlushCache()
val = ds.ReadRaster(0, 0, 1, 1).decode('ascii')
- if val != 'A':
- gdaltest.post_reason('fail')
- print(val)
- return 'fail'
+ assert val == 'A'
ds = None
gdal.Unlink('/vsimem/tiff_write_137_src.tif')
@@ -6381,20 +5272,14 @@ def tiff_write_137():
ds = gdal.Open('/vsimem/tiff_write_137.tif')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 4672:
- gdaltest.post_reason('fail')
- print(cs)
- print(expected_cs)
- return 'fail'
+ assert cs == 4672, expected_cs
gdal.Unlink('/vsimem/tiff_write_137.tif')
- return 'success'
-
###############################################################################
# Test that pixel-interleaved writing generates optimal size
-def tiff_write_138():
+def test_tiff_write_138():
# Test that consecutive IWriteBlock() calls for the same block but in
# different bands only generate a single tile write, and not 3 rewrites
@@ -6408,10 +5293,7 @@ def tiff_write_138():
ds.GetRasterBand(3).FlushCache()
ds = None
size = gdal.VSIStatL('/vsimem/tiff_write_138.tif').size
- if size != 181:
- gdaltest.post_reason('fail')
- print(size)
- return 'fail'
+ assert size == 181
# Test fix for #5999
@@ -6433,21 +5315,16 @@ def tiff_write_138():
tmp_ds = None
ds = None
size = gdal.VSIStatL('/vsimem/tiff_write_138.tif').size
- if size != 181:
- gdaltest.post_reason('fail')
- print(size)
- return 'fail'
+ assert size == 181
gdal.Unlink('/vsimem/tiff_write_138.tif')
gdal.Unlink('/vsimem/tiff_write_138_saturate.tif')
- return 'success'
-
###############################################################################
# Test that pixel-interleaved writing generates optimal size
-def tiff_write_139():
+def test_tiff_write_139():
import struct
drv = gdal.GetDriverByName('GTiff')
@@ -6466,9 +5343,7 @@ def tiff_write_139():
ds = gdal.Open('/vsimem/tiff_write_139.tif')
for i in range(nbands):
content = ds.GetRasterBand(i + 1).ReadRaster()
- if ref_content != content:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ref_content == content
ds = None
gdal.Unlink('/vsimem/tiff_write_139.tif')
@@ -6487,10 +5362,8 @@ def tiff_write_139():
ds = gdal.Open('/vsimem/tiff_write_139.tif')
content = ds.GetRasterBand(1).ReadRaster()
if ref_content != content:
- gdaltest.post_reason('fail')
print(endianness)
- print(struct.unpack('h' * 6, content))
- return 'fail'
+ pytest.fail(struct.unpack('h' * 6, content))
ds = None
gdal.Unlink('/vsimem/tiff_write_139.tif')
@@ -6509,10 +5382,8 @@ def tiff_write_139():
ds = gdal.Open('/vsimem/tiff_write_139.tif')
content = ds.GetRasterBand(1).ReadRaster()
if ref_content != content:
- gdaltest.post_reason('fail')
print(endianness)
- print(struct.unpack('H' * 6, content))
- return 'fail'
+ pytest.fail(struct.unpack('H' * 6, content))
ds = None
gdal.Unlink('/vsimem/tiff_write_139.tif')
@@ -6531,10 +5402,8 @@ def tiff_write_139():
ds = gdal.Open('/vsimem/tiff_write_139.tif')
content = ds.GetRasterBand(1).ReadRaster()
if ref_content != content:
- gdaltest.post_reason('fail')
print(endianness)
- print(struct.unpack('I' * 6, content))
- return 'fail'
+ pytest.fail(struct.unpack('I' * 6, content))
ds = None
gdal.Unlink('/vsimem/tiff_write_139.tif')
@@ -6548,35 +5417,25 @@ def tiff_write_139():
ds = None
ds = gdal.Open('/vsimem/tiff_write_139.tif')
content = ds.GetRasterBand(1).ReadRaster()
- if ref_content != content:
- gdaltest.post_reason('fail')
- print(struct.unpack('d' * 4, content))
- return 'fail'
+ assert ref_content == content, struct.unpack('d' * 4, content)
ds = None
gdal.Unlink('/vsimem/tiff_write_139.tif')
- return 'success'
-
###############################################################################
# Test setting a band to alpha
-def tiff_write_140():
+def test_tiff_write_140():
# Nominal case: set alpha to last band
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_140.tif', 1, 1, 5)
ds.GetRasterBand(5).SetColorInterpretation(gdal.GCI_AlphaBand)
ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_140.tif.aux.xml', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is not None:
- gdaltest.post_reason('did not expect PAM file')
- return 'fail'
+ assert statBuf is None, 'did not expect PAM file'
ds = gdal.Open('/vsimem/tiff_write_140.tif')
- if ds.GetRasterBand(5).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(5).GetColorInterpretation())
- return 'fail'
+ assert ds.GetRasterBand(5).GetColorInterpretation() == gdal.GCI_AlphaBand
ds = None
# Strange case: set alpha to a band, but it is already set on another one
@@ -6586,26 +5445,14 @@ def tiff_write_140():
gdal.ErrorReset()
with gdaltest.error_handler():
ret = ds.GetRasterBand(5).SetColorInterpretation(gdal.GCI_AlphaBand)
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
- if ret != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() != ''
+ assert ret == 0
ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_140.tif.aux.xml', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is not None:
- gdaltest.post_reason('did not expect PAM file')
- return 'fail'
+ assert statBuf is None, 'did not expect PAM file'
ds = gdal.Open('/vsimem/tiff_write_140.tif')
- if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(5).GetColorInterpretation())
- return 'fail'
- if ds.GetRasterBand(5).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(5).GetColorInterpretation())
- return 'fail'
+ assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_AlphaBand
+ assert ds.GetRasterBand(5).GetColorInterpretation() == gdal.GCI_AlphaBand
ds = None
# Strange case: set alpha to a band, but it is already set on another one (because of ALPHA=YES)
@@ -6614,37 +5461,23 @@ def tiff_write_140():
gdal.ErrorReset()
with gdaltest.error_handler():
ret = ds.GetRasterBand(5).SetColorInterpretation(gdal.GCI_AlphaBand)
- if gdal.GetLastErrorMsg().find('ALPHA') < 0:
- gdaltest.post_reason('fail')
- return 'fail'
- if ret != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg().find('ALPHA') >= 0
+ assert ret == 0
ds = None
statBuf = gdal.VSIStatL('/vsimem/tiff_write_140.tif.aux.xml', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG | gdal.VSI_STAT_SIZE_FLAG)
- if statBuf is not None:
- gdaltest.post_reason('did not expect PAM file')
- return 'fail'
+ assert statBuf is None, 'did not expect PAM file'
ds = gdal.Open('/vsimem/tiff_write_140.tif')
- if ds.GetRasterBand(2).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(5).GetColorInterpretation())
- return 'fail'
- if ds.GetRasterBand(5).GetColorInterpretation() != gdal.GCI_AlphaBand:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(5).GetColorInterpretation())
- return 'fail'
+ assert ds.GetRasterBand(2).GetColorInterpretation() == gdal.GCI_AlphaBand
+ assert ds.GetRasterBand(5).GetColorInterpretation() == gdal.GCI_AlphaBand
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_140.tif')
- return 'success'
-
###############################################################################
# Test GEOTIFF_KEYS_FLAVOR=ESRI_PE with EPSG:3857
-def tiff_write_141():
+def test_tiff_write_141():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_141.tif', 1, 1, options=['GEOTIFF_KEYS_FLAVOR=ESRI_PE'])
srs = osr.SpatialReference()
@@ -6656,25 +5489,17 @@ def tiff_write_141():
wkt = ds.GetProjectionRef()
ds = None
- if wkt.find('PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere"') != 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt.find('PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere"') == 0
- if wkt.find('EXTENSION["PROJ4"') < 0:
- gdaltest.post_reason('fail')
- print(wkt)
- return 'fail'
+ assert wkt.find('EXTENSION["PROJ4"') >= 0
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_141.tif')
- return 'success'
-
###############################################################################
# Test PixelIsPoint without SRS (#6225)
-def tiff_write_142():
+def test_tiff_write_142():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_142.tif', 1, 1)
ds.SetMetadataItem('AREA_OR_POINT', 'Point')
@@ -6694,45 +5519,34 @@ def tiff_write_142():
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_142_2.tif')
gt_expected = (10, 1, 0, 100, 0, -1)
- if gt != gt_expected:
- print(gt)
- gdaltest.post_reason('did not get expected geotransform')
- return 'fail'
-
- if md != 'Point':
- gdaltest.post_reason('did not get expected AREA_OR_POINT value')
- return 'fail'
+ assert gt == gt_expected, 'did not get expected geotransform'
- return 'success'
+ assert md == 'Point', 'did not get expected AREA_OR_POINT value'
###############################################################################
# Check that we detect that free space isn't sufficient
-def tiff_write_143():
+def test_tiff_write_143():
with gdaltest.error_handler():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_143.tif', 1000000000, 1000000000)
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# Test creating a real BigTIFF file > 4 GB with multiple directories (on filesystems supporting sparse files)
-def tiff_write_144():
+def test_tiff_write_144():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
- return 'skip'
+ pytest.skip()
# Determine if the filesystem supports sparse files (we don't want to create a real 10 GB
# file !
if not gdaltest.filesystem_supports_sparse_files('tmp'):
- return 'skip'
+ pytest.skip()
ds = gdal.GetDriverByName('GTiff').Create('tmp/tiff_write_144.tif', 20, 20, 1, options=['BIGTIFF=YES'])
ds.GetRasterBand(1).Fill(255)
@@ -6755,19 +5569,13 @@ def tiff_write_144():
gdal.Unlink('tmp/tiff_write_144.tif')
- if got_cs != 4873 or got_cs_ovr != 1218:
- gdaltest.post_reason('fail')
- print(got_cs)
- print(got_cs_ovr)
- return 'fail'
-
- return 'success'
+ assert got_cs == 4873 and got_cs_ovr == 1218
###############################################################################
# Test various warnings / errors of Create()
-def tiff_write_145():
+def test_tiff_write_145():
options_list = [{'bands': 65536, 'expected_failure': True},
{'creation_options': ['INTERLEAVE=foo'], 'expected_failure': True},
@@ -6806,33 +5614,29 @@ def tiff_write_145():
with gdaltest.error_handler():
ds = gdaltest.tiff_drv.Create(filename, xsize, ysize, bands, datatype, options=creation_options)
if ds is not None and options.get('expected_failure', False):
- gdaltest.post_reason('expected failure, but did not get it')
print(options)
- return 'fail'
+ pytest.fail('expected failure, but did not get it')
elif ds is None and not options.get('expected_failure', False):
- gdaltest.post_reason('got failure, but did not expect it')
print(options)
- return 'fail'
+ pytest.fail('got failure, but did not expect it')
ds = None
# print(gdal.GetLastErrorMsg())
if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('did not get any warning/error')
print(options)
- return 'fail'
+ pytest.fail('did not get any warning/error')
gdal.Unlink(filename)
- return 'success'
-
+
###############################################################################
# Test implicit JPEG-in-TIFF overviews with RGBA (not completely sure this
# is a legal formulation since 4 bands should probably be seen as CMYK)
-def tiff_write_146():
+def test_tiff_write_146():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
tmp_ds = gdal.Translate('', 'data/stefan_full_rgba.tif', format='MEM')
original_stats = [tmp_ds.GetRasterBand(i + 1).ComputeStatistics(True) for i in range(4)]
@@ -6844,25 +5648,20 @@ def tiff_write_146():
for i in range(4):
for j in range(4):
- if i != 2 and j >= 2 and abs(original_stats[i][j] - got_stats[i][j]) > 5:
- gdaltest.post_reason('did not get expected statistics')
- print(i, j)
- print(original_stats)
- print(got_stats)
- return 'fail'
-
- return 'success'
+ assert i == 2 or j < 2 or abs(original_stats[i][j] - got_stats[i][j]) <= 5, \
+ 'did not get expected statistics'
+
###############################################################################
# Test that we don't use implicit JPEG-in-TIFF overviews with CMYK when converting
# to RGBA
-def tiff_write_147():
+def test_tiff_write_147():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
gdal.SetConfigOption('GDAL_JPEG_TO_RGB', 'NO')
gdal.SetConfigOption('GDAL_PAM_ENABLED', 'NO')
@@ -6870,23 +5669,19 @@ def tiff_write_147():
gdal.SetConfigOption('GDAL_JPEG_TO_RGB', None)
gdal.SetConfigOption('GDAL_PAM_ENABLED', None)
out_ds = gdal.Open('/vsimem/tiff_write_147.tif')
- if out_ds.GetRasterBand(1).GetOverview(0) is not None:
- gdaltest.post_reason('did not expected overview')
- return 'fail'
+ assert out_ds.GetRasterBand(1).GetOverview(0) is None, 'did not expected overview'
out_ds = None
gdal.GetDriverByName('GTiff').Delete('/vsimem/tiff_write_147.tif')
- return 'success'
-
###############################################################################
# Test that we can use implicit JPEG-in-TIFF overviews with CMYK in raw mode
-def tiff_write_148():
+def test_tiff_write_148():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
gdal.SetConfigOption('GDAL_JPEG_TO_RGB', 'NO')
tmp_ds = gdal.Translate('', '../gdrivers/data/rgb_ntf_cmyk.jpg', format='MEM')
@@ -6904,20 +5699,15 @@ def tiff_write_148():
for i in range(4):
for j in range(4):
- if j >= 2 and abs(original_stats[i][j] - got_stats[i][j]) > 5:
- gdaltest.post_reason('did not get expected statistics')
- print(i, j)
- print(original_stats)
- print(got_stats)
- return 'fail'
-
- return 'success'
+ assert j < 2 or abs(original_stats[i][j] - got_stats[i][j]) <= 5, \
+ 'did not get expected statistics'
+
###############################################################################
# Test filling missing blocks with nodata
-def tiff_write_149():
+def test_tiff_write_149():
# Power-of-two bit depth
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_149.tif', 1, 1)
@@ -6926,10 +5716,7 @@ def tiff_write_149():
ds = gdal.Open('/vsimem/tiff_write_149.tif')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 1:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 1
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_149.tif')
# Test implicit blocks
@@ -6941,10 +5728,7 @@ def tiff_write_149():
ds = gdal.Open('/vsimem/tiff_write_149.tif')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != expected_cs:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == expected_cs
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_149.tif')
# NBITS=12, SEPARATE. Checksum must be the same as in the implicit blocks case
@@ -6955,10 +5739,7 @@ def tiff_write_149():
ds = gdal.Open('/vsimem/tiff_write_149.tif')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != expected_cs:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == expected_cs
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_149.tif')
# NBITS=12, CONTIG. Checksum must be the same as in the implicit blocks case
@@ -6969,19 +5750,14 @@ def tiff_write_149():
ds = gdal.Open('/vsimem/tiff_write_149.tif')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != expected_cs:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == expected_cs
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_149.tif')
- return 'success'
-
###############################################################################
# Test failure when loading block from disk in IWriteBlock()
-def tiff_write_150():
+def test_tiff_write_150():
shutil.copy('data/tiled_bad_offset.tif', 'tmp/tiled_bad_offset.tif')
ds = gdal.Open('tmp/tiled_bad_offset.tif', gdal.GA_Update)
@@ -6989,19 +5765,15 @@ def tiff_write_150():
gdal.ErrorReset()
with gdaltest.error_handler():
ds.FlushCache()
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() != ''
ds = None
gdaltest.tiff_drv.Delete('tmp/tiled_bad_offset.tif')
- return 'success'
-
###############################################################################
# Test IWriteBlock() with more than 10 bands
-def tiff_write_151():
+def test_tiff_write_151():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_151.tif', 1, 1, 11)
ds = None
@@ -7014,54 +5786,38 @@ def tiff_write_151():
ds.GetRasterBand(3).Fill(1)
ds = None
ds = gdal.Open('/vsimem/tiff_write_151.tif')
- if ds.GetRasterBand(1).Checksum() != 1:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(2).Checksum() != 1:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(3).Checksum() != 1:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 1
+ assert ds.GetRasterBand(2).Checksum() == 1
+ assert ds.GetRasterBand(3).Checksum() == 1
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_151.tif')
- return 'success'
-
###############################################################################
# Test flushing of blocks in a contig multi band file with Create()
-def tiff_write_152():
+def test_tiff_write_152():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_152.tif', 1, 1, 2, options=['NBITS=2'])
ds.GetRasterBand(2).SetNoDataValue(3)
ds.GetRasterBand(2).Fill(1)
ds = None
ds = gdal.Open('/vsimem/tiff_write_152.tif')
- if ds.GetRasterBand(1).Checksum() != 0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).Checksum())
- return 'fail'
- if ds.GetRasterBand(2).Checksum() != 1:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).Checksum())
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 0
+ assert ds.GetRasterBand(2).Checksum() == 1
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_152.tif')
- return 'success'
-
###############################################################################
# Test that empty blocks are created in a filesystem sparse way
-def tiff_write_153():
+def test_tiff_write_153():
target_dir = 'tmp'
if gdal.VSISupportsSparseFiles(target_dir) == 0:
- return 'skip'
+ pytest.skip()
gdaltest.tiff_drv.Create(target_dir + '/tiff_write_153.tif', 500, 500)
@@ -7071,18 +5827,13 @@ def tiff_write_153():
gdaltest.tiff_drv.Delete(target_dir + '/tiff_write_153.tif')
- if ret == gdal.VSI_RANGE_STATUS_DATA:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
-
- return 'success'
+ assert ret != gdal.VSI_RANGE_STATUS_DATA
###############################################################################
# Test empty block writing skipping and SPARSE_OK in CreateCopy() and Open()
-def tiff_write_154():
+def test_tiff_write_154():
import struct
@@ -7091,75 +5842,48 @@ def tiff_write_154():
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_154.tif', src_ds, options=['BLOCKYSIZE=256'])
ds.FlushCache()
# At that point empty blocks have not yet been flushed
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 162:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 162
ds = None
# Now they are and that's done in a filesystem sparse way. TODO: check this
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 256162:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 256162
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_154.tif')
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_154.tif', src_ds, options=['BLOCKYSIZE=256', 'COMPRESS=DEFLATE'])
ds.FlushCache()
# With compression, empty blocks are written right away
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 462:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
- ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 462:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 462
+ ds = None
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 462
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_154.tif')
# SPARSE_OK in CreateCopy(): blocks are not written
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_154.tif', src_ds, options=['SPARSE_OK=YES', 'BLOCKYSIZE=256'])
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 162:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 162
# SPARSE_OK in Open()/update: blocks are not written
ds = gdal.OpenEx('/vsimem/tiff_write_154.tif', gdal.OF_UPDATE, open_options=['SPARSE_OK=YES'])
ds.GetRasterBand(1).Fill(0)
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 162:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 162
ds = None
# Default behaviour in Open()/update: blocks are written
ds = gdal.OpenEx('/vsimem/tiff_write_154.tif', gdal.OF_UPDATE)
ds.GetRasterBand(1).Fill(0)
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 250162:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 250162
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_154.tif')
# SPARSE_OK in CreateCopy() in compressed case (strips): blocks are not written
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_154.tif', src_ds, options=['SPARSE_OK=YES', 'BLOCKYSIZE=256', 'COMPRESS=DEFLATE'])
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 174:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 174
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_154.tif')
# SPARSE_OK in CreateCopy() in compressed case (tiling): blocks are not written
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_154.tif', src_ds, options=['SPARSE_OK=YES', 'TILED=YES'])
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 190:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 190
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_154.tif')
# Test detection of 0 blocks for all data types
@@ -7174,11 +5898,7 @@ def tiff_write_154():
src_ds = gdal.GetDriverByName('MEM').Create('', 500, 500, 1, dt)
options = ['SPARSE_OK=YES', 'BLOCKYSIZE=256']
gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_154.tif', src_ds, options=options)
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 162:
- gdaltest.post_reason('fail')
- print(dt)
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 162, dt
# Test detection of nodata blocks with nodata != 0 for all data types
for dt in ['signedbyte', gdal.GDT_Int16, gdal.GDT_UInt16,
@@ -7195,21 +5915,14 @@ def tiff_write_154():
src_ds.GetRasterBand(1).SetNoDataValue(1)
ds = gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_154.tif', src_ds, options=options)
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 174:
- gdaltest.post_reason('fail')
- print(dt)
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 174, dt
# Test optimized detection when nodata==0, and with the last pixel != 0
src_ds = gdal.GetDriverByName('MEM').Create('', 100, 1, 1)
src_ds.GetRasterBand(1).Fill(0)
src_ds.GetRasterBand(1).WriteRaster(99, 0, 1, 1, struct.pack('B' * 1, 1))
gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_154.tif', src_ds, options=['SPARSE_OK=YES'])
- if gdal.VSIStatL('/vsimem/tiff_write_154.tif').size != 246:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsimem/tiff_write_154.tif').size)
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_154.tif').size == 246
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_154.tif')
@@ -7221,30 +5934,22 @@ def tiff_write_154():
offset = ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_0', 'TIFF')
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_154.tif')
- if offset is None or int(offset) == 0:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert not (offset is None or int(offset) == 0)
###############################################################################
# Test reading and writing band description
-def tiff_write_155():
+def test_tiff_write_155():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_155.tif', 1, 1)
ds.GetRasterBand(1).SetDescription('foo')
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_155.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_155.tif.aux.xml') is None
ds = gdal.Open('/vsimem/tiff_write_155.tif')
- if ds.GetRasterBand(1).GetDescription() != 'foo':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetDescription() == 'foo'
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_155.tif')
@@ -7252,48 +5957,30 @@ def tiff_write_155():
ds.GetRasterBand(1).SetDescription('foo')
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_155.tif.aux.xml') is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_155.tif.aux.xml') is not None
ds = gdal.Open('/vsimem/tiff_write_155.tif')
- if ds.GetRasterBand(1).GetDescription() != 'foo':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetDescription() == 'foo'
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_155.tif')
- return 'success'
-
###############################################################################
# Test GetDataCoverageStatus()
-def tiff_write_156():
+def test_tiff_write_156():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_156.tif', 64, 64, options=['SPARSE_OK=YES', 'TILED=YES', 'BLOCKXSIZE=32', 'BLOCKYSIZE=32'])
ds.GetRasterBand(1).WriteRaster(0, 0, 1, 1, 'X')
(flags, pct) = ds.GetRasterBand(1).GetDataCoverageStatus(0, 0, 32, 32)
- if flags != gdal.GDAL_DATA_COVERAGE_STATUS_DATA or pct != 100.0:
- gdaltest.post_reason('failure')
- print(flags)
- print(pct)
- return 'fail'
+ assert flags == gdal.GDAL_DATA_COVERAGE_STATUS_DATA and pct == 100.0
(flags, pct) = ds.GetRasterBand(1).GetDataCoverageStatus(32, 0, 32, 32)
- if flags != gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY or pct != 0.0:
- gdaltest.post_reason('failure')
- print(flags)
- print(pct)
- return 'fail'
+ assert flags == gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY and pct == 0.0
(flags, pct) = ds.GetRasterBand(1).GetDataCoverageStatus(16, 16, 32, 32)
- if flags != gdal.GDAL_DATA_COVERAGE_STATUS_DATA | gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY or pct != 25.0:
- gdaltest.post_reason('failure')
- print(flags)
- print(pct)
- return 'fail'
+ assert flags == gdal.GDAL_DATA_COVERAGE_STATUS_DATA | gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY and pct == 25.0
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_156.tif')
@@ -7304,20 +5991,15 @@ def tiff_write_156():
ds = None
ds = gdal.Open('/vsimem/tiff_write_156.tif')
flags, _ = ds.GetRasterBand(1).GetDataCoverageStatus(0, 100, 1, 1)
- if flags != gdal.GDAL_DATA_COVERAGE_STATUS_DATA:
- gdaltest.post_reason('failure')
- print(flags)
- return 'fail'
+ assert flags == gdal.GDAL_DATA_COVERAGE_STATUS_DATA
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_156.tif')
- return 'success'
-
###############################################################################
# Test Float16
-def tiff_write_157():
+def test_tiff_write_157():
import struct
@@ -7352,24 +6034,16 @@ def tiff_write_157():
# Check that we properly deserialize Float16 values
ds = gdal.Open('/vsimem/tiff_write_157.tif')
- if ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '16':
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '16'
got = struct.unpack('f' * 14, ds.ReadRaster())
expected = [0.0, -0.0, gdaltest.posinf(), -gdaltest.posinf(), gdaltest.NaN(), gdaltest.NaN(), 1.25, -1.25, 5.9604644775390625e-08, -5.9604644775390625e-08, 6.0975551605224609e-05, -6.0975551605224609e-05, 6.103515625e-05, -6.103515625e-05]
for i in range(14):
if i == 4 or i == 5:
- if got[i] == got[i]:
- gdaltest.post_reason('failure')
- print(i)
- print(got[i])
- return 'fail'
+ assert got[i] != got[i]
elif abs(got[i] - expected[i]) > 1e-15:
- gdaltest.post_reason('failure')
- print(i)
print(got[i])
print(expected[i])
- return 'fail'
+ pytest.fail(i)
# Check that we properly decode&re-encode Float16 values
gdal.Translate('/vsimem/tiff_write_157_dst.tif', ds)
@@ -7385,10 +6059,8 @@ def tiff_write_157():
gdal.VSIFCloseL(f)
if vals != vals_copied:
- gdaltest.post_reason('failure')
print(struct.unpack('H' * 14, vals))
- print(struct.unpack('H' * 14, vals_copied))
- return 'fail'
+ pytest.fail(struct.unpack('H' * 14, vals_copied))
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_157.tif')
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_157_dst.tif')
@@ -7428,17 +6100,11 @@ def tiff_write_157():
1.25, -1.25, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 5.9604644775390625e-08, gdaltest.posinf())
for i in range(18):
if i == 4 or i == 5:
- if got[i] == got[i]:
- gdaltest.post_reason('failure')
- print(i)
- print(got[i])
- return 'fail'
+ assert got[i] != got[i]
elif abs(got[i] - expected[i]) > 1e-15:
- gdaltest.post_reason('failure')
- print(i)
print(got[i])
print(expected[i])
- return 'fail'
+ pytest.fail(i)
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_157.tif')
@@ -7446,72 +6112,48 @@ def tiff_write_157():
gdal.Translate('/vsimem/tiff_write_157.tif', '../gdrivers/data/small_world.tif', options='-co NBITS=16 -ot Float32')
ds = gdal.Open('/vsimem/tiff_write_157.tif')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 30111:
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 30111
cs = ds.GetRasterBand(2).Checksum()
- if cs != 32302:
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 32302
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_157.tif')
- return 'success'
-
###############################################################################
# Test GetActualBlockSize() (perhaps not the best place for that...)
-def tiff_write_158():
+def test_tiff_write_158():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_158.tif', 20, 40, 1, options=['TILED=YES', 'BLOCKXSIZE=16', 'BLOCKYSIZE=32'])
(w, h) = ds.GetRasterBand(1).GetActualBlockSize(0, 0)
- if (w, h) != (16, 32):
- gdaltest.post_reason('failure')
- print(w, h)
- return 'fail'
+ assert (w, h) == (16, 32)
(w, h) = ds.GetRasterBand(1).GetActualBlockSize(1, 1)
- if (w, h) != (4, 8):
- gdaltest.post_reason('failure')
- print(w, h)
- return 'fail'
+ assert (w, h) == (4, 8)
res = ds.GetRasterBand(1).GetActualBlockSize(2, 0)
- if res is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert res is None
res = ds.GetRasterBand(1).GetActualBlockSize(0, 2)
- if res is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert res is None
res = ds.GetRasterBand(1).GetActualBlockSize(-1, 0)
- if res is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert res is None
res = ds.GetRasterBand(1).GetActualBlockSize(0, -1)
- if res is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert res is None
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_158.tif')
- return 'success'
-
###############################################################################
# Test that COPY_SRC_OVERVIEWS creation option with JPEG compression
# result in a https://trac.osgeo.org/gdal/wiki/CloudOptimizedGeoTIFF
-def tiff_write_159():
+def test_tiff_write_159():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('JPEG') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('BIGTIFF') == -1:
- return 'skip'
+ pytest.skip()
prev_table = ''
for options in [[], ['JPEG_QUALITY=50'], ['PHOTOMETRIC=YCBCR']]:
@@ -7527,36 +6169,21 @@ def tiff_write_159():
cs0 = ds.GetRasterBand(1).Checksum()
cs1 = ds.GetRasterBand(1).GetOverview(0).Checksum()
cs2 = ds.GetRasterBand(1).GetOverview(1).Checksum()
- if cs0 == 0 or cs1 == 0 or cs2 == 0:
- gdaltest.post_reason('failure')
- print(options)
- print(cs0)
- print(cs1)
- print(cs2)
- return 'fail'
+ assert not (cs0 == 0 or cs1 == 0 or cs2 == 0), options
ifd_main = int(ds.GetRasterBand(1).GetMetadataItem('IFD_OFFSET', 'TIFF'))
ifd_ovr_0 = int(ds.GetRasterBand(1).GetOverview(0).GetMetadataItem('IFD_OFFSET', 'TIFF'))
ifd_ovr_1 = int(ds.GetRasterBand(1).GetOverview(1).GetMetadataItem('IFD_OFFSET', 'TIFF'))
data_ovr_1 = int(ds.GetRasterBand(1).GetOverview(1).GetMetadataItem('BLOCK_OFFSET_0_0', 'TIFF'))
data_ovr_0 = int(ds.GetRasterBand(1).GetOverview(0).GetMetadataItem('BLOCK_OFFSET_0_0', 'TIFF'))
data_main = int(ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_0', 'TIFF'))
- if not(ifd_main < ifd_ovr_0 and ifd_ovr_0 < ifd_ovr_1 and ifd_ovr_1 < data_ovr_1 and data_ovr_1 < data_ovr_0 and data_ovr_0 < data_main):
- gdaltest.post_reason('failure')
- print(options)
- print(ifd_main, ifd_ovr_0, ifd_ovr_1, data_ovr_1, data_ovr_0, data_main)
- return 'fail'
+ assert (ifd_main < ifd_ovr_0 and ifd_ovr_0 < ifd_ovr_1 and ifd_ovr_1 < data_ovr_1 and data_ovr_1 < data_ovr_0 and data_ovr_0 < data_main), \
+ options
table_main = ds.GetRasterBand(1).GetMetadataItem('JPEGTABLES', 'TIFF')
table_ovr_0 = ds.GetRasterBand(1).GetOverview(0).GetMetadataItem('JPEGTABLES', 'TIFF')
table_ovr_1 = ds.GetRasterBand(1).GetOverview(1).GetMetadataItem('JPEGTABLES', 'TIFF')
- if table_main != table_ovr_0 or table_ovr_0 != table_ovr_1:
- gdaltest.post_reason('failure')
- print(options)
- return 'fail'
+ assert table_main == table_ovr_0 and table_ovr_0 == table_ovr_1, options
# Check that the JPEG tables are different in the 3 modes
- if table_main == prev_table:
- gdaltest.post_reason('failure')
- print(options)
- return 'fail'
+ assert table_main != prev_table, options
prev_table = table_main
ds = None
@@ -7574,23 +6201,17 @@ def tiff_write_159():
ds = gdal.Open('/vsimem/tiff_write_159.tif')
cs0 = ds.GetRasterBand(1).Checksum()
cs1 = ds.GetRasterBand(1).GetOverview(0).Checksum()
- if cs0 != 4743 or cs1 != 1133:
- gdaltest.post_reason('failure')
- print(value)
- print(cs0)
- print(cs1)
- return 'fail'
+ assert cs0 == 4743 and cs1 == 1133, value
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_159.tif')
- return 'success'
-
+
###############################################################################
# Test the Create() interface with a BLOCKYSIZE > image height
-def tiff_write_160():
+def test_tiff_write_160():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_160.tif', 10, 10, options=['BLOCKYSIZE=11'])
ds.GetRasterBand(1).Fill(255)
@@ -7598,21 +6219,16 @@ def tiff_write_160():
ds = gdal.Open('/vsimem/tiff_write_160.tif')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 1218:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 1218
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_160.tif')
- return 'success'
-
###############################################################################
# Test setting GCPs on an image with already a geotransform and vice-versa (#6751)
-def tiff_write_161():
+def test_tiff_write_161():
ds = gdaltest.tiff_drv.Create('/vsimem/tiff_write_161.tif', 1, 1)
ds.SetGeoTransform([0, 1, 2, 3, 4, 5])
@@ -7621,51 +6237,31 @@ def tiff_write_161():
ds = gdal.Open('/vsimem/tiff_write_161.tif', gdal.GA_Update)
src_ds = gdal.Open('data/gcps.vrt')
with gdaltest.error_handler():
- if ds.SetGCPs(src_ds.GetGCPs(), '') != 0:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGeoTransform(can_return_null=True) is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.SetGCPs(src_ds.GetGCPs(), '') == 0
+ assert ds.GetGeoTransform(can_return_null=True) is None
ds = None
ds = gdal.Open('/vsimem/tiff_write_161.tif', gdal.GA_Update)
- if not ds.GetGCPs():
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGeoTransform(can_return_null=True) is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetGCPs()
+ assert ds.GetGeoTransform(can_return_null=True) is None
with gdaltest.error_handler():
- if ds.SetGeoTransform([0, 1, 2, 3, 4, 5]) != 0:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGeoTransform() != (0.0, 1.0, 2.0, 3.0, 4.0, 5.0):
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGCPs():
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.SetGeoTransform([0, 1, 2, 3, 4, 5]) == 0
+ assert ds.GetGeoTransform() == (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
+ assert not ds.GetGCPs()
ds = None
ds = gdal.Open('/vsimem/tiff_write_161.tif', gdal.GA_Update)
- if ds.GetGCPs():
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetGeoTransform() != (0.0, 1.0, 2.0, 3.0, 4.0, 5.0):
- gdaltest.post_reason('fail')
- return 'fail'
+ assert not ds.GetGCPs()
+ assert ds.GetGeoTransform() == (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_161.tif')
- return 'success'
-
###############################################################################
# Test creating a JPEG compressed file with big tiles (#6757)
-def tiff_write_162():
+def test_tiff_write_162():
src_ds = gdal.GetDriverByName('MEM').Create('', 512, 512, 3)
@@ -7674,49 +6270,37 @@ def tiff_write_162():
gdaltest.tiff_drv.CreateCopy('/vsimem/tiff_write_162.tif', src_ds,
options=options)
- if gdal.GetLastErrorMsg() != '':
- return 'fail'
+ assert gdal.GetLastErrorMsg() == ''
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_162.tif')
- return 'success'
-
###############################################################################
# Test creating a file that would trigger strip chopping (#6924)
-def tiff_write_163():
+def test_tiff_write_163():
# Was a libtiff 4.0.8 regression
if gdaltest.tiff_drv.GetMetadataItem('LIBTIFF').find('4.0.8') >= 0:
- print('Test broken with libtiff 4.0.8')
- return 'skip'
+ pytest.skip('Test broken with libtiff 4.0.8')
gdal.Translate('/vsimem/tiff_write_163.tif', 'data/byte.tif',
options='-outsize 1 20000 -co BLOCKYSIZE=20000 -co PROFILE=BASELINE')
ds = gdal.Open('/vsimem/tiff_write_163.tif')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 47567:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 47567
# Check that IsBlockAvailable() works properly in that mode
offset_0_2 = ds.GetRasterBand(1).GetMetadataItem('BLOCK_OFFSET_0_2', 'TIFF')
- if offset_0_2 != str(146 + 2 * 8192):
- gdaltest.post_reason('fail')
- print(offset_0_2)
- return 'fail'
+ assert offset_0_2 == str(146 + 2 * 8192)
ds = None
gdaltest.tiff_drv.Delete('/vsimem/tiff_write_163.tif')
- return 'success'
-
###############################################################################
# Test that we handle [0,1,0,0,0,1] geotransform as a regular geotransform
-def tiff_write_164():
+def test_tiff_write_164():
ds = gdaltest.tiff_drv.Create('/vsimem/test.tif', 1, 1)
ds.SetGeoTransform([0, 1, 0, 0, 0, 1])
@@ -7726,10 +6310,7 @@ def tiff_write_164():
gt = ds.GetGeoTransform(can_return_null=True)
ds = None
- if gt != (0, 1, 0, 0, 0, 1):
- gdaltest.post_reason('fail')
- print(gt)
- return 'fail'
+ assert gt == (0, 1, 0, 0, 0, 1)
# Test [0,1,0,0,0,-1] as well
ds = gdaltest.tiff_drv.Create('/vsimem/test.tif', 1, 1)
@@ -7740,47 +6321,30 @@ def tiff_write_164():
gt = ds.GetGeoTransform(can_return_null=True)
ds = None
- if gt != (0, 1, 0, 0, 0, -1):
- gdaltest.post_reason('fail')
- print(gt)
- return 'fail'
+ assert gt == (0, 1, 0, 0, 0, -1)
gdal.Unlink('/vsimem/test.tif')
- return 'success'
-
###############################################################################
# Test the current behaviour of per-band nodata vs per-dataset serialization
-def tiff_write_165():
+def test_tiff_write_165():
ds = gdaltest.tiff_drv.Create('/vsimem/test.tif', 1, 1, 3)
ret = ds.GetRasterBand(1).SetNoDataValue(100)
- if ret != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret == 0
with gdaltest.error_handler():
ret = ds.GetRasterBand(2).SetNoDataValue(200)
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('warning expected, but not emitted')
- return 'fail'
- if ret != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() != '', 'warning expected, but not emitted'
+ assert ret == 0
nd = ds.GetRasterBand(1).GetNoDataValue()
- if nd != 100:
- gdaltest.post_reason('fail')
- print(nd)
- return 'fail'
+ assert nd == 100
nd = ds.GetRasterBand(2).GetNoDataValue()
- if nd != 200:
- gdaltest.post_reason('fail')
- print(nd)
- return 'fail'
+ assert nd == 200
ds = None
@@ -7788,69 +6352,42 @@ def tiff_write_165():
nd = ds.GetRasterBand(1).GetNoDataValue()
ds = None
- if nd != 200:
- gdaltest.post_reason('fail')
- print(nd)
- return 'fail'
+ assert nd == 200
gdal.Unlink('/vsimem/test.tif')
- return 'success'
-
###############################################################################
# Test reading & writing Z dimension for ModelTiepointTag and ModelPixelScaleTag (#7093)
-def tiff_write_166():
+def test_tiff_write_166():
ds = gdal.Open('data/tiff_vertcs_scale_offset.tif')
- if ds.GetRasterBand(1).GetScale() != 2.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetScale())
- return 'fail'
+ assert ds.GetRasterBand(1).GetScale() == 2.0
- if ds.GetRasterBand(1).GetOffset() != 10.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetOffset())
- return 'fail'
+ assert ds.GetRasterBand(1).GetOffset() == 10.0
# Scale + offset through CreateCopy()
gdal.Translate('/vsimem/tiff_write_166.tif', 'data/byte.tif',
options='-a_srs EPSG:26711+5773 -a_scale 2.0 -a_offset 10 -co PROFILE=GEOTIFF')
- if gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is None
ds = gdal.Open('/vsimem/tiff_write_166.tif')
- if ds.GetRasterBand(1).GetScale() != 2.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetScale())
- return 'fail'
+ assert ds.GetRasterBand(1).GetScale() == 2.0
- if ds.GetRasterBand(1).GetOffset() != 10.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetOffset())
- return 'fail'
+ assert ds.GetRasterBand(1).GetOffset() == 10.0
ds = None
gdal.Unlink('/vsimem/tiff_write_166.tif')
# Offset only through CreateCopy()
gdal.Translate('/vsimem/tiff_write_166.tif', 'data/byte.tif',
options='-a_srs EPSG:26711+5773 -a_offset 10 -co PROFILE=GEOTIFF')
- if gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is None
ds = gdal.Open('/vsimem/tiff_write_166.tif')
- if ds.GetRasterBand(1).GetScale() != 1.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetScale())
- return 'fail'
+ assert ds.GetRasterBand(1).GetScale() == 1.0
- if ds.GetRasterBand(1).GetOffset() != 10.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetOffset())
- return 'fail'
+ assert ds.GetRasterBand(1).GetOffset() == 10.0
ds = None
gdal.Unlink('/vsimem/tiff_write_166.tif')
@@ -7863,19 +6400,11 @@ def tiff_write_166():
ds.GetRasterBand(1).SetScale(2)
ds.GetRasterBand(1).SetOffset(10)
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is None
ds = gdal.Open('/vsimem/tiff_write_166.tif')
- if ds.GetRasterBand(1).GetScale() != 2.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetScale())
- return 'fail'
- if ds.GetRasterBand(1).GetOffset() != 10.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetOffset())
- return 'fail'
+ assert ds.GetRasterBand(1).GetScale() == 2.0
+ assert ds.GetRasterBand(1).GetOffset() == 10.0
ds = None
gdal.Unlink('/vsimem/tiff_write_166.tif')
@@ -7887,19 +6416,11 @@ def tiff_write_166():
ds.SetGeoTransform([440720, 60, 0, 3751320, 0, -60])
ds.GetRasterBand(1).SetScale(2)
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is None
ds = gdal.Open('/vsimem/tiff_write_166.tif')
- if ds.GetRasterBand(1).GetScale() != 2.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetScale())
- return 'fail'
- if ds.GetRasterBand(1).GetOffset() != 0.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetOffset())
- return 'fail'
+ assert ds.GetRasterBand(1).GetScale() == 2.0
+ assert ds.GetRasterBand(1).GetOffset() == 0.0
ds = None
gdal.Unlink('/vsimem/tiff_write_166.tif')
@@ -7911,28 +6432,18 @@ def tiff_write_166():
ds.SetGeoTransform([440720, 60, 0, 3751320, 0, -60])
ds.GetRasterBand(1).SetOffset(10)
ds = None
- if gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.VSIStatL('/vsimem/tiff_write_166.tif.aux.xml') is None
ds = gdal.Open('/vsimem/tiff_write_166.tif')
- if ds.GetRasterBand(1).GetScale() != 1.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetScale())
- return 'fail'
- if ds.GetRasterBand(1).GetOffset() != 10.0:
- gdaltest.post_reason('fail')
- print(ds.GetRasterBand(1).GetOffset())
- return 'fail'
+ assert ds.GetRasterBand(1).GetScale() == 1.0
+ assert ds.GetRasterBand(1).GetOffset() == 10.0
ds = None
gdal.Unlink('/vsimem/tiff_write_166.tif')
- return 'success'
-
###############################################################################
-def tiff_write_167_deflate_zlevel():
+def test_tiff_write_167_deflate_zlevel():
src_ds = gdal.Open('data/byte.tif')
gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/out.tif', src_ds,
@@ -7947,10 +6458,7 @@ def tiff_write_167_deflate_zlevel():
size2 = gdal.VSIStatL('/vsimem/out.tif').size
gdal.Unlink('/vsimem/out.tif')
- if size2 >= size1:
- gdaltest.post_reason('fail')
- print(size1, size2)
- return 'fail'
+ assert size2 < size1
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/out.tif', 20, 20, 1,
options=['COMPRESS=DEFLATE',
@@ -7963,18 +6471,13 @@ def tiff_write_167_deflate_zlevel():
size2_create = gdal.VSIStatL('/vsimem/out.tif').size
gdal.Unlink('/vsimem/out.tif')
- if size2 != size2_create:
- gdaltest.post_reason('fail')
- print(size2, size2_create)
- return 'fail'
-
- return 'success'
+ assert size2 == size2_create
###############################################################################
# Test CCITTFAX3
-def tiff_write_168_ccitfax3():
+def test_tiff_write_168_ccitfax3():
ut = gdaltest.GDALTest('GTiff', 'oddsize1bit.tif', 1, 5918,
options=['NBITS=1', 'COMPRESS=CCITTFAX3'])
@@ -7984,7 +6487,7 @@ def tiff_write_168_ccitfax3():
# Test CCITTRLE
-def tiff_write_169_ccitrle():
+def test_tiff_write_169_ccitrle():
ut = gdaltest.GDALTest('GTiff', 'oddsize1bit.tif', 1, 5918,
options=['NBITS=1', 'COMPRESS=CCITTRLE'])
@@ -7994,26 +6497,24 @@ def tiff_write_169_ccitrle():
# Test invalid compression method
-def tiff_write_170_invalid_compresion():
+def test_tiff_write_170_invalid_compresion():
src_ds = gdal.Open('data/byte.tif')
with gdaltest.error_handler():
gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/out.tif', src_ds,
options=['COMPRESS=INVALID'])
- if gdal.GetLastErrorMsg() == '':
- return 'fail'
+ assert gdal.GetLastErrorMsg() != ''
gdal.Unlink('/vsimem/out.tif')
- return 'success'
###############################################################################
# Test ZSTD compression
-def tiff_write_171_zstd():
+def test_tiff_write_171_zstd():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('ZSTD') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672,
options=['COMPRESS=ZSTD', 'ZSTD_LEVEL=1'])
@@ -8023,11 +6524,11 @@ def tiff_write_171_zstd():
# Test ZSTD compression with PREDICTOR = 2
-def tiff_write_171_zstd_predictor():
+def test_tiff_write_171_zstd_predictor():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('ZSTD') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672,
options=['COMPRESS=ZSTD', 'ZSTD_LEVEL=1', 'PREDICTOR=2'])
@@ -8037,11 +6538,11 @@ def tiff_write_171_zstd_predictor():
# Test WEBP compression
-def tiff_write_webp():
+def test_tiff_write_webp():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('WEBP') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'md_ge_rgb_0010000.tif', 0, None,
options=['COMPRESS=WEBP'])
@@ -8051,14 +6552,14 @@ def tiff_write_webp():
# Test WEBP compression with internal tiling
-def tiff_write_tiled_webp():
+def test_tiff_write_tiled_webp():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('WEBP') == -1:
- return 'skip'
+ pytest.skip()
if md['DMD_CREATIONOPTIONLIST'].find('WEBP_LOSSLESS') == -1:
- return 'skip'
+ pytest.skip()
filename = '/vsimem/tiff_write_tiled_webp.tif'
src_ds = gdal.Open('data/md_ge_rgb_0010000.tif')
@@ -8068,25 +6569,20 @@ def tiff_write_tiled_webp():
'TILED=true'])
ds = gdal.Open(filename)
cs = [ds.GetRasterBand(i+1).Checksum() for i in range(3)]
- if cs != [21212, 21053, 21349]:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == [21212, 21053, 21349]
gdaltest.tiff_drv.Delete(filename)
gdal.Unlink('data/md_ge_rgb_0010000.tif.aux.xml')
- return 'success'
-
###############################################################################
# Test WEBP compression with huge single strip
-def tiff_write_webp_huge_single_strip():
+def test_tiff_write_webp_huge_single_strip():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('WEBP') == -1:
- return 'skip'
+ pytest.skip()
filename = '/vsimem/tif_webp_huge_single_strip.tif'
src_ds = gdal.Open('data/tif_webp_huge_single_strip.tif')
@@ -8101,24 +6597,18 @@ def tiff_write_webp_huge_single_strip():
for i in range(3):
for j in range(4):
- if abs(original_stats[i][j] - got_stats[i][j]) > 1e-1 * abs(original_stats[i][j]):
- gdaltest.post_reason('did not get expected statistics')
- print(i, j)
- print(original_stats)
- print(got_stats)
- return 'fail'
+ assert abs(original_stats[i][j] - got_stats[i][j]) <= 1e-1 * abs(original_stats[i][j]), \
+ 'did not get expected statistics'
gdaltest.tiff_drv.Delete(filename)
gdal.Unlink('data/tif_webp_huge_single_strip.tif.aux.xml')
- return 'success'
-
###############################################################################
# GeoTIFF DGIWG tags
-def tiff_write_172_geometadata_tiff_rsid():
+def test_tiff_write_172_geometadata_tiff_rsid():
tmpfilename = '/vsimem/tiff_write_172_geometadata_tiff_rsid.tiff'
ds = gdal.GetDriverByName('GTiff').Create(tmpfilename, 1, 1)
@@ -8127,40 +6617,27 @@ def tiff_write_172_geometadata_tiff_rsid():
ds = None
ds = gdal.Open(tmpfilename, gdal.GA_Update)
- if ds.GetMetadataItem('GEO_METADATA') != 'foo':
- gdaltest.post_reason('fail')
- print(ds.GetMetadata())
- return 'fail'
- if ds.GetMetadataItem('TIFF_RSID') != 'bar':
- gdaltest.post_reason('fail')
- print(ds.GetMetadata())
- return 'fail'
+ assert ds.GetMetadataItem('GEO_METADATA') == 'foo', ds.GetMetadata()
+ assert ds.GetMetadataItem('TIFF_RSID') == 'bar', ds.GetMetadata()
ds.SetMetadata({})
ds = None
ds = gdal.Open(tmpfilename)
- if ds.GetMetadataItem('GEO_METADATA') is not None:
- gdaltest.post_reason('fail')
- print(ds.GetMetadata())
- return 'fail'
- if ds.GetMetadataItem('TIFF_RSID') is not None:
- gdaltest.post_reason('fail')
- print(ds.GetMetadata())
- return 'fail'
+ assert ds.GetMetadataItem('GEO_METADATA') is None, ds.GetMetadata()
+ assert ds.GetMetadataItem('TIFF_RSID') is None, ds.GetMetadata()
ds = None
gdal.Unlink(tmpfilename)
- return 'success'
###############################################################################
# Test LERC compression
-def tiff_write_173_lerc():
+def test_tiff_write_173_lerc():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672,
options=['COMPRESS=LERC'])
@@ -8170,11 +6647,11 @@ def tiff_write_173_lerc():
# Test LERC_DEFLATE compression
-def tiff_write_174_lerc_deflate():
+def test_tiff_write_174_lerc_deflate():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC_DEFLATE') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672,
options=['COMPRESS=LERC_DEFLATE'])
@@ -8184,11 +6661,11 @@ def tiff_write_174_lerc_deflate():
# Test LERC_DEFLATE compression
-def tiff_write_174_lerc_deflate_with_level():
+def test_tiff_write_174_lerc_deflate_with_level():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC_DEFLATE') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672,
options=['COMPRESS=LERC_DEFLATE', 'ZLEVEL=1'])
@@ -8198,11 +6675,11 @@ def tiff_write_174_lerc_deflate_with_level():
# Test LERC_ZSTD compression
-def tiff_write_175_lerc_zstd():
+def test_tiff_write_175_lerc_zstd():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC_ZSTD') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672,
options=['COMPRESS=LERC_ZSTD'])
@@ -8212,11 +6689,11 @@ def tiff_write_175_lerc_zstd():
# Test LERC_ZSTD compression
-def tiff_write_175_lerc_zstd_with_level():
+def test_tiff_write_175_lerc_zstd_with_level():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC_ZSTD') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4672,
options=['COMPRESS=LERC_ZSTD', 'ZSTD_LEVEL=1'])
@@ -8226,11 +6703,11 @@ def tiff_write_175_lerc_zstd_with_level():
# Test LERC compression with MAX_Z_ERROR
-def tiff_write_176_lerc_max_z_error():
+def test_tiff_write_176_lerc_max_z_error():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC') == -1:
- return 'skip'
+ pytest.skip()
ut = gdaltest.GDALTest('GTiff', 'byte.tif', 1, 4529,
options=['COMPRESS=LERC', 'MAX_Z_ERROR=1'])
@@ -8240,11 +6717,11 @@ def tiff_write_176_lerc_max_z_error():
# Test LERC compression with several bands and tiling
-def tiff_write_177_lerc_several_bands_tiling():
+def test_tiff_write_177_lerc_several_bands_tiling():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC') == -1:
- return 'skip'
+ pytest.skip()
filename = '/vsimem/tiff_write_177_lerc_several_bands_tiling.tif'
gdal.Translate(filename, '../gdrivers/data/small_world.tif',
@@ -8253,22 +6730,17 @@ def tiff_write_177_lerc_several_bands_tiling():
cs = [ds.GetRasterBand(i+1).Checksum() for i in range(3)]
ds = None
gdal.Unlink(filename)
- if cs != [30111, 32302, 40026]:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == [30111, 32302, 40026]
###############################################################################
# Test LERC compression with alpha band
-def tiff_write_178_lerc_with_alpha():
+def test_tiff_write_178_lerc_with_alpha():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC') == -1:
- return 'skip'
+ pytest.skip()
filename = '/vsimem/tiff_write_178_lerc_with_alpha.tif'
gdal.Translate(filename, 'data/stefan_full_rgba.tif',
@@ -8277,22 +6749,17 @@ def tiff_write_178_lerc_with_alpha():
cs = [ds.GetRasterBand(i+1).Checksum() for i in range(4)]
ds = None
gdal.Unlink(filename)
- if cs != [12603, 58561, 36064, 10807]:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == [12603, 58561, 36064, 10807]
###############################################################################
# Test LERC compression with alpha band with only 0 and 255
-def tiff_write_178_lerc_with_alpha_0_and_255():
+def test_tiff_write_178_lerc_with_alpha_0_and_255():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC') == -1:
- return 'skip'
+ pytest.skip()
filename = '/vsimem/tiff_write_178_lerc_with_alpha_0_and_255.tif'
gdal.Translate(filename, 'data/rgba_with_alpha_0_and_255.tif',
@@ -8301,22 +6768,17 @@ def tiff_write_178_lerc_with_alpha_0_and_255():
cs = [ds.GetRasterBand(i+1).Checksum() for i in range(4)]
ds = None
gdal.Unlink(filename)
- if cs != [13, 13, 13, 13]:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == [13, 13, 13, 13]
###############################################################################
# Test LERC compression with different data types
-def tiff_write_179_lerc_data_types():
+def test_tiff_write_179_lerc_data_types():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC') == -1:
- return 'skip'
+ pytest.skip()
filename = '/vsimem/tiff_write_179_lerc_data_types.tif'
for src_filename in ['uint16.tif', 'int16.tif', 'uint32.tif', 'int32.tif',
@@ -8327,10 +6789,7 @@ def tiff_write_179_lerc_data_types():
cs = ds.GetRasterBand(1).Checksum()
ds = None
gdal.Unlink(filename)
- if cs != 4672:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 4672
filename_tmp = filename + ".tmp.tif"
gdal.Translate(filename_tmp, 'data/byte.tif',
@@ -8341,30 +6800,23 @@ def tiff_write_179_lerc_data_types():
cs = ds.GetRasterBand(1).Checksum()
ds = None
gdal.Unlink(filename)
- if cs != 4672:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 4672
gdal.ErrorReset()
with gdaltest.error_handler():
gdal.Translate(filename, 'data/cfloat32.tif', creationOptions=['COMPRESS=LERC'])
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() != ''
gdal.Unlink(filename)
- return 'success'
-
###############################################################################
# Test LERC compression with several bands and separate
-def tiff_write_180_lerc_separate():
+def test_tiff_write_180_lerc_separate():
md = gdaltest.tiff_drv.GetMetadata()
if md['DMD_CREATIONOPTIONLIST'].find('LERC') == -1:
- return 'skip'
+ pytest.skip()
filename = '/vsimem/tiff_write_180_lerc_separate.tif'
gdal.Translate(filename, '../gdrivers/data/small_world.tif',
@@ -8373,18 +6825,13 @@ def tiff_write_180_lerc_separate():
cs = [ds.GetRasterBand(i+1).Checksum() for i in range(3)]
ds = None
gdal.Unlink(filename)
- if cs != [30111, 32302, 40026]:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == [30111, 32302, 40026]
###############################################################################
# Test set XMP metadata
-def tiff_write_181_xmp():
+def test_tiff_write_181_xmp():
src_ds = gdal.Open('data/utmsmall.tif')
@@ -8394,9 +6841,7 @@ def tiff_write_181_xmp():
xmp_ds = gdal.Open('../gdrivers/data/byte_with_xmp.tif')
xmp = xmp_ds.GetMetadata('xml:XMP')
xmp_ds = None
- if 'W5M0MpCehiHzreSzNTczkc9d' not in xmp[0]:
- gdaltest.post_reason('Wrong input file without XMP')
- return 'fail'
+ assert 'W5M0MpCehiHzreSzNTczkc9d' in xmp[0], 'Wrong input file without XMP'
new_ds.SetMetadata(xmp, 'xml:XMP')
new_ds = None
@@ -8405,42 +6850,34 @@ def tiff_write_181_xmp():
new_ds = gdal.Open('tmp/test_181.tif')
read_xmp = new_ds.GetMetadata('xml:XMP')
- if not read_xmp or 'W5M0MpCehiHzreSzNTczkc9d' not in read_xmp[0]:
- gdaltest.post_reason('No XMP data written in output file')
- return 'fail'
+ assert read_xmp and 'W5M0MpCehiHzreSzNTczkc9d' in read_xmp[0], \
+ 'No XMP data written in output file'
new_ds = None
gdaltest.tiff_drv.Delete('tmp/test_181.tif')
- return 'success'
-
###############################################################################
# Test delete XMP from a dataset
-def tiff_write_182_xmp_delete():
+def test_tiff_write_182_xmp_delete():
shutil.copyfile('../gdrivers/data/byte_with_xmp.tif', 'tmp/test_182.tif')
chg_ds = gdal.Open('tmp/test_182.tif', gdal.GA_Update)
read_xmp = chg_ds.GetMetadata('xml:XMP')
- if not read_xmp or 'W5M0MpCehiHzreSzNTczkc9d' not in read_xmp[0]:
- gdaltest.post_reason('No XMP data written in output file')
- return 'fail'
+ assert read_xmp and 'W5M0MpCehiHzreSzNTczkc9d' in read_xmp[0], \
+ 'No XMP data written in output file'
chg_ds.SetMetadata(None, 'xml:XMP')
chg_ds = None
again_ds = gdal.Open('tmp/test_182.tif')
read_xmp = again_ds.GetMetadata('xml:XMP')
- if read_xmp:
- gdaltest.post_reason('XMP data not removed')
- return 'fail'
+ assert not read_xmp, 'XMP data not removed'
again_ds = None
gdaltest.tiff_drv.Delete('tmp/test_182.tif')
- return 'success'
-
###############################################################################
# Ask to run again tests with GDAL_API_PROXY=YES
@@ -8448,237 +6885,15 @@ def tiff_write_182_xmp_delete():
def tiff_write_api_proxy():
if not run_tiff_write_api_proxy:
- return 'skip'
+ pytest.skip()
import test_py_scripts
ret = test_py_scripts.run_py_script_as_external_script('.', 'tiff_write', ' -api_proxy', display_live_on_parent_stdout=True)
- if ret.find('Failed: 0') == -1:
- return 'fail'
-
- return 'success'
+ assert ret.find('Failed: 0') != -1
###############################################################################
-def tiff_write_cleanup():
+def test_tiff_write_cleanup():
gdaltest.tiff_drv = None
-
- return 'success'
-
-
-gdaltest_list = [
- tiff_write_1,
- tiff_write_2,
- tiff_write_3,
- tiff_write_4,
- tiff_write_5,
- tiff_write_6,
- tiff_write_7,
- tiff_write_8,
- tiff_write_9,
- tiff_write_10,
- tiff_write_11,
- tiff_write_12,
- tiff_write_13,
- tiff_write_14,
- tiff_write_15,
- tiff_write_16,
- tiff_write_17,
- tiff_write_17_disable_readdir,
- tiff_write_18,
- tiff_write_18_disable_readdir,
- tiff_write_rpc_txt,
- tiff_write_rpc_in_pam,
- tiff_write_19,
- tiff_write_20,
- tiff_write_21,
- tiff_write_22,
- tiff_write_23,
- tiff_write_24,
- tiff_write_25,
- tiff_write_26,
- tiff_write_27,
- tiff_write_28,
- tiff_write_29,
- tiff_write_30,
- tiff_write_31,
- tiff_write_32,
- tiff_write_33,
- tiff_write_34,
- tiff_write_35,
- tiff_write_36,
- tiff_write_37,
- tiff_write_38,
- tiff_write_39,
- tiff_write_40,
- tiff_write_41,
- tiff_write_42,
- tiff_write_43,
- tiff_write_44,
- tiff_write_45,
- tiff_write_46,
- tiff_write_47,
- tiff_write_48,
- tiff_write_49,
- tiff_write_50,
- tiff_write_51,
- tiff_write_52,
- tiff_write_53,
- tiff_write_53_bis,
- tiff_write_54,
- tiff_write_55,
- tiff_write_56,
- tiff_write_57,
- tiff_write_58,
- tiff_write_59,
- tiff_write_60,
- tiff_write_61,
- tiff_write_62,
- tiff_write_63,
- tiff_write_64,
- tiff_write_65,
- tiff_write_66,
- tiff_write_67,
- tiff_write_68,
- tiff_write_69,
- tiff_write_70,
- tiff_write_71,
- tiff_write_72,
- tiff_write_73,
- tiff_write_74,
- tiff_write_75,
- tiff_write_76,
- tiff_write_77,
- tiff_write_78,
- tiff_write_79,
- tiff_write_80,
- tiff_write_81,
- tiff_write_82,
- tiff_write_83,
- tiff_write_84,
- tiff_write_85,
- tiff_write_86,
- tiff_write_87,
- tiff_write_88,
- tiff_write_89, # leaks mem
- tiff_write_90, # leaks mem
- tiff_write_91, # leaks mem
- tiff_write_92, # leaks mem
- tiff_write_93, # leaks mem
- tiff_write_94, # leaks mem
- tiff_write_95,
- tiff_write_96, # leaks mem
- tiff_write_97,
- tiff_write_98,
- tiff_write_99,
- tiff_write_100,
- tiff_write_101,
- tiff_write_102,
- tiff_write_103,
- tiff_write_104,
- tiff_write_105,
- tiff_write_106,
- tiff_write_107,
- tiff_write_108,
- tiff_write_109,
- tiff_write_110,
- tiff_write_111,
- tiff_write_111_bis,
- tiff_write_111_ter,
- tiff_write_112,
- tiff_write_113,
- tiff_write_114,
- tiff_write_115,
- tiff_write_116,
- tiff_write_117,
- tiff_write_118,
- tiff_write_119,
- tiff_write_120,
- tiff_write_121,
- tiff_write_122,
- tiff_write_123,
- tiff_write_124,
- tiff_write_125,
- tiff_write_126,
- tiff_write_127,
- tiff_write_128,
- tiff_write_129,
- tiff_write_130,
- tiff_write_131,
- tiff_write_131_level_9,
- tiff_write_132,
- tiff_write_133,
- tiff_write_134,
- tiff_write_135,
- tiff_write_136,
- tiff_write_137,
- tiff_write_138,
- tiff_write_139,
- tiff_write_140,
- tiff_write_141,
- tiff_write_142,
- tiff_write_143,
- tiff_write_144,
- tiff_write_145,
- tiff_write_146,
- tiff_write_147,
- tiff_write_148,
- tiff_write_149,
- tiff_write_150,
- tiff_write_151,
- tiff_write_152,
- tiff_write_153,
- tiff_write_154,
- tiff_write_155,
- tiff_write_156,
- tiff_write_157,
- tiff_write_158,
- tiff_write_159,
- tiff_write_160,
- tiff_write_161,
- tiff_write_162,
- tiff_write_163,
- tiff_write_164,
- tiff_write_165,
- tiff_write_166,
- tiff_write_167_deflate_zlevel,
- tiff_write_168_ccitfax3,
- tiff_write_169_ccitrle,
- tiff_write_170_invalid_compresion,
- tiff_write_171_zstd,
- tiff_write_171_zstd_predictor,
- tiff_write_172_geometadata_tiff_rsid,
- tiff_write_173_lerc,
- tiff_write_174_lerc_deflate,
- tiff_write_174_lerc_deflate_with_level,
- tiff_write_175_lerc_zstd,
- tiff_write_175_lerc_zstd_with_level,
- tiff_write_176_lerc_max_z_error,
- tiff_write_177_lerc_several_bands_tiling,
- tiff_write_178_lerc_with_alpha,
- tiff_write_178_lerc_with_alpha_0_and_255,
- tiff_write_179_lerc_data_types,
- tiff_write_180_lerc_separate,
- tiff_write_181_xmp,
- tiff_write_182_xmp_delete,
- # tiff_write_api_proxy,
- tiff_write_webp,
- tiff_write_tiled_webp,
- tiff_write_webp_huge_single_strip,
- tiff_write_cleanup]
-
-
-# gdaltest_list = [ tiff_write_1, tiff_write_176_lerc_max_z_error ]
-
-if __name__ == '__main__':
-
- if len(sys.argv) >= 2 and sys.argv[1] == '-api_proxy':
- run_tiff_write_api_proxy = False
- gdal.SetConfigOption('GDAL_API_PROXY', 'YES')
-
- gdaltest.setup_run('tiff_write')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/transformer.py b/autotest/gcore/transformer.py
index 80d6d289a991..a7c43e5af579 100755
--- a/autotest/gcore/transformer.py
+++ b/autotest/gcore/transformer.py
@@ -30,207 +30,130 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
-sys.path.append('../pymod')
import gdaltest
from osgeo import gdal
from osgeo import osr
+import pytest
###############################################################################
# Test simple Geotransform based transformer.
-def transformer_1():
+def test_transformer_1():
ds = gdal.Open('data/byte.tif')
tr = gdal.Transformer(ds, None, [])
(success, pnt) = tr.TransformPoint(0, 20, 10)
- if not success \
- or abs(pnt[0] - 441920) > 0.00000001 \
- or abs(pnt[1] - 3750720) > 0.00000001 \
- or pnt[2] != 0.0:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.')
- return 'fail'
+ assert success and abs(pnt[0] - 441920) <= 0.00000001 and abs(pnt[1] - 3750720) <= 0.00000001 and pnt[2] == 0.0, \
+ 'got wrong forward transform result.'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20) > 0.00000001 \
- or abs(pnt[1] - 10) > 0.00000001 \
- or pnt[2] != 0.0:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
-
- return 'success'
+ assert success and abs(pnt[0] - 20) <= 0.00000001 and abs(pnt[1] - 10) <= 0.00000001 and pnt[2] == 0.0, \
+ 'got wrong reverse transform result.'
###############################################################################
# Test GCP based transformer with polynomials.
-def transformer_2():
+def test_transformer_2():
ds = gdal.Open('data/gcps.vrt')
tr = gdal.Transformer(ds, None, ['METHOD=GCP_POLYNOMIAL'])
(success, pnt) = tr.TransformPoint(0, 20, 10)
- if not success \
- or abs(pnt[0] - 441920) > 0.001 \
- or abs(pnt[1] - 3750720) > 0.001 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.')
- return 'fail'
+ assert success and abs(pnt[0] - 441920) <= 0.001 and abs(pnt[1] - 3750720) <= 0.001 and pnt[2] == 0, \
+ 'got wrong forward transform result.'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20) > 0.001 \
- or abs(pnt[1] - 10) > 0.001 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
-
- return 'success'
+ assert success and abs(pnt[0] - 20) <= 0.001 and abs(pnt[1] - 10) <= 0.001 and pnt[2] == 0, \
+ 'got wrong reverse transform result.'
###############################################################################
# Test GCP based transformer with thin plate splines.
-def transformer_3():
+def test_transformer_3():
ds = gdal.Open('data/gcps.vrt')
tr = gdal.Transformer(ds, None, ['METHOD=GCP_TPS'])
(success, pnt) = tr.TransformPoint(0, 20, 10)
- if not success \
- or abs(pnt[0] - 441920) > 0.001 \
- or abs(pnt[1] - 3750720) > 0.001 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.')
- return 'fail'
+ assert success and abs(pnt[0] - 441920) <= 0.001 and abs(pnt[1] - 3750720) <= 0.001 and pnt[2] == 0, \
+ 'got wrong forward transform result.'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20) > 0.001 \
- or abs(pnt[1] - 10) > 0.001 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
-
- return 'success'
+ assert success and abs(pnt[0] - 20) <= 0.001 and abs(pnt[1] - 10) <= 0.001 and pnt[2] == 0, \
+ 'got wrong reverse transform result.'
###############################################################################
# Test geolocation based transformer.
-def transformer_4():
+def test_transformer_4():
ds = gdal.Open('data/sstgeo.vrt')
tr = gdal.Transformer(ds, None, ['METHOD=GEOLOC_ARRAY'])
(success, pnt) = tr.TransformPoint(0, 20, 10)
- if not success \
- or abs(pnt[0] + 81.961341857910156) > 0.000001 \
- or abs(pnt[1] - 29.612689971923828) > 0.000001 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.')
- return 'fail'
+ assert success and abs(pnt[0] + 81.961341857910156) <= 0.000001 and abs(pnt[1] - 29.612689971923828) <= 0.000001 and pnt[2] == 0, \
+ 'got wrong forward transform result.'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20.436627518907024) > 0.001 \
- or abs(pnt[1] - 10.484599774610549) > 0.001 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
-
- return 'success'
+ assert success and abs(pnt[0] - 20.436627518907024) <= 0.001 and abs(pnt[1] - 10.484599774610549) <= 0.001 and pnt[2] == 0, \
+ 'got wrong reverse transform result.'
###############################################################################
# Test RPC based transformer.
-def transformer_5():
+def test_transformer_5():
ds = gdal.Open('data/rpc.vrt')
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_PIXEL_ERROR_THRESHOLD=0.05'])
(success, pnt) = tr.TransformPoint(0, 20.5, 10.5)
- if not success \
- or abs(pnt[0] - 125.64830100509131) > 0.000001 \
- or abs(pnt[1] - 39.869433991997553) > 0.000001 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.')
- return 'fail'
+ assert success and abs(pnt[0] - 125.64830100509131) <= 0.000001 and abs(pnt[1] - 39.869433991997553) <= 0.000001 and pnt[2] == 0, \
+ 'got wrong forward transform result.'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20.5) > 0.05 \
- or abs(pnt[1] - 10.5) > 0.05 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
+ assert success and abs(pnt[0] - 20.5) <= 0.05 and abs(pnt[1] - 10.5) <= 0.05 and pnt[2] == 0, \
+ 'got wrong reverse transform result.'
# Try with a different height.
(success, pnt) = tr.TransformPoint(0, 20.5, 10.5, 30)
- if not success \
- or abs(pnt[0] - 125.64828521533849) > 0.000001 \
- or abs(pnt[1] - 39.869345204440144) > 0.000001 \
- or pnt[2] != 30:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.(2)')
- return 'fail'
+ assert success and abs(pnt[0] - 125.64828521533849) <= 0.000001 and abs(pnt[1] - 39.869345204440144) <= 0.000001 and pnt[2] == 30, \
+ 'got wrong forward transform result.(2)'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20.5) > 0.05 \
- or abs(pnt[1] - 10.5) > 0.05 \
- or pnt[2] != 30:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.(2)')
- return 'fail'
+ assert success and abs(pnt[0] - 20.5) <= 0.05 and abs(pnt[1] - 10.5) <= 0.05 and pnt[2] == 30, \
+ 'got wrong reverse transform result.(2)'
# Test RPC_HEIGHT option
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_HEIGHT=30'])
(success, pnt) = tr.TransformPoint(0, 20.5, 10.5)
- if not success \
- or abs(pnt[0] - 125.64828521533849) > 0.000001 \
- or abs(pnt[1] - 39.869345204440144) > 0.000001:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.(3)')
- return 'fail'
+ assert success and abs(pnt[0] - 125.64828521533849) <= 0.000001 and abs(pnt[1] - 39.869345204440144) <= 0.000001, \
+ 'got wrong forward transform result.(3)'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20.5) > 0.1 \
- or abs(pnt[1] - 10.5) > 0.1:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.(3)')
- return 'fail'
+ assert success and abs(pnt[0] - 20.5) <= 0.1 and abs(pnt[1] - 10.5) <= 0.1, \
+ 'got wrong reverse transform result.(3)'
# Test RPC_DEM and RPC_HEIGHT_SCALE options
@@ -247,21 +170,13 @@ def transformer_5():
(success, pnt) = tr.TransformPoint(0, 20.5, 10.5, 0)
- if not success \
- or abs(pnt[0] - 125.64828521533849) > 0.000001 \
- or abs(pnt[1] - 39.869345204440144) > 0.000001:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.(4)')
- return 'fail'
+ assert success and abs(pnt[0] - 125.64828521533849) <= 0.000001 and abs(pnt[1] - 39.869345204440144) <= 0.000001, \
+ 'got wrong forward transform result.(4)'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20.5) > 0.05 \
- or abs(pnt[1] - 10.5) > 0.05:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.(4)')
- return 'fail'
+ assert success and abs(pnt[0] - 20.5) <= 0.05 and abs(pnt[1] - 10.5) <= 0.05, \
+ 'got wrong reverse transform result.(4)'
tr = None
@@ -271,21 +186,13 @@ def transformer_5():
(success, pnt) = tr.TransformPoint(0, 20.5, 10.5, 0)
- if not success \
- or abs(pnt[0] - 125.64828521533849) > 0.000001 \
- or abs(pnt[1] - 39.869345204440144) > 0.000001:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.(5)')
- return 'fail'
+ assert success and abs(pnt[0] - 125.64828521533849) <= 0.000001 and abs(pnt[1] - 39.869345204440144) <= 0.000001, \
+ 'got wrong forward transform result.(5)'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20.5) > 0.05 \
- or abs(pnt[1] - 10.5) > 0.05:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.(5)')
- return 'fail'
+ assert success and abs(pnt[0] - 20.5) <= 0.05 and abs(pnt[1] - 10.5) <= 0.05, \
+ 'got wrong reverse transform result.(5)'
tr = None
@@ -295,21 +202,13 @@ def transformer_5():
(success, pnt) = tr.TransformPoint(0, 20.5, 10.5, 0)
- if not success \
- or abs(pnt[0] - 125.64828521503811) > 0.000001 \
- or abs(pnt[1] - 39.869345204874911) > 0.000001:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.(6)')
- return 'fail'
+ assert success and abs(pnt[0] - 125.64828521503811) <= 0.000001 and abs(pnt[1] - 39.869345204874911) <= 0.000001, \
+ 'got wrong forward transform result.(6)'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - 20.5) > 0.05 \
- or abs(pnt[1] - 10.5) > 0.05:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.(6)')
- return 'fail'
+ assert success and abs(pnt[0] - 20.5) <= 0.05 and abs(pnt[1] - 10.5) <= 0.05, \
+ 'got wrong reverse transform result.(6)'
tr = None
@@ -317,14 +216,10 @@ def transformer_5():
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_HEIGHT_SCALE=2', 'RPC_DEM=/vsimem/dem.tif'])
(success, pnt) = tr.TransformPoint(0, 40000, 0, 0)
- if success != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert success == 0
(success, pnt) = tr.TransformPoint(1, 125, 40, 0)
- if success != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert success == 0
tr = None
@@ -339,74 +234,50 @@ def transformer_5():
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_HEIGHT_SCALE=2', 'RPC_DEM=/vsimem/dem.tif', 'RPC_DEM_MISSING_VALUE=0'])
(success, pnt) = tr.TransformPoint(0, -99.5, 0.5, 0)
- if not success \
- or abs(pnt[0] - 125.64746155942839) > 0.000001 \
- or abs(pnt[1] - 39.869506789921168) > 0.000001:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.')
- return 'fail'
+ assert success and abs(pnt[0] - 125.64746155942839) <= 0.000001 and abs(pnt[1] - 39.869506789921168) <= 0.000001, \
+ 'got wrong forward transform result.'
(success, pnt) = tr.TransformPoint(1, pnt[0], pnt[1], pnt[2])
- if not success \
- or abs(pnt[0] - -99.5) > 0.05 \
- or abs(pnt[1] - 0.5) > 0.05:
- print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
+ assert success and abs(pnt[0] - -99.5) <= 0.05 and abs(pnt[1] - 0.5) <= 0.05, \
+ 'got wrong reverse transform result.'
tr = None
gdal.Unlink('/vsimem/dem.tif')
- return 'success'
-
###############################################################################
# Test RPC convergence bug (bug # 5395)
-def transformer_6():
+def test_transformer_6():
ds = gdal.Open('data/rpc_5395.vrt')
tr = gdal.Transformer(ds, None, ['METHOD=RPC'])
(success, pnt) = tr.TransformPoint(0, 0.5, 0.5)
- if not success \
- or abs(pnt[0] - 28.26163232) > 0.0001 \
- or abs(pnt[1] - -27.79853245) > 0.0001 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.')
- return 'fail'
-
- return 'success'
+ assert success and abs(pnt[0] - 28.26163232) <= 0.0001 and abs(pnt[1] - -27.79853245) <= 0.0001 and pnt[2] == 0, \
+ 'got wrong forward transform result.'
###############################################################################
# Test Transformer.TransformPoints
-def transformer_7():
+def test_transformer_7():
ds = gdal.Open('data/byte.tif')
tr = gdal.Transformer(ds, None, [])
(pnt, success) = tr.TransformPoints(0, [(20, 10)])
- if success[0] == 0 \
- or abs(pnt[0][0] - 441920) > 0.00000001 \
- or abs(pnt[0][1] - 3750720) > 0.00000001 \
- or pnt[0][2] != 0.0:
- print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.')
- return 'fail'
-
- return 'success'
+ assert success[0] != 0 and abs(pnt[0][0] - 441920) <= 0.00000001 and abs(pnt[0][1] - 3750720) <= 0.00000001 and pnt[0][2] == 0.0, \
+ 'got wrong forward transform result.'
###############################################################################
# Test handling of nodata in RPC DEM (#5680)
-def transformer_8():
+def test_transformer_8():
ds = gdal.Open('data/rpc.vrt')
@@ -427,25 +298,21 @@ def transformer_8():
if success:
print(success, pnt)
- gdaltest.post_reason('got wrong forward transform result.')
- return 'fail'
+ pytest.fail('got wrong forward transform result.')
(success, pnt) = tr.TransformPoint(1, 125.64828521533849, 39.869345204440144, 0)
if success:
print(success, pnt)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
+ pytest.fail('got wrong reverse transform result.')
gdal.Unlink('/vsimem/dem.tif')
- return 'success'
-
###############################################################################
# Test RPC DEM line optimization
-def transformer_9():
+def test_transformer_9():
ds = gdal.Open('data/rpc.vrt')
@@ -466,34 +333,21 @@ def transformer_9():
points = [(125.64828521533849, 39.869345204440144)] * 10
(pnt, success) = tr.TransformPoints(1, points)
- if not success[0]:
- gdaltest.post_reason('failure')
- print(method)
- return 'fail'
+ assert success[0], method
pnt_optimized = pnt[0]
(success, pnt) = tr.TransformPoint(1, 125.64828521533849, 39.869345204440144, 0)
- if not success:
- gdaltest.post_reason('failure')
- print(method)
- return 'fail'
-
- if pnt != pnt_optimized:
- gdaltest.post_reason('failure')
- print(method)
- print(pnt)
- print(pnt_optimized)
- return 'fail'
+ assert success, method
- gdal.Unlink('/vsimem/dem.tif')
+ assert pnt == pnt_optimized, method
- return 'success'
+ gdal.Unlink('/vsimem/dem.tif')
###############################################################################
# Test RPC DEM transform from geoid height to ellipsoidal height
-def transformer_10():
+def test_transformer_10():
# Create fake vertical shift grid
out_ds = gdal.GetDriverByName('GTX').Create('tmp/fake.gtx', 10, 10, 1, gdal.GDT_Float32)
@@ -507,13 +361,11 @@ def transformer_10():
sr = osr.SpatialReference()
sr.ImportFromProj4('+proj=longlat +datum=WGS84 +geoidgrids=./tmp/fake.gtx +vunits=m +foo=bar +no_defs')
if sr.ExportToProj4().find('foo=bar') >= 0:
- print('Missing proj.4')
gdal.GetDriverByName('GTX').Delete('tmp/fake.gtx')
- return 'skip'
+ pytest.skip('Missing proj.4')
if sr.ExportToProj4().find('geoidgrids') < 0:
- print('Missing geoidgrids in %s. Outdated proj.4 version' % sr.ExportToProj4())
gdal.GetDriverByName('GTX').Delete('tmp/fake.gtx')
- return 'skip'
+ pytest.skip('Missing geoidgrids in %s. Outdated proj.4 version' % sr.ExportToProj4())
# Create a fake DEM
ds_dem = gdal.GetDriverByName('GTiff').Create('/vsimem/dem.tif', 100, 100, 1, gdal.GDT_Byte)
@@ -552,36 +404,24 @@ def transformer_10():
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_DEM=/vsimem/dem.vrt'])
(success, pnt) = tr.TransformPoint(1, 125.64828521533849, 39.869345204440144, 0)
- if not success \
- or abs(pnt[0] - 27.31476045569616) > 1e-5 \
- or abs(pnt[1] - -53.328814757762302) > 1e-5 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong result.')
- return 'fail'
+ assert success and abs(pnt[0] - 27.31476045569616) <= 1e-5 and abs(pnt[1] - -53.328814757762302) <= 1e-5 and pnt[2] == 0, \
+ 'got wrong result.'
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_DEM=/vsimem/dem.vrt', 'RPC_DEM_APPLY_VDATUM_SHIFT=FALSE'])
(success, pnt) = tr.TransformPoint(1, 125.64828521533849, 39.869345204440144, 0)
- if not success \
- or abs(pnt[0] - 21.445626206892484) > 1e-5 \
- or abs(pnt[1] - 1.6460100520871492) > 1e-5 \
- or pnt[2] != 0:
- print(success, pnt)
- gdaltest.post_reason('got wrong result.')
- return 'fail'
+ assert success and abs(pnt[0] - 21.445626206892484) <= 1e-5 and abs(pnt[1] - 1.6460100520871492) <= 1e-5 and pnt[2] == 0, \
+ 'got wrong result.'
gdal.GetDriverByName('GTX').Delete('tmp/fake.gtx')
gdal.Unlink('/vsimem/dem.tif')
gdal.Unlink('/vsimem/dem.vrt')
- return 'success'
-
###############################################################################
# Test failed inverse RPC transform (#6162)
-def transformer_11():
+def test_transformer_11():
ds = gdal.GetDriverByName('MEM').Create('', 6600, 4400)
rpc = [
@@ -604,24 +444,18 @@ def transformer_11():
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_HEIGHT=4000'])
(success, pnt) = tr.TransformPoint(0, 0, 0, 0)
- if success:
- print(pnt)
- return 'fail'
+ assert not success, pnt
# But this one should succeed
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_HEIGHT=1150'])
(success, pnt) = tr.TransformPoint(0, 0, 0, 0)
- if not success or abs(pnt[0] - 77.350939956024618) > 1e-7 or abs(pnt[1] - 38.739703990877814) > 1e-7:
- print(pnt)
- return 'fail'
-
- return 'success'
+ assert success and abs(pnt[0] - 77.350939956024618) <= 1e-7 and abs(pnt[1] - 38.739703990877814) <= 1e-7
###############################################################################
# Test degenerate cases of TPS transformer
-def transformer_12():
+def test_transformer_12():
ds = gdal.Open("""
@@ -641,9 +475,7 @@ def transformer_12():
""")
tr = gdal.Transformer(ds, None, ['METHOD=GCP_TPS'])
- if tr is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert tr is not None
ds = gdal.Open("""
@@ -665,9 +497,7 @@ def transformer_12():
gdal.ErrorReset()
with gdaltest.error_handler():
tr = gdal.Transformer(ds, None, ['METHOD=GCP_TPS'])
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() != ''
ds = gdal.Open("""
@@ -689,17 +519,13 @@ def transformer_12():
gdal.ErrorReset()
with gdaltest.error_handler():
tr = gdal.Transformer(ds, None, ['METHOD=GCP_TPS'])
- if gdal.GetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert gdal.GetLastErrorMsg() != ''
###############################################################################
# Test inverse RPC transform at DEM edge (#6377)
-def transformer_13():
+def test_transformer_13():
ds = gdal.GetDriverByName('MEM').Create('', 6600, 4400)
rpc = [
@@ -722,17 +548,13 @@ def transformer_13():
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_DEM=data/transformer_13_dem.tif'])
(success, pnt) = tr.TransformPoint(0, 6600, 24)
- if not success or abs(pnt[0] - -108.00066000065341) > 1e-7 or abs(pnt[1] - 39.157694013439489) > 1e-7:
- print(pnt)
- return 'fail'
-
- return 'success'
+ assert success and abs(pnt[0] - -108.00066000065341) <= 1e-7 and abs(pnt[1] - 39.157694013439489) <= 1e-7
###############################################################################
# Test inverse RPC transform when iterations do oscillations (#6377)
-def transformer_14():
+def test_transformer_14():
ds = gdal.GetDriverByName('MEM').Create('', 4032, 2688)
rpc = ["MIN_LAT=0",
"MAX_LAT=0",
@@ -763,41 +585,30 @@ def transformer_14():
gdal.SetConfigOption('RPC_INVERSE_VERBOSE', old_rpc_inverse_verbose)
gdal.SetConfigOption('RPC_INVERSE_LOG', old_rpc_inverse_log)
(success, pnt) = tr.TransformPoint(0, 0, 0)
- if not success or abs(pnt[0] - 1.9391846640653961e-05) > 1e-7 or abs(pnt[1] - -0.0038824752244123275) > 1e-7:
- gdaltest.post_reason('fail')
- print(pnt)
- return 'fail'
+ assert success and abs(pnt[0] - 1.9391846640653961e-05) <= 1e-7 and abs(pnt[1] - -0.0038824752244123275) <= 1e-7
f = gdal.VSIFOpenL('/vsimem/transformer_14.csvt', 'rb')
if f is not None:
content = gdal.VSIFReadL(1, 1000, f).decode('ASCII')
gdal.VSIFCloseL(f)
- if content.find('Integer,Real,Real,Real,String,Real,Real') != 0:
- gdaltest.post_reason('fail')
- print(content)
- return 'fail'
+ assert content.find('Integer,Real,Real,Real,String,Real,Real') == 0
f = gdal.VSIFOpenL('/vsimem/transformer_14.csv', 'rb')
if f is not None:
content = gdal.VSIFReadL(1, 1000, f).decode('ASCII')
gdal.VSIFCloseL(f)
- if content.find("""iter,long,lat,height,WKT,error_pixel_x,error_pixel_y
-0,""") != 0:
- gdaltest.post_reason('fail')
- print(content)
- return 'fail'
+ assert content.find("""iter,long,lat,height,WKT,error_pixel_x,error_pixel_y
+0,""") == 0
gdal.Unlink('/vsimem/transformer_14.csvt')
gdal.Unlink('/vsimem/transformer_14.csv')
- return 'success'
-
###############################################################################
# Test inverse RPC transform with DEM in [-180,180] but guessed longitude going
# beyond
-def transformer_15():
+def test_transformer_15():
ds = gdal.GetDriverByName('MEM').Create('', 6600, 4400)
rpc = [
@@ -834,25 +645,15 @@ def transformer_15():
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_DEM=/vsimem/transformer_15_dem.vrt'])
(success, pnt) = tr.TransformPoint(0, 0, 0)
- if not success or abs(pnt[0] - 180.02280735469199) > 1e-7 or abs(pnt[1] - 0.061069145746997976) > 1e-7:
- print(pnt)
- return 'fail'
+ assert success and abs(pnt[0] - 180.02280735469199) <= 1e-7 and abs(pnt[1] - 0.061069145746997976) <= 1e-7
(success, pnt_forward) = tr.TransformPoint(1, pnt[0], pnt[1], 0)
- if not success \
- or abs(pnt_forward[0] - 0) > 0.1 \
- or abs(pnt_forward[1] - 0) > 0.1:
- print(success, pnt_forward)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
+ assert success and abs(pnt_forward[0] - 0) <= 0.1 and abs(pnt_forward[1] - 0) <= 0.1, \
+ 'got wrong reverse transform result.'
(success, pnt_forward) = tr.TransformPoint(1, pnt[0] - 360, pnt[1], 0)
- if not success \
- or abs(pnt_forward[0] - 0) > 0.1 \
- or abs(pnt_forward[1] - 0) > 0.1:
- print(success, pnt_forward)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
+ assert success and abs(pnt_forward[0] - 0) <= 0.1 and abs(pnt_forward[1] - 0) <= 0.1, \
+ 'got wrong reverse transform result.'
# Now test around -180
ds = gdal.GetDriverByName('MEM').Create('', 6600, 4400)
@@ -862,39 +663,27 @@ def transformer_15():
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_DEM=/vsimem/transformer_15_dem.vrt'])
(success, pnt) = tr.TransformPoint(0, 6600, 4400)
- if not success or abs(pnt[0] - -180.02313813793387) > 1e-7 or abs(pnt[1] - -0.061398913932229765) > 1e-7:
- print(pnt)
- return 'fail'
+ assert success and abs(pnt[0] - -180.02313813793387) <= 1e-7 and abs(pnt[1] - -0.061398913932229765) <= 1e-7
(success, pnt_forward) = tr.TransformPoint(1, pnt[0], pnt[1], 0)
- if not success \
- or abs(pnt_forward[0] - 6600) > 0.1 \
- or abs(pnt_forward[1] - 4400) > 0.1:
- print(success, pnt_forward)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
+ assert success and abs(pnt_forward[0] - 6600) <= 0.1 and abs(pnt_forward[1] - 4400) <= 0.1, \
+ 'got wrong reverse transform result.'
(success, pnt_forward) = tr.TransformPoint(1, pnt[0] + 360, pnt[1], 0)
- if not success \
- or abs(pnt_forward[0] - 6600) > 0.1 \
- or abs(pnt_forward[1] - 4400) > 0.1:
- print(success, pnt_forward)
- gdaltest.post_reason('got wrong reverse transform result.')
- return 'fail'
+ assert success and abs(pnt_forward[0] - 6600) <= 0.1 and abs(pnt_forward[1] - 4400) <= 0.1, \
+ 'got wrong reverse transform result.'
gdal.Unlink('/vsimem/demE179.tif')
gdal.Unlink('/vsimem/demW180.tif')
gdal.Unlink('/vsimem/transformer_15_dem.tif')
gdal.Unlink('/vsimem/transformer_15_dem.vrt')
- return 'success'
-
###############################################################################
# Test approximate sub-transformers in GenImgProjTransformer
# (we mostly test that the parameters are well recognized and serialized)
-def transformer_16():
+def test_transformer_16():
gdal.Translate('/vsimem/transformer_16.tif', 'data/byte.tif', options="-gcp 0 0 440720.000 3751320.000 -gcp 0 20 440720.000 3750120.000 -gcp 20 0 441920.000 3751320.000 -gcp 20 20 441920.000 3750120.000 -a_srs EPSG:26711")
gdal.Warp('/vsimem/transformer_16.vrt', '/vsimem/transformer_16.tif', options='-of VRT -t_srs EPSG:4326 -et 0 -to SRC_APPROX_ERROR_IN_SRS_UNIT=6.05 -to SRC_APPROX_ERROR_IN_PIXEL=0.1 -to REPROJECTION_APPROX_ERROR_IN_SRC_SRS_UNIT=6.1 -to REPROJECTION_APPROX_ERROR_IN_DST_SRS_UNIT=0.0001')
@@ -902,67 +691,23 @@ def transformer_16():
if f is not None:
content = gdal.VSIFReadL(1, 10000, f).decode('ASCII')
gdal.VSIFCloseL(f)
- if content.find('6.05') < 0 or \
- content.find('0.1') < 0 or \
- content.find('0.0001') < 0 or \
- content.find('6.1') < 0:
- gdaltest.post_reason('fail')
- print(content)
- return 'fail'
+ assert (content.find('6.05') >= 0 and \
+ content.find('0.1') >= 0 and \
+ content.find('0.0001') >= 0 and \
+ content.find('6.1') >= 0)
ds = gdal.Translate('', '/vsimem/transformer_16.vrt', format='MEM')
- if ds.GetRasterBand(1).Checksum() != 4727:
- gdaltest.post_reason('failure')
- print(ds.GetRasterBand(1).Checksum())
- return 'fail'
+ assert ds.GetRasterBand(1).Checksum() == 4727
ds = None
gdal.Unlink('/vsimem/transformer_16.tif')
gdal.Unlink('/vsimem/transformer_16.vrt')
- return 'success'
-
###############################################################################
# Test RPC DEM with unexisting RPC DEM file
-def transformer_17():
+def test_transformer_17():
ds = gdal.Open('data/rpc.vrt')
with gdaltest.error_handler():
tr = gdal.Transformer(ds, None, ['METHOD=RPC', 'RPC_DEM=/vsimem/i/donot/exist/dem.tif'])
- if tr is not None:
- return 'fail'
- return 'success'
-
-
-gdaltest_list = [
- transformer_1,
- transformer_2,
- transformer_3,
- transformer_4,
- transformer_5,
- transformer_6,
- transformer_7,
- transformer_8,
- transformer_9,
- transformer_10,
- transformer_11,
- transformer_12,
- transformer_13,
- transformer_14,
- transformer_15,
- transformer_16,
- transformer_17
-]
-
-disabled_gdaltest_list = [
- transformer_11
-]
-
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('transformer')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ assert tr is None
diff --git a/autotest/gcore/virtualmem.py b/autotest/gcore/virtualmem.py
index 5a2ca46ad4aa..cf8f40ff75a5 100755
--- a/autotest/gcore/virtualmem.py
+++ b/autotest/gcore/virtualmem.py
@@ -31,25 +31,24 @@
import sys
-sys.path.append('../pymod')
-import gdaltest
from osgeo import gdal
+import pytest
###############################################################################
# Test linear and tiled virtual mem interfaces in read-only mode
-def virtualmem_1():
+def test_virtualmem_1():
if gdal.GetConfigOption('SKIP_VIRTUALMEM'):
- return 'skip'
+ pytest.skip()
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
except (ImportError, AttributeError):
- return 'skip'
+ pytest.skip()
ds = gdal.Open('../gdrivers/data/small_world.tif')
bufxsize = 400
@@ -68,7 +67,7 @@ def virtualmem_1():
ar_tiled_band1 = ds.GetRasterBand(1).GetTiledVirtualMemArray(gdal.GF_Read, 0, 0, bufxsize, bufysize, tilexsize, tileysize, gdal.GDT_Int16, 1024 * 1024)
except:
pass
- return 'skip'
+ pytest.skip()
ar_flat_band1 = ds.GetRasterBand(1).GetVirtualMemArray(gdal.GF_Read, 0, 0, bufxsize, bufysize, bufxsize, bufysize, gdal.GDT_Int16, 1024 * 1024, 0)
ar_flat_bip = ds.GetVirtualMemArray(gdal.GF_Read, 0, 0, bufxsize, bufysize, bufxsize, bufysize, gdal.GDT_Int16, [1, 2, 3], 0, 1024 * 1024, 0)
@@ -90,28 +89,14 @@ def virtualmem_1():
for y in range(reqysize):
for x in range(reqxsize):
for band in range(3):
- if ar_tip[tiley][tilex][y][x][band] != ar[band][tiley * tileysize + y][tilex * tilexsize + x]:
- gdaltest.post_reason('fail')
- return 'fail'
- if ar_tip[tiley][tilex][y][x][band] != ar_flat_bsq[band][tiley * tileysize + y][tilex * tilexsize + x]:
- gdaltest.post_reason('fail')
- return 'fail'
- if ar_tip[tiley][tilex][y][x][band] != ar_flat_bip[tiley * tileysize + y][tilex * tilexsize + x][band]:
- gdaltest.post_reason('fail')
- return 'fail'
- if ar_tip[tiley][tilex][y][x][band] != ar_bsq[band][tiley][tilex][y][x]:
- gdaltest.post_reason('fail')
- return 'fail'
- if ar_tip[tiley][tilex][y][x][band] != ar_bit[tiley][tilex][band][y][x]:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ar_tip[tiley][tilex][y][x][band] == ar[band][tiley * tileysize + y][tilex * tilexsize + x]
+ assert ar_tip[tiley][tilex][y][x][band] == ar_flat_bsq[band][tiley * tileysize + y][tilex * tilexsize + x]
+ assert ar_tip[tiley][tilex][y][x][band] == ar_flat_bip[tiley * tileysize + y][tilex * tilexsize + x][band]
+ assert ar_tip[tiley][tilex][y][x][band] == ar_bsq[band][tiley][tilex][y][x]
+ assert ar_tip[tiley][tilex][y][x][band] == ar_bit[tiley][tilex][band][y][x]
if band == 0:
- if ar_flat_band1[tiley * tileysize + y][tilex * tilexsize + x] != ar_flat_bip[tiley * tileysize + y][tilex * tilexsize + x][0]:
- gdaltest.post_reason('fail')
- return 'fail'
- if ar_tiled_band1[tiley][tilex][y][x] != ar_flat_bip[tiley * tileysize + y][tilex * tilexsize + x][0]:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ar_flat_band1[tiley * tileysize + y][tilex * tilexsize + x] == ar_flat_bip[tiley * tileysize + y][tilex * tilexsize + x][0]
+ assert ar_tiled_band1[tiley][tilex][y][x] == ar_flat_bip[tiley * tileysize + y][tilex * tilexsize + x][0]
# We need to destroy the array before dataset destruction
ar_flat_band1 = None
@@ -122,24 +107,22 @@ def virtualmem_1():
ar_bsq = None
ds = None
- return 'success'
-
###############################################################################
# Test write mode
-def virtualmem_2():
+def test_virtualmem_2():
if gdal.GetConfigOption('SKIP_VIRTUALMEM'):
- return 'skip'
+ pytest.skip()
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
except (ImportError, AttributeError):
- return 'skip'
+ pytest.skip()
if not sys.platform.startswith('linux'):
- return 'skip'
+ pytest.skip()
ds = gdal.GetDriverByName('MEM').Create('', 100, 100, 1)
ar = ds.GetVirtualMemArray(gdal.GF_Write)
@@ -150,27 +133,23 @@ def virtualmem_2():
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 57182:
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 57182
###############################################################################
# Test virtual mem auto with a raw driver
-def virtualmem_3():
+def test_virtualmem_3():
if gdal.GetConfigOption('SKIP_VIRTUALMEM'):
- return 'skip'
+ pytest.skip()
try:
from osgeo import gdalnumeric
except ImportError:
- return 'skip'
+ pytest.skip()
if not sys.platform.startswith('linux'):
- return 'skip'
+ pytest.skip()
for tmpfile in ['tmp/virtualmem_3.img', '/vsimem/virtualmem_3.img']:
ds = gdal.GetDriverByName('EHdr').Create(tmpfile, 400, 300, 2)
@@ -192,12 +171,8 @@ def virtualmem_3():
ar_255 = gdalnumeric.empty(ds.RasterXSize)
ar_255.fill(255)
for y in range(ds.RasterYSize):
- if not gdalnumeric.array_equal(ar1[y], ar_127):
- gdaltest.post_reason('fail')
- return 'fail'
- if not gdalnumeric.array_equal(ar2[y], ar_255):
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdalnumeric.array_equal(ar1[y], ar_127)
+ assert gdalnumeric.array_equal(ar2[y], ar_255)
# We need to destroy the array before dataset destruction
ar1 = None
ar2 = None
@@ -205,23 +180,22 @@ def virtualmem_3():
gdal.GetDriverByName('EHdr').Delete(tmpfile)
- return 'success'
-
+
###############################################################################
# Test virtual mem auto with GTiff
-def virtualmem_4():
+def test_virtualmem_4():
if gdal.GetConfigOption('SKIP_VIRTUALMEM'):
- return 'skip'
+ pytest.skip()
try:
from osgeo import gdalnumeric
except ImportError:
- return 'skip'
+ pytest.skip()
if not sys.platform.startswith('linux'):
- return 'skip'
+ pytest.skip()
tmpfile = 'tmp/virtualmem_4.tif'
for option in ['INTERLEAVE=PIXEL', 'INTERLEAVE=BAND']:
@@ -231,7 +205,7 @@ def virtualmem_4():
if gdal.GetLastErrorMsg().find('mmap() failed') >= 0:
ar1 = None
ds = None
- return 'skip'
+ pytest.skip()
ar1 = None
ar1 = ds.GetRasterBand(1).GetVirtualMemAutoArray(gdal.GF_Write)
ar1_bis = ds.GetRasterBand(1).GetVirtualMemAutoArray(gdal.GF_Write)
@@ -246,10 +220,7 @@ def virtualmem_4():
ar1_bis = None
ar2 = None
ds = None
- if val != 127:
- gdaltest.post_reason('fail')
- print(val)
- return 'fail'
+ assert val == 127
ds = gdal.Open(tmpfile)
ar1 = ds.GetRasterBand(1).GetVirtualMemAutoArray(gdal.GF_Read)
@@ -260,17 +231,15 @@ def virtualmem_4():
ar_255.fill(255)
for y in range(ds.RasterYSize):
if not gdalnumeric.array_equal(ar1[y], ar_127):
- gdaltest.post_reason('fail')
ar1 = None
ar2 = None
ds = None
- return 'fail'
+ pytest.fail()
if not gdalnumeric.array_equal(ar2[y], ar_255):
- gdaltest.post_reason('fail')
ar1 = None
ar2 = None
ds = None
- return 'fail'
+ pytest.fail()
# We need to destroy the array before dataset destruction
ar1 = None
ar2 = None
@@ -278,19 +247,7 @@ def virtualmem_4():
gdal.GetDriverByName('GTiff').Delete(tmpfile)
- return 'success'
-
-
-gdaltest_list = [virtualmem_1,
- virtualmem_2,
- virtualmem_3,
- virtualmem_4]
-
-
-if __name__ == '__main__':
+
- gdaltest.setup_run('virtualmem')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/vrt_read.py b/autotest/gcore/vrt_read.py
index c43d32ab3aa7..9bfb0d983e43 100755
--- a/autotest/gcore/vrt_read.py
+++ b/autotest/gcore/vrt_read.py
@@ -31,11 +31,10 @@
###############################################################################
import os
-import sys
import shutil
import struct
-sys.path.append('../pymod')
+import pytest
import gdaltest
from osgeo import gdal
@@ -44,71 +43,80 @@
###############################################################################
# When imported build a list of units based on the files available.
-gdaltest_list = []
init_list = [
- ('byte.vrt', 1, 4672, None),
- ('int16.vrt', 1, 4672, None),
- ('uint16.vrt', 1, 4672, None),
- ('int32.vrt', 1, 4672, None),
- ('uint32.vrt', 1, 4672, None),
- ('float32.vrt', 1, 4672, None),
- ('float64.vrt', 1, 4672, None),
- ('cint16.vrt', 1, 5028, None),
- ('cint32.vrt', 1, 5028, None),
- ('cfloat32.vrt', 1, 5028, None),
- ('cfloat64.vrt', 1, 5028, None),
- ('msubwinbyte.vrt', 2, 2699, None),
- ('utmsmall.vrt', 1, 50054, None),
- ('byte_nearest_50pct.vrt', 1, 1192, None),
- ('byte_averaged_50pct.vrt', 1, 1152, None),
- ('byte_nearest_200pct.vrt', 1, 18784, None),
- ('byte_averaged_200pct.vrt', 1, 18784, None)]
+ ('byte.vrt', 4672),
+ ('int16.vrt', 4672),
+ ('uint16.vrt', 4672),
+ ('int32.vrt', 4672),
+ ('uint32.vrt', 4672),
+ ('float32.vrt', 4672),
+ ('float64.vrt', 4672),
+ ('cint16.vrt', 5028),
+ ('cint32.vrt', 5028),
+ ('cfloat32.vrt', 5028),
+ ('cfloat64.vrt', 5028),
+ ('msubwinbyte.vrt', 2699),
+ ('utmsmall.vrt', 50054),
+ ('byte_nearest_50pct.vrt', 1192),
+ ('byte_averaged_50pct.vrt', 1152),
+ ('byte_nearest_200pct.vrt', 18784),
+ ('byte_averaged_200pct.vrt', 18784)
+]
+
+
+@pytest.mark.parametrize(
+ 'filename,checksum',
+ init_list,
+ ids=[tup[0].split('.')[0] for tup in init_list],
+)
+@pytest.mark.require_driver('VRT')
+def test_vrt_open(filename, checksum):
+ ut = gdaltest.GDALTest('VRT', filename, 1, checksum)
+ ut.testOpen()
+
###############################################################################
# The VRT references a non existing TIF file
-def vrt_read_1():
+def test_vrt_read_1():
gdal.PushErrorHandler('CPLQuietErrorHandler')
ds = gdal.Open('data/idontexist.vrt')
gdal.PopErrorHandler()
if ds is None:
- return 'success'
+ return
- return 'fail'
+ pytest.fail()
###############################################################################
# The VRT references a non existing TIF file, but using the proxy pool dataset API (#2837)
-def vrt_read_2():
+def test_vrt_read_2():
ds = gdal.Open('data/idontexist2.vrt')
- if ds is None:
- return 'fail'
+ assert ds is not None
gdal.PushErrorHandler('CPLQuietErrorHandler')
cs = ds.GetRasterBand(1).Checksum()
gdal.PopErrorHandler()
- if cs != 0:
- return 'fail'
+ assert cs == 0
ds.GetMetadata()
ds.GetRasterBand(1).GetMetadata()
ds.GetGCPs()
ds = None
- return 'success'
###############################################################################
# Test init of band data in case of cascaded VRT (ticket #2867)
-def vrt_read_3():
+def test_vrt_read_3():
driver_tif = gdal.GetDriverByName("GTIFF")
@@ -126,26 +134,22 @@ def vrt_read_3():
data = ds.GetRasterBand(1).ReadRaster(90, 0, 20, 100)
got = struct.unpack('B' * 20 * 100, data)
for i in range(100):
- if got[i * 20 + 9] != 255:
- gdaltest.post_reason('at line %d, did not find 255' % i)
- return 'fail'
+ assert got[i * 20 + 9] == 255, ('at line %d, did not find 255' % i)
ds = None
driver_tif.Delete('tmp/test_mosaic1.tif')
driver_tif.Delete('tmp/test_mosaic2.tif')
- return 'success'
-
###############################################################################
# Test complex source with complex data (#3977)
-def vrt_read_4():
+def test_vrt_read_4():
try:
import numpy as np
except ImportError:
- return 'skip'
+ pytest.skip()
data = np.zeros((1, 1), np.complex64)
data[0, 0] = 1. + 3.j
@@ -174,17 +178,15 @@ def vrt_read_4():
gdal.Unlink("/vsimem/test.tif")
if scaleddata[0, 0].real != 5.0 or scaleddata[0, 0].imag != 9.0:
- gdaltest.post_reason('did not get expected value')
print('scaleddata[0, 0]: %f %f' % (scaleddata[0, 0].real, scaleddata[0, 0].imag))
- return 'fail'
-
- return 'success'
+ pytest.fail('did not get expected value')
+
###############################################################################
# Test serializing and deserializing of various band metadata
-def vrt_read_5():
+def test_vrt_read_5():
src_ds = gdal.Open('data/testserialization.asc')
ds = gdal.GetDriverByName('VRT').CreateCopy('/vsimem/vrt_read_5.vrt', src_ds)
@@ -194,105 +196,63 @@ def vrt_read_5():
ds = gdal.Open('/vsimem/vrt_read_5.vrt')
gcps = ds.GetGCPs()
- if len(gcps) != 2 or ds.GetGCPCount() != 2:
- return 'fail'
+ assert len(gcps) == 2 and ds.GetGCPCount() == 2
- if ds.GetGCPProjection().find("WGS 84") == -1:
- print(ds.GetGCPProjection())
- return 'fail'
+ assert ds.GetGCPProjection().find("WGS 84") != -1
ds.SetGCPs(ds.GetGCPs(), ds.GetGCPProjection())
gcps = ds.GetGCPs()
- if len(gcps) != 2 or ds.GetGCPCount() != 2:
- return 'fail'
+ assert len(gcps) == 2 and ds.GetGCPCount() == 2
- if ds.GetGCPProjection().find("WGS 84") == -1:
- print(ds.GetGCPProjection())
- return 'fail'
+ assert ds.GetGCPProjection().find("WGS 84") != -1
band = ds.GetRasterBand(1)
- if band.GetDescription() != 'MyDescription':
- print(band.GetDescription())
- return 'fail'
+ assert band.GetDescription() == 'MyDescription'
- if band.GetUnitType() != 'MyUnit':
- print(band.GetUnitType())
- return 'fail'
+ assert band.GetUnitType() == 'MyUnit'
- if band.GetOffset() != 1:
- print(band.GetOffset())
- return 'fail'
+ assert band.GetOffset() == 1
- if band.GetScale() != 2:
- print(band.GetScale())
- return 'fail'
+ assert band.GetScale() == 2
- if band.GetRasterColorInterpretation() != gdal.GCI_PaletteIndex:
- print(band.GetRasterColorInterpretation())
- return 'fail'
+ assert band.GetRasterColorInterpretation() == gdal.GCI_PaletteIndex
- if band.GetCategoryNames() != ['Cat1', 'Cat2']:
- print(band.GetCategoryNames())
- return 'fail'
+ assert band.GetCategoryNames() == ['Cat1', 'Cat2']
ct = band.GetColorTable()
- if ct.GetColorEntry(0) != (0, 0, 0, 255):
- print(ct.GetColorEntry(0))
- return 'fail'
- if ct.GetColorEntry(1) != (1, 1, 1, 255):
- print(ct.GetColorEntry(1))
- return 'fail'
+ assert ct.GetColorEntry(0) == (0, 0, 0, 255)
+ assert ct.GetColorEntry(1) == (1, 1, 1, 255)
- if band.GetMaximum() != 0:
- print(band.GetMaximum())
- return 'fail'
+ assert band.GetMaximum() == 0
- if band.GetMinimum() != 2:
- print(band.GetMinimum())
- return 'fail'
+ assert band.GetMinimum() == 2
- if band.GetMetadata() != {'STATISTICS_MEAN': '1', 'STATISTICS_MINIMUM': '2', 'STATISTICS_MAXIMUM': '0', 'STATISTICS_STDDEV': '3'}:
- print(band.GetMetadata())
- return 'fail'
+ assert band.GetMetadata() == {'STATISTICS_MEAN': '1', 'STATISTICS_MINIMUM': '2', 'STATISTICS_MAXIMUM': '0', 'STATISTICS_STDDEV': '3'}
ds = None
gdal.Unlink('/vsimem/vrt_read_5.vrt')
- return 'success'
-
###############################################################################
# Test GetMinimum() and GetMaximum()
-def vrt_read_6():
+def test_vrt_read_6():
gdal.Unlink('data/byte.tif.aux.xml')
src_ds = gdal.Open('data/byte.tif')
mem_ds = gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/vrt_read_6.tif', src_ds)
vrt_ds = gdal.GetDriverByName('VRT').CreateCopy('/vsimem/vrt_read_6.vrt', mem_ds)
- if vrt_ds.GetRasterBand(1).GetMinimum() is not None:
- gdaltest.post_reason('got bad minimum value')
- print(vrt_ds.GetRasterBand(1).GetMinimum())
- return 'fail'
- if vrt_ds.GetRasterBand(1).GetMaximum() is not None:
- gdaltest.post_reason('got bad maximum value')
- print(vrt_ds.GetRasterBand(1).GetMaximum())
- return 'fail'
+ assert vrt_ds.GetRasterBand(1).GetMinimum() is None, 'got bad minimum value'
+ assert vrt_ds.GetRasterBand(1).GetMaximum() is None, 'got bad maximum value'
# Now compute source statistics
mem_ds.GetRasterBand(1).ComputeStatistics(False)
- if vrt_ds.GetRasterBand(1).GetMinimum() != 74:
- gdaltest.post_reason('got bad minimum value')
- print(vrt_ds.GetRasterBand(1).GetMinimum())
- return 'fail'
- if vrt_ds.GetRasterBand(1).GetMaximum() != 255:
- gdaltest.post_reason('got bad maximum value')
- print(vrt_ds.GetRasterBand(1).GetMaximum())
- return 'fail'
+ assert vrt_ds.GetRasterBand(1).GetMinimum() == 74, 'got bad minimum value'
+ assert vrt_ds.GetRasterBand(1).GetMaximum() == 255, 'got bad maximum value'
mem_ds = None
vrt_ds = None
@@ -300,13 +260,11 @@ def vrt_read_6():
gdal.GetDriverByName('GTiff').Delete('/vsimem/vrt_read_6.tif')
gdal.GetDriverByName('VRT').Delete('/vsimem/vrt_read_6.vrt')
- return 'success'
-
###############################################################################
# Test GDALOpen() anti-recursion mechanism
-def vrt_read_7():
+def test_vrt_read_7():
filename = "/vsimem/vrt_read_7.vrt"
@@ -328,21 +286,15 @@ def vrt_read_7():
error_msg = gdal.GetLastErrorMsg()
gdal.Unlink(filename)
- if ds is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- if error_msg == '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds is None
- return 'success'
+ assert error_msg != ''
###############################################################################
# Test ComputeRasterMinMax()
-def vrt_read_8():
+def test_vrt_read_8():
src_ds = gdal.Open('data/byte.tif')
mem_ds = gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/vrt_read_8.tif', src_ds)
@@ -357,18 +309,13 @@ def vrt_read_8():
gdal.GetDriverByName('GTiff').Delete('/vsimem/vrt_read_8.tif')
gdal.GetDriverByName('VRT').Delete('/vsimem/vrt_read_8.vrt')
- if vrt_minmax != mem_minmax:
- print(vrt_minmax)
- print(mem_minmax)
- return 'fail'
-
- return 'success'
+ assert vrt_minmax == mem_minmax
###############################################################################
# Test ComputeStatistics()
-def vrt_read_9():
+def test_vrt_read_9():
src_ds = gdal.Open('data/byte.tif')
mem_ds = gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/vrt_read_9.tif', src_ds)
@@ -383,18 +330,13 @@ def vrt_read_9():
gdal.GetDriverByName('GTiff').Delete('/vsimem/vrt_read_9.tif')
gdal.GetDriverByName('VRT').Delete('/vsimem/vrt_read_9.vrt')
- if vrt_stats != mem_stats:
- print(vrt_stats)
- print(mem_stats)
- return 'fail'
-
- return 'success'
+ assert vrt_stats == mem_stats
###############################################################################
# Test GetHistogram() & GetDefaultHistogram()
-def vrt_read_10():
+def test_vrt_read_10():
src_ds = gdal.Open('data/byte.tif')
mem_ds = gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/vrt_read_10.tif', src_ds)
@@ -410,16 +352,9 @@ def vrt_read_10():
content = gdal.VSIFReadL(1, 10000, f).decode('ascii')
gdal.VSIFCloseL(f)
- if vrt_hist != mem_hist:
- gdaltest.post_reason('fail')
- print(vrt_hist)
- print(mem_hist)
- return 'fail'
+ assert vrt_hist == mem_hist
- if content.find('') < 0:
- gdaltest.post_reason('fail')
- print(content)
- return 'fail'
+ assert content.find('') >= 0
# Single source optimization
for i in range(2):
@@ -443,10 +378,7 @@ def vrt_read_10():
content = gdal.VSIFReadL(1, 10000, f).decode('ascii')
gdal.VSIFCloseL(f)
- if content.find('') < 0:
- gdaltest.post_reason('fail')
- print(content)
- return 'fail'
+ assert content.find('') >= 0
# Two sources general case
for i in range(2):
@@ -473,24 +405,19 @@ def vrt_read_10():
content = gdal.VSIFReadL(1, 10000, f).decode('ascii')
gdal.VSIFCloseL(f)
- if content.find('') < 0:
- gdaltest.post_reason('fail')
- print(content)
- return 'fail'
+ assert content.find('') >= 0
gdal.GetDriverByName('GTiff').Delete('/vsimem/vrt_read_10.tif')
gdal.GetDriverByName('VRT').Delete('/vsimem/vrt_read_10.vrt')
- return 'success'
-
###############################################################################
# Test resolving files from a symlinked vrt using relativeToVRT with an absolute symlink
-def vrt_read_11():
+def test_vrt_read_11():
if not gdaltest.support_symlink():
- return 'skip'
+ pytest.skip()
try:
os.remove('tmp/byte.vrt')
@@ -504,20 +431,17 @@ def vrt_read_11():
os.remove('tmp/byte.vrt')
- if ds is None:
- return 'fail'
-
- return 'success'
+ assert ds is not None
###############################################################################
# Test resolving files from a symlinked vrt using relativeToVRT
# with a relative symlink pointing to a relative symlink
-def vrt_read_12():
+def test_vrt_read_12():
if not gdaltest.support_symlink():
- return 'skip'
+ pytest.skip()
try:
os.remove('tmp/byte.vrt')
@@ -531,19 +455,16 @@ def vrt_read_12():
os.remove('tmp/byte.vrt')
- if ds is None:
- return 'fail'
-
- return 'success'
+ assert ds is not None
###############################################################################
# Test resolving files from a symlinked vrt using relativeToVRT with a relative symlink
-def vrt_read_13():
+def test_vrt_read_13():
if not gdaltest.support_symlink():
- return 'skip'
+ pytest.skip()
try:
os.remove('tmp/byte.vrt')
@@ -564,16 +485,13 @@ def vrt_read_13():
os.remove('tmp/other_byte.vrt')
os.remove('tmp/byte.vrt')
- if ds is None:
- return 'fail'
-
- return 'success'
+ assert ds is not None
###############################################################################
# Test ComputeStatistics() when the VRT is a subwindow of the source dataset (#5468)
-def vrt_read_14():
+def test_vrt_read_14():
src_ds = gdal.Open('data/byte.tif')
mem_ds = gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/vrt_read_14.tif', src_ds)
@@ -597,18 +515,13 @@ def vrt_read_14():
gdal.GetDriverByName('GTiff').Delete('/vsimem/vrt_read_14.tif')
- if vrt_stats[0] != 115.0 or vrt_stats[1] != 173.0:
- print(vrt_stats)
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert vrt_stats[0] == 115.0 and vrt_stats[1] == 173.0
###############################################################################
# Test RasterIO() with resampling on SimpleSource
-def vrt_read_15():
+def test_vrt_read_15():
vrt_ds = gdal.Open("""
@@ -630,17 +543,13 @@ def vrt_read_15():
""")
cs = vrt_ds.GetRasterBand(1).Checksum()
- if cs != 1044:
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 1044
###############################################################################
# Test RasterIO() with resampling on ComplexSource
-def vrt_read_16():
+def test_vrt_read_16():
vrt_ds = gdal.Open("""
@@ -662,17 +571,13 @@ def vrt_read_16():
""")
cs = vrt_ds.GetRasterBand(1).Checksum()
- if cs != 1044:
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 1044
###############################################################################
# Test RasterIO() with resampling on AveragedSource
-def vrt_read_17():
+def test_vrt_read_17():
vrt_ds = gdal.Open("""
@@ -689,31 +594,23 @@ def vrt_read_17():
# Note: AveragedSource with resampling does not give consistent results
# depending on the RasterIO() request
cs = vrt_ds.GetRasterBand(1).Checksum()
- if cs != 847:
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 847
###############################################################################
# Test that relative path is correctly VRT-in-VRT
-def vrt_read_18():
+def test_vrt_read_18():
vrt_ds = gdal.Open('data/vrtinvrt.vrt')
cs = vrt_ds.GetRasterBand(1).Checksum()
- if cs != 4672:
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4672
###############################################################################
# Test shared="0"
-def vrt_read_19():
+def test_vrt_read_19():
vrt_ds = gdal.Open("""
@@ -735,25 +632,19 @@ def vrt_read_19():
""")
cs = vrt_ds.GetRasterBand(1).Checksum()
- if cs != 4672:
- print(cs)
- return 'fail'
+ assert cs == 4672
cs = vrt2_ds.GetRasterBand(1).Checksum()
- if cs != 4672:
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4672
###############################################################################
# Test 2 level of VRT with shared="0"
-def vrt_read_20():
+def test_vrt_read_20():
if test_cli_utilities.get_gdalinfo_path() is None:
- return 'skip'
+ pytest.skip()
shutil.copy('data/byte.tif', 'tmp')
for i in range(3):
@@ -794,21 +685,17 @@ def vrt_read_20():
""")
ret = gdaltest.runexternal(test_cli_utilities.get_gdalinfo_path() + ' -checksum tmp/byte2.vrt --config VRT_SHARED_SOURCE 0 --config GDAL_MAX_DATASET_POOL_SIZE 3')
- if ret.find('Checksum=4672') < 0:
- gdaltest.post_reason('failure')
- print(ret)
- return 'fail'
+ assert ret.find('Checksum=4672') >= 0
for f in ['tmp/byte.tif', 'tmp/byte1_1.vrt', 'tmp/byte1_2.vrt', 'tmp/byte1_3.vrt', 'tmp/byte2.vrt']:
os.unlink(f)
- return 'success'
-
+
###############################################################################
# Test implicit virtual overviews
-def vrt_read_21():
+def test_vrt_read_21():
ds = gdal.Open('data/byte.tif')
data = ds.ReadRaster(0, 0, 20, 20, 400, 400)
@@ -830,10 +717,7 @@ def vrt_read_21():
""")
ds = gdal.Open('/vsimem/vrt_read_21.vrt')
- if ds.GetRasterBand(1).GetOverviewCount() != 1:
- gdaltest.post_reason('failure')
- print(ds.GetRasterBand(1).GetOverviewCount())
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 1
data_ds_one_band = ds.ReadRaster(0, 0, 800, 800, 400, 400)
ds = None
@@ -859,76 +743,47 @@ def vrt_read_21():
""")
ds = gdal.Open('/vsimem/vrt_read_21.vrt')
- if ds.GetRasterBand(1).GetOverviewCount() != 1:
- gdaltest.post_reason('failure')
- print(ds.GetRasterBand(1).GetOverviewCount())
- return 'fail'
+ assert ds.GetRasterBand(1).GetOverviewCount() == 1
ds = gdal.Open('/vsimem/vrt_read_21.vrt')
ovr_band = ds.GetRasterBand(1).GetOverview(-1)
- if ovr_band is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ovr_band is None
ovr_band = ds.GetRasterBand(1).GetOverview(1)
- if ovr_band is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ovr_band is None
ovr_band = ds.GetRasterBand(1).GetOverview(0)
- if ovr_band is None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ovr_band is not None
cs = ovr_band.Checksum()
cs2 = ds.GetRasterBand(2).GetOverview(0).Checksum()
data = ds.ReadRaster(0, 0, 800, 800, 400, 400)
- if data != data_ds_one_band + ds.GetRasterBand(2).ReadRaster(0, 0, 800, 800, 400, 400):
- gdaltest.post_reason('failure')
- return 'fail'
+ assert data == data_ds_one_band + ds.GetRasterBand(2).ReadRaster(0, 0, 800, 800, 400, 400)
mem_ds = gdal.GetDriverByName('MEM').Create('', 400, 400, 2)
mem_ds.WriteRaster(0, 0, 400, 400, data)
ref_cs = mem_ds.GetRasterBand(1).Checksum()
ref_cs2 = mem_ds.GetRasterBand(2).Checksum()
mem_ds = None
- if cs != ref_cs:
- gdaltest.post_reason('failure')
- print(cs)
- print(ref_cs)
- return 'fail'
- if cs2 != ref_cs2:
- gdaltest.post_reason('failure')
- print(cs2)
- print(ref_cs2)
- return 'fail'
+ assert cs == ref_cs
+ assert cs2 == ref_cs2
ds.BuildOverviews('NEAR', [2])
expected_cs = ds.GetRasterBand(1).GetOverview(0).Checksum()
expected_cs2 = ds.GetRasterBand(2).GetOverview(0).Checksum()
ds = None
- if cs != expected_cs:
- gdaltest.post_reason('failure')
- print(cs)
- print(expected_cs)
- return 'fail'
- if cs2 != expected_cs2:
- gdaltest.post_reason('failure')
- print(cs2)
- print(expected_cs2)
- return 'fail'
+ assert cs == expected_cs
+ assert cs2 == expected_cs2
gdal.Unlink('/vsimem/vrt_read_21.vrt')
gdal.Unlink('/vsimem/vrt_read_21.vrt.ovr')
gdal.Unlink('/vsimem/byte.tif')
- return 'success'
-
###############################################################################
# Test that we honour NBITS with SimpleSource and ComplexSource
-def vrt_read_22():
+def test_vrt_read_22():
ds = gdal.Open('data/byte.tif')
data = ds.ReadRaster()
@@ -949,28 +804,17 @@ def vrt_read_22():
""")
- if ds.GetRasterBand(1).GetMinimum() != 63:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMinimum() == 63
- if ds.GetRasterBand(1).GetMaximum() != 63:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaximum() == 63
- if ds.GetRasterBand(1).ComputeRasterMinMax() != (63, 63):
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetRasterBand(1).ComputeRasterMinMax() == (63, 63)
- if ds.GetRasterBand(1).ComputeStatistics(False) != [63.0, 63.0, 63.0, 0.0]:
- gdaltest.post_reason('failure')
- print(ds.GetRasterBand(1).ComputeStatistics(False))
- return 'fail'
+ assert ds.GetRasterBand(1).ComputeStatistics(False) == [63.0, 63.0, 63.0, 0.0]
data = ds.ReadRaster()
got = struct.unpack('B' * 20 * 20, data)
- if got[0] != 63:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert got[0] == 63
ds = gdal.Open("""
@@ -983,22 +827,13 @@ def vrt_read_22():
""")
- if ds.GetRasterBand(1).GetMinimum() != 63:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMinimum() == 63
- if ds.GetRasterBand(1).GetMaximum() != 63:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaximum() == 63
- if ds.GetRasterBand(1).ComputeRasterMinMax() != (63, 63):
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetRasterBand(1).ComputeRasterMinMax() == (63, 63)
- if ds.GetRasterBand(1).ComputeStatistics(False) != [63.0, 63.0, 63.0, 0.0]:
- gdaltest.post_reason('failure')
- print(ds.GetRasterBand(1).ComputeStatistics(False))
- return 'fail'
+ assert ds.GetRasterBand(1).ComputeStatistics(False) == [63.0, 63.0, 63.0, 0.0]
ds = gdal.Open("""
@@ -1012,42 +847,30 @@ def vrt_read_22():
""")
- if ds.GetRasterBand(1).GetMinimum() is not None:
- gdaltest.post_reason('failure')
- print(ds.GetRasterBand(1).GetMinimum())
- return 'fail'
+ assert ds.GetRasterBand(1).GetMinimum() is None
- if ds.GetRasterBand(1).GetMaximum() is not None:
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetRasterBand(1).GetMaximum() is None
- if ds.GetRasterBand(1).ComputeRasterMinMax() != (63, 63):
- gdaltest.post_reason('failure')
- return 'fail'
+ assert ds.GetRasterBand(1).ComputeRasterMinMax() == (63, 63)
- if ds.GetRasterBand(1).ComputeStatistics(False) != [63.0, 63.0, 63.0, 0.0]:
- gdaltest.post_reason('failure')
- print(ds.GetRasterBand(1).ComputeStatistics(False))
- return 'fail'
+ assert ds.GetRasterBand(1).ComputeStatistics(False) == [63.0, 63.0, 63.0, 0.0]
gdal.Unlink('/vsimem/byte.tif')
gdal.Unlink('/vsimem/byte.tif.aux.xml')
- return 'success'
-
###############################################################################
# Test non-nearest resampling on a VRT exposing a nodata value but with
# an underlying dataset without nodata
-def vrt_read_23():
+def test_vrt_read_23():
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
import numpy
except (ImportError, AttributeError):
- return 'skip'
+ pytest.skip()
mem_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/vrt_read_23.tif', 2, 1)
mem_ds.GetRasterBand(1).WriteArray(numpy.array([[0, 10]]))
@@ -1061,13 +884,8 @@ def vrt_read_23():
""")
got_ar = ds.GetRasterBand(1).ReadAsArray(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear)
- if list(got_ar[0]) != [0, 10, 10, 10]:
- gdaltest.post_reason('failure')
- print(list(got_ar[0]))
- return 'fail'
- if ds.ReadRaster(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear) != ds.GetRasterBand(1).ReadRaster(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear):
- gdaltest.post_reason('failure')
- return 'fail'
+ assert list(got_ar[0]) == [0, 10, 10, 10]
+ assert ds.ReadRaster(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear) == ds.GetRasterBand(1).ReadRaster(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear)
ds = None
gdal.Unlink('/vsimem/vrt_read_23.tif')
@@ -1086,24 +904,17 @@ def vrt_read_23():
""")
got_ar = ds.GetRasterBand(1).ReadAsArray(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear)
- if list(got_ar[0]) != [0, 10, 10, 10]:
- gdaltest.post_reason('failure')
- print(list(got_ar[0]))
- return 'fail'
- if ds.ReadRaster(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear) != ds.GetRasterBand(1).ReadRaster(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear):
- gdaltest.post_reason('failure')
- return 'fail'
+ assert list(got_ar[0]) == [0, 10, 10, 10]
+ assert ds.ReadRaster(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear) == ds.GetRasterBand(1).ReadRaster(0, 0, 2, 1, 4, 1, resample_alg=gdal.GRIORA_Bilinear)
ds = None
gdal.Unlink('/vsimem/vrt_read_23.tif')
- return 'success'
-
###############################################################################
# Test floating point rounding issues when the VRT does a zoom-in
-def vrt_read_24():
+def test_vrt_read_24():
ds = gdal.Open('data/zoom_in.vrt')
data = ds.ReadRaster(34, 5, 66, 87)
@@ -1116,23 +927,18 @@ def vrt_read_24():
# Please do not change the expected checksum without checking that
# the result image has no vertical black line in the middle
- if cs != 46612:
- gdaltest.post_reason('failure')
- print(cs)
- return 'fail'
+ assert cs == 46612
ds = None
- return 'success'
-
###############################################################################
# Test GetDataCoverageStatus()
-def vrt_read_25():
+def test_vrt_read_25():
import ogrtest
if not ogrtest.have_geos():
- return 'skip'
+ pytest.skip()
ds = gdal.Open("""
@@ -1158,41 +964,23 @@ def vrt_read_25():
""")
(flags, pct) = ds.GetRasterBand(1).GetDataCoverageStatus(0, 0, 20, 20)
- if flags != gdal.GDAL_DATA_COVERAGE_STATUS_DATA or pct != 100.0:
- gdaltest.post_reason('failure')
- print(flags)
- print(pct)
- return 'fail'
+ assert flags == gdal.GDAL_DATA_COVERAGE_STATUS_DATA and pct == 100.0
(flags, pct) = ds.GetRasterBand(1).GetDataCoverageStatus(1005, 35, 10, 10)
- if flags != gdal.GDAL_DATA_COVERAGE_STATUS_DATA or pct != 100.0:
- gdaltest.post_reason('failure')
- print(flags)
- print(pct)
- return 'fail'
+ assert flags == gdal.GDAL_DATA_COVERAGE_STATUS_DATA and pct == 100.0
(flags, pct) = ds.GetRasterBand(1).GetDataCoverageStatus(100, 100, 20, 20)
- if flags != gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY or pct != 0.0:
- gdaltest.post_reason('failure')
- print(flags)
- print(pct)
- return 'fail'
+ assert flags == gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY and pct == 0.0
(flags, pct) = ds.GetRasterBand(1).GetDataCoverageStatus(10, 10, 20, 20)
- if flags != gdal.GDAL_DATA_COVERAGE_STATUS_DATA | gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY or pct != 25.0:
- gdaltest.post_reason('failure')
- print(flags)
- print(pct)
- return 'fail'
-
- return 'success'
+ assert flags == gdal.GDAL_DATA_COVERAGE_STATUS_DATA | gdal.GDAL_DATA_COVERAGE_STATUS_EMPTY and pct == 25.0
###############################################################################
# Test consistency of RasterIO() with resampling, that is extracting different
# sub-windows give consistent results
-def vrt_read_26():
+def test_vrt_read_26():
vrt_ds = gdal.Open("""
@@ -1212,50 +1000,37 @@ def vrt_read_26():
partial_data = vrt_ds.GetRasterBand(1).ReadRaster(1, 1, 1, 1)
partial_data = struct.unpack('B' * 1 * 1, partial_data)
- if partial_data[0] != full_data[22 + 1]:
- gdaltest.post_reason('fail')
- print(full_data)
- print(partial_data[0])
- print(full_data[22 + 1])
- return 'fail'
-
- return 'success'
+ assert partial_data[0] == full_data[22 + 1]
###############################################################################
# Test fix for https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=1553
-def vrt_read_27():
+def test_vrt_read_27():
gdal.Open('data/empty_gcplist.vrt')
- return 'success'
-
###############################################################################
# Test fix for https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=1551
-def vrt_read_28():
+def test_vrt_read_28():
with gdaltest.error_handler():
ds = gdal.Open('')
- if ds is not None:
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# Check VRT source sharing and non-sharing situations (#6949)
-def vrt_read_29():
+def test_vrt_read_29():
f = open('data/byte.tif')
- lst_before = gdaltest.get_opened_files()
+ lst_before = sorted(gdaltest.get_opened_files())
if not lst_before:
- return 'skip'
+ pytest.skip()
f.close()
- lst_before = gdaltest.get_opened_files()
gdal.Translate('tmp/vrt_read_29.tif', 'data/byte.tif')
@@ -1280,52 +1055,35 @@ def vrt_read_29():
"""
+ lst_before = sorted(gdaltest.get_opened_files())
ds = gdal.Open(vrt_text)
# Just after opening, we shouldn't have read the source
- lst = gdaltest.get_opened_files()
- if lst.sort() != lst_before.sort():
- gdaltest.post_reason('fail')
- print(lst)
- print(lst_before)
- return 'fail'
+ lst = sorted(gdaltest.get_opened_files())
+ assert lst == lst_before
# Check that the 2 bands share the same source handle
ds.GetRasterBand(1).Checksum()
- lst = gdaltest.get_opened_files()
- if len(lst) != len(lst_before) + 1:
- gdaltest.post_reason('fail')
- print(lst)
- print(lst_before)
- return 'fail'
+ lst = sorted(gdaltest.get_opened_files())
+ assert len(lst) == len(lst_before) + 1
ds.GetRasterBand(2).Checksum()
- lst = gdaltest.get_opened_files()
- if len(lst) != len(lst_before) + 1:
- gdaltest.post_reason('fail')
- print(lst)
- print(lst_before)
- return 'fail'
+ lst = sorted(gdaltest.get_opened_files())
+ assert len(lst) == len(lst_before) + 1
# Open a second VRT dataset handle
ds2 = gdal.Open(vrt_text)
# Check that it consumes an extra handle
ds2.GetRasterBand(1).Checksum()
- lst = gdaltest.get_opened_files()
- if len(lst) != len(lst_before) + 2:
- gdaltest.post_reason('fail')
- print(lst)
- print(lst_before)
- return 'fail'
+ lst = sorted(gdaltest.get_opened_files())
+ assert len(lst) == len(lst_before) + 2
gdal.Unlink('tmp/vrt_read_29.tif')
- return 'success'
-
###############################################################################
# Check VRT reading with DatasetRasterIO
-def vrt_read_30():
+def test_vrt_read_30():
ds = gdal.Open("""
@@ -1339,18 +1097,14 @@ def vrt_read_30():
data = ds.ReadRaster(0, 0, 2, 2, 2, 2, buf_pixel_space=3, buf_line_space=2 * 3, buf_band_space=1)
got = struct.unpack('B' * 2 * 2 * 3, data)
for i in range(2 * 2 * 3):
- if got[i] != 0:
- print(got)
- return 'fail'
+ assert got[i] == 0
ds = None
- return 'success'
-
###############################################################################
# Check that we take into account intermediate data type demotion
-def vrt_read_31():
+def test_vrt_read_31():
gdal.FileFromMemBuffer('/vsimem/in.asc',
"""ncols 2
@@ -1366,30 +1120,22 @@ def vrt_read_31():
data = ds.GetRasterBand(1).ReadRaster(0, 0, 2, 2, buf_type=gdal.GDT_Float32)
got = struct.unpack('f' * 2 * 2, data)
- if got != (0, 1, 254, 255):
- gdaltest.post_reason('fail')
- print(got)
- return 'fail'
+ assert got == (0, 1, 254, 255)
data = ds.ReadRaster(0, 0, 2, 2, buf_type=gdal.GDT_Float32)
got = struct.unpack('f' * 2 * 2, data)
- if got != (0, 1, 254, 255):
- gdaltest.post_reason('fail')
- print(got)
- return 'fail'
+ assert got == (0, 1, 254, 255)
ds = None
gdal.Unlink('/vsimem/in.asc')
- return 'success'
-
###############################################################################
# Test reading a VRT where the NODATA & NoDataValue are slighly below the
# minimum float value (https://github.com/OSGeo/gdal/issues/1071)
-def vrt_float32_with_nodata_slightly_below_float_min():
+def test_vrt_float32_with_nodata_slightly_below_float_min():
shutil.copyfile('data/minfloat.tif', 'tmp/minfloat.tif')
shutil.copyfile('data/minfloat_nodata_slightly_out_of_float.vrt',
@@ -1407,100 +1153,32 @@ def vrt_float32_with_nodata_slightly_below_float_min():
gdal.Unlink('tmp/minfloat_nodata_slightly_out_of_float.vrt')
# Check that the values were 'normalized' when regenerating the VRT
- if vrt_content.find('-3.402823466385289') >= 0:
- gdaltest.post_reason('did not get expected nodata in rewritten VRT')
- print(vrt_content)
- return 'fail'
+ assert vrt_content.find('-3.402823466385289') < 0, \
+ 'did not get expected nodata in rewritten VRT'
if nodata != -3.4028234663852886e+38:
- gdaltest.post_reason('did not get expected nodata')
print("%.18g" % nodata)
- return 'fail'
+ pytest.fail('did not get expected nodata')
- if stats != [-3.0, 5.0, 1.0, 4.0]:
- gdaltest.post_reason('did not get expected stats')
- print(stats)
- return 'fail'
-
- return 'success'
+ assert stats == [-3.0, 5.0, 1.0, 4.0], 'did not get expected stats'
###############################################################################
# Fix issue raised in https://lists.osgeo.org/pipermail/gdal-dev/2018-December/049415.html
-def vrt_subpixel_offset():
+def test_vrt_subpixel_offset():
ds = gdal.Open('data/vrt_subpixel_offset.vrt')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 4849:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4849
###############################################################################
# Check bug fix of bug fix of
# https://lists.osgeo.org/pipermail/gdal-dev/2018-December/049415.html
-def vrt_dstsize_larger_than_source():
+def test_vrt_dstsize_larger_than_source():
ds = gdal.Open('data/dstsize_larger_than_source.vrt')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 33273:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
-
- return 'success'
-
-for item in init_list:
- ut = gdaltest.GDALTest('VRT', item[0], item[1], item[2])
- if ut is None:
- print('VRT tests skipped')
- sys.exit()
- gdaltest_list.append((ut.testOpen, item[0]))
-
-gdaltest_list.append(vrt_read_1)
-gdaltest_list.append(vrt_read_2)
-gdaltest_list.append(vrt_read_3)
-gdaltest_list.append(vrt_read_4)
-gdaltest_list.append(vrt_read_5)
-gdaltest_list.append(vrt_read_6)
-gdaltest_list.append(vrt_read_7)
-gdaltest_list.append(vrt_read_8)
-gdaltest_list.append(vrt_read_9)
-gdaltest_list.append(vrt_read_10)
-gdaltest_list.append(vrt_read_11)
-gdaltest_list.append(vrt_read_12)
-gdaltest_list.append(vrt_read_13)
-gdaltest_list.append(vrt_read_14)
-gdaltest_list.append(vrt_read_15)
-gdaltest_list.append(vrt_read_16)
-gdaltest_list.append(vrt_read_17)
-gdaltest_list.append(vrt_read_18)
-gdaltest_list.append(vrt_read_19)
-gdaltest_list.append(vrt_read_20)
-gdaltest_list.append(vrt_read_21)
-gdaltest_list.append(vrt_read_22)
-gdaltest_list.append(vrt_read_23)
-gdaltest_list.append(vrt_read_24)
-gdaltest_list.append(vrt_read_25)
-gdaltest_list.append(vrt_read_26)
-gdaltest_list.append(vrt_read_27)
-gdaltest_list.append(vrt_read_28)
-gdaltest_list.append(vrt_read_29)
-gdaltest_list.append(vrt_read_30)
-gdaltest_list.append(vrt_read_31)
-gdaltest_list.append(vrt_float32_with_nodata_slightly_below_float_min)
-gdaltest_list.append(vrt_subpixel_offset)
-gdaltest_list.append(vrt_dstsize_larger_than_source)
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('vrt_read')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+ assert cs == 33273
diff --git a/autotest/gcore/vrtmisc.py b/autotest/gcore/vrtmisc.py
index 3666f74602fd..e1f0f7b2d83b 100755
--- a/autotest/gcore/vrtmisc.py
+++ b/autotest/gcore/vrtmisc.py
@@ -29,52 +29,39 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
from osgeo import gdal
-sys.path.append('../pymod')
-import gdaltest
###############################################################################
# Test linear scaling
-def vrtmisc_1():
+def test_vrtmisc_1():
ds = gdal.Translate('', 'data/byte.tif', options='-of MEM -scale 74 255 0 255')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 4323:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4323, 'did not get expected checksum'
###############################################################################
# Test power scaling
-def vrtmisc_2():
+def test_vrtmisc_2():
ds = gdal.Translate('', 'data/byte.tif', options='-of MEM -scale 74 255 0 255 -exponent 2.2')
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 4159:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4159, 'did not get expected checksum'
###############################################################################
# Test power scaling (not in VRT file)
-def vrtmisc_3():
+def test_vrtmisc_3():
ds = gdal.Open("""
@@ -90,18 +77,13 @@ def vrtmisc_3():
cs = ds.GetRasterBand(1).Checksum()
ds = None
- if cs != 4159:
- gdaltest.post_reason('did not get expected checksum')
- print(cs)
- return 'fail'
-
- return 'success'
+ assert cs == 4159, 'did not get expected checksum'
###############################################################################
# Test multi-band linear scaling with a single -scale occurrence.
-def vrtmisc_4():
+def test_vrtmisc_4():
# -scale specified once applies to all bands
ds = gdal.Translate('', 'data/byte.tif', options='-of MEM -scale 74 255 0 255 -b 1 -b 1')
@@ -109,22 +91,14 @@ def vrtmisc_4():
cs2 = ds.GetRasterBand(2).Checksum()
ds = None
- if cs1 != 4323:
- gdaltest.post_reason('did not get expected checksum')
- print(cs1)
- return 'fail'
- if cs2 != 4323:
- gdaltest.post_reason('did not get expected checksum')
- print(cs2)
- return 'fail'
-
- return 'success'
+ assert cs1 == 4323, 'did not get expected checksum'
+ assert cs2 == 4323, 'did not get expected checksum'
###############################################################################
# Test multi-band linear scaling with -scale_XX syntax
-def vrtmisc_5():
+def test_vrtmisc_5():
# -scale_2 applies to band 2 only
ds = gdal.Translate('', 'data/byte.tif', options='-of MEM -scale_2 74 255 0 255 -b 1 -b 1')
@@ -132,22 +106,14 @@ def vrtmisc_5():
cs2 = ds.GetRasterBand(2).Checksum()
ds = None
- if cs1 != 4672:
- gdaltest.post_reason('did not get expected checksum')
- print(cs1)
- return 'fail'
- if cs2 != 4323:
- gdaltest.post_reason('did not get expected checksum')
- print(cs2)
- return 'fail'
-
- return 'success'
+ assert cs1 == 4672, 'did not get expected checksum'
+ assert cs2 == 4323, 'did not get expected checksum'
###############################################################################
# Test multi-band linear scaling with repeated -scale syntax
-def vrtmisc_6():
+def test_vrtmisc_6():
# -scale repeated as many times as output band number
ds = gdal.Translate('', 'data/byte.tif', options='-of MEM -scale 0 255 0 255 -scale 74 255 0 255 -b 1 -b 1')
@@ -155,22 +121,14 @@ def vrtmisc_6():
cs2 = ds.GetRasterBand(2).Checksum()
ds = None
- if cs1 != 4672:
- gdaltest.post_reason('did not get expected checksum')
- print(cs1)
- return 'fail'
- if cs2 != 4323:
- gdaltest.post_reason('did not get expected checksum')
- print(cs2)
- return 'fail'
-
- return 'success'
+ assert cs1 == 4672, 'did not get expected checksum'
+ assert cs2 == 4323, 'did not get expected checksum'
###############################################################################
# Test multi-band power scaling with a single -scale and -exponent occurrence.
-def vrtmisc_7():
+def test_vrtmisc_7():
# -scale and -exponent, specified once, apply to all bands
ds = gdal.Translate('', 'data/byte.tif', options='-of MEM -scale 74 255 0 255 -exponent 2.2 -b 1 -b 1')
@@ -178,22 +136,14 @@ def vrtmisc_7():
cs2 = ds.GetRasterBand(2).Checksum()
ds = None
- if cs1 != 4159:
- gdaltest.post_reason('did not get expected checksum')
- print(cs1)
- return 'fail'
- if cs2 != 4159:
- gdaltest.post_reason('did not get expected checksum')
- print(cs2)
- return 'fail'
-
- return 'success'
+ assert cs1 == 4159, 'did not get expected checksum'
+ assert cs2 == 4159, 'did not get expected checksum'
###############################################################################
# Test multi-band power scaling with -scale_XX and -exponent_XX syntax
-def vrtmisc_8():
+def test_vrtmisc_8():
# -scale_2 and -exponent_2 apply to band 2 only
ds = gdal.Translate('', 'data/byte.tif', options='-of MEM -scale_2 74 255 0 255 -exponent_2 2.2 -b 1 -b 1')
@@ -201,22 +151,14 @@ def vrtmisc_8():
cs2 = ds.GetRasterBand(2).Checksum()
ds = None
- if cs1 != 4672:
- gdaltest.post_reason('did not get expected checksum')
- print(cs1)
- return 'fail'
- if cs2 != 4159:
- gdaltest.post_reason('did not get expected checksum')
- print(cs2)
- return 'fail'
-
- return 'success'
+ assert cs1 == 4672, 'did not get expected checksum'
+ assert cs2 == 4159, 'did not get expected checksum'
###############################################################################
# Test multi-band linear scaling with repeated -scale and -exponent syntax
-def vrtmisc_9():
+def test_vrtmisc_9():
# -scale and -exponent repeated as many times as output band number
ds = gdal.Translate('', 'data/byte.tif', options='-of MEM -scale 0 255 0 255 -scale 74 255 0 255 -exponent 1 -exponent 2.2 -b 1 -b 1')
@@ -224,22 +166,14 @@ def vrtmisc_9():
cs2 = ds.GetRasterBand(2).Checksum()
ds = None
- if cs1 != 4672:
- gdaltest.post_reason('did not get expected checksum')
- print(cs1)
- return 'fail'
- if cs2 != 4159:
- gdaltest.post_reason('did not get expected checksum')
- print(cs2)
- return 'fail'
-
- return 'success'
+ assert cs1 == 4672, 'did not get expected checksum'
+ assert cs2 == 4159, 'did not get expected checksum'
###############################################################################
# Test metadata serialization (#5944)
-def vrtmisc_10():
+def test_vrtmisc_10():
gdal.FileFromMemBuffer("/vsimem/vrtmisc_10.vrt",
"""
@@ -270,46 +204,26 @@ def vrtmisc_10():
ds = None
ds = gdal.Open("/vsimem/vrtmisc_10.vrt", gdal.GA_Update)
- if ds.GetMetadata() != {'foo': 'bar'}:
- gdaltest.post_reason('fail')
- print(ds.GetMetadata())
- return 'fail'
- if ds.GetMetadata('some_domain') != {'bar': 'baz'}:
- gdaltest.post_reason('fail')
- print(ds.GetMetadata('some_domain'))
- return 'fail'
- if ds.GetMetadata_List('xml:a_xml_domain')[0] != '\n':
- gdaltest.post_reason('fail')
- print(ds.GetMetadata_List('xml:a_xml_domain'))
- return 'fail'
+ assert ds.GetMetadata() == {'foo': 'bar'}
+ assert ds.GetMetadata('some_domain') == {'bar': 'baz'}
+ assert ds.GetMetadata_List('xml:a_xml_domain')[0] == '\n'
# Empty default domain
ds.SetMetadata({})
ds = None
ds = gdal.Open("/vsimem/vrtmisc_10.vrt")
- if ds.GetMetadata() != {}:
- gdaltest.post_reason('fail')
- print(ds.GetMetadata())
- return 'fail'
- if ds.GetMetadata('some_domain') != {'bar': 'baz'}:
- gdaltest.post_reason('fail')
- print(ds.GetMetadata('some_domain'))
- return 'fail'
- if ds.GetMetadata_List('xml:a_xml_domain')[0] != '\n':
- gdaltest.post_reason('fail')
- print(ds.GetMetadata_List('xml:a_xml_domain'))
- return 'fail'
+ assert ds.GetMetadata() == {}
+ assert ds.GetMetadata('some_domain') == {'bar': 'baz'}
+ assert ds.GetMetadata_List('xml:a_xml_domain')[0] == '\n'
ds = None
gdal.Unlink("/vsimem/vrtmisc_10.vrt")
- return "success"
-
###############################################################################
# Test relativeToVRT is preserved during re-serialization (#5985)
-def vrtmisc_11():
+def test_vrtmisc_11():
f = open('tmp/vrtmisc_11.vrt', 'wt')
f.write(
@@ -336,17 +250,13 @@ def vrtmisc_11():
gdal.Unlink("tmp/vrtmisc_11.vrt")
- if data.find('../data/byte.tif') < 0:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return "success"
+ assert data.find('../data/byte.tif') >= 0
###############################################################################
# Test set/delete nodata
-def vrtmisc_12():
+def test_vrtmisc_12():
gdal.FileFromMemBuffer("/vsimem/vrtmisc_12.vrt",
"""
@@ -367,43 +277,31 @@ def vrtmisc_12():
ds = None
ds = gdal.Open("/vsimem/vrtmisc_12.vrt", gdal.GA_Update)
- if ds.GetRasterBand(1).GetNoDataValue() != 123:
- gdaltest.post_reason('fail')
- return 'fail'
- if ds.GetRasterBand(1).DeleteNoDataValue() != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetNoDataValue() == 123
+ assert ds.GetRasterBand(1).DeleteNoDataValue() == 0
ds = None
ds = gdal.Open("/vsimem/vrtmisc_12.vrt")
- if ds.GetRasterBand(1).GetNoDataValue() is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetNoDataValue() is None
ds = None
gdal.Unlink("/vsimem/vrtmisc_12.vrt")
- return "success"
-
###############################################################################
# Test CreateCopy() preserve NBITS
-def vrtmisc_13():
+def test_vrtmisc_13():
ds = gdal.Open('data/oddsize1bit.tif')
out_ds = gdal.GetDriverByName('VRT').CreateCopy('', ds)
- if out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') != '1':
- gdaltest.post_reason('fail')
- return 'fail'
-
- return "success"
+ assert out_ds.GetRasterBand(1).GetMetadataItem('NBITS', 'IMAGE_STRUCTURE') == '1'
###############################################################################
# Test SrcRect/DstRect are serialized as integers
-def vrtmisc_14():
+def test_vrtmisc_14():
src_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/vrtmisc_14_src.tif', 123456789, 1, options=['SPARSE_OK=YES', 'TILED=YES'])
gdal.GetDriverByName('VRT').CreateCopy('/vsimem/vrtmisc_14.vrt', src_ds)
@@ -415,11 +313,8 @@ def vrtmisc_14():
gdal.Unlink("/vsimem/vrtmisc_14_src.tif")
gdal.Unlink("/vsimem/vrtmisc_14.vrt")
- if content.find('= 0 and \
+ content.find('= 0)
src_ds = gdal.GetDriverByName('GTiff').Create('/vsimem/vrtmisc_14_src.tif', 1, 123456789, options=['SPARSE_OK=YES', 'TILED=YES'])
gdal.GetDriverByName('VRT').CreateCopy('/vsimem/vrtmisc_14.vrt', src_ds)
@@ -431,65 +326,41 @@ def vrtmisc_14():
gdal.Unlink("/vsimem/vrtmisc_14_src.tif")
gdal.Unlink("/vsimem/vrtmisc_14.vrt")
- if content.find('= 0 and \
+ content.find('= 0)
###############################################################################
# Test CreateCopy() preserve SIGNEDBYTE
-def vrtmisc_15():
+def test_vrtmisc_15():
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/vrtmisc_15.tif', 1, 1, options=['PIXELTYPE=SIGNEDBYTE'])
out_ds = gdal.GetDriverByName('VRT').CreateCopy('', ds)
- if out_ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') != 'SIGNEDBYTE':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert out_ds.GetRasterBand(1).GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') == 'SIGNEDBYTE'
ds = None
gdal.Unlink('/vsimem/vrtmisc_15.tif')
- return "success"
-
###############################################################################
# Test rounding to closest int for coordinates
-def vrtmisc_16():
+def test_vrtmisc_16():
gdal.BuildVRT('/vsimem/vrtmisc_16.vrt', ['data/vrtmisc16_tile1.tif', 'data/vrtmisc16_tile2.tif'])
fp = gdal.VSIFOpenL('/vsimem/vrtmisc_16.vrt', 'rb')
content = gdal.VSIFReadL(1, 100000, fp).decode('latin1')
gdal.VSIFCloseL(fp)
- if content.find('= 0
+ assert content.find('= 0
+ assert content.find('= 0
+ assert content.find('= 0
gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/vrtmisc_16.tif', gdal.Open('/vsimem/vrtmisc_16.vrt'))
ds = gdal.Open('/vsimem/vrtmisc_16.tif')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 206:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 206
gdal.Unlink('/vsimem/vrtmisc_16.tif')
gdal.Unlink('/vsimem/vrtmisc_16.vrt')
@@ -517,20 +388,15 @@ def vrtmisc_16():
gdal.GetDriverByName('GTiff').CreateCopy('/vsimem/vrtmisc_16.tif', gdal.Open('/vsimem/vrtmisc_16.vrt'))
ds = gdal.Open('/vsimem/vrtmisc_16.tif')
cs = ds.GetRasterBand(1).Checksum()
- if cs != 206:
- gdaltest.post_reason('fail')
- print(cs)
- return 'fail'
+ assert cs == 206
gdal.Unlink('/vsimem/vrtmisc_16.tif')
gdal.Unlink('/vsimem/vrtmisc_16.vrt')
- return "success"
-
###############################################################################
# Check that the serialized xml:VRT doesn't include itself (#6767)
-def vrtmisc_17():
+def test_vrtmisc_17():
ds = gdal.Open('data/byte.tif')
vrt_ds = gdal.GetDriverByName('VRT').CreateCopy('/vsimem/vrtmisc_17.vrt', ds)
@@ -539,38 +405,28 @@ def vrtmisc_17():
gdal.Unlink('/vsimem/vrtmisc_17.vrt')
- if xml_vrt.find('xml:VRT') >= 0:
- return 'fail'
-
- return "success"
+ assert xml_vrt.find('xml:VRT') < 0
###############################################################################
# Check GetMetadata('xml:VRT') behaviour on a in-memory VRT copied from a VRT
-def vrtmisc_18():
+def test_vrtmisc_18():
ds = gdal.Open('data/byte.vrt')
vrt_ds = gdal.GetDriverByName('VRT').CreateCopy('', ds)
xml_vrt = vrt_ds.GetMetadata('xml:VRT')[0]
- if gdal.GetLastErrorMsg() != '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() == ''
vrt_ds = None
- if xml_vrt.find('data/byte.tif') < 0 and \
- xml_vrt.find('data\\byte.tif') < 0:
- gdaltest.post_reason('fail')
- print(xml_vrt)
- return 'fail'
-
- return "success"
+ assert (xml_vrt.find('data/byte.tif') >= 0 or \
+ xml_vrt.find('data\\byte.tif') >= 0)
###############################################################################
# Check RAT support
-def vrtmisc_rat():
+def test_vrtmisc_rat():
ds = gdal.Translate('/vsimem/vrtmisc_rat.tif', 'data/byte.tif', format='MEM')
rat = gdal.RasterAttributeTable()
@@ -580,40 +436,26 @@ def vrtmisc_rat():
vrt_ds = gdal.GetDriverByName('VRT').CreateCopy('/vsimem/vrtmisc_rat.vrt', ds)
xml_vrt = vrt_ds.GetMetadata('xml:VRT')[0]
- if gdal.GetLastErrorMsg() != '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() == ''
vrt_ds = None
- if xml_vrt.find('') < 0:
- gdaltest.post_reason('fail')
- print(xml_vrt)
- return 'fail'
+ assert xml_vrt.find('') >= 0
vrt_ds = gdal.Translate('/vsimem/vrtmisc_rat.vrt', ds, format='VRT', srcWin=[0, 0, 1, 1])
xml_vrt = vrt_ds.GetMetadata('xml:VRT')[0]
- if gdal.GetLastErrorMsg() != '':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert gdal.GetLastErrorMsg() == ''
vrt_ds = None
- if xml_vrt.find('') < 0:
- gdaltest.post_reason('fail')
- print(xml_vrt)
- return 'fail'
+ assert xml_vrt.find('') >= 0
ds = None
vrt_ds = gdal.Open('/vsimem/vrtmisc_rat.vrt', gdal.GA_Update)
rat = vrt_ds.GetRasterBand(1).GetDefaultRAT()
- if rat is None or rat.GetColumnCount() != 1:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert rat is not None and rat.GetColumnCount() == 1
vrt_ds.GetRasterBand(1).SetDefaultRAT(None)
- if vrt_ds.GetRasterBand(1).GetDefaultRAT() is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert vrt_ds.GetRasterBand(1).GetDefaultRAT() is None
vrt_ds = None
ds = None
@@ -621,33 +463,25 @@ def vrtmisc_rat():
gdal.Unlink('/vsimem/vrtmisc_rat.vrt')
gdal.Unlink('/vsimem/vrtmisc_rat.tif')
- return "success"
-
###############################################################################
# Check ColorTable support
-def vrtmisc_colortable():
+def test_vrtmisc_colortable():
ds = gdal.Translate('', 'data/byte.tif', format='VRT')
ct = gdal.ColorTable()
ct.SetColorEntry(0, (255, 255, 255, 255))
ds.GetRasterBand(1).SetColorTable(ct)
- if ds.GetRasterBand(1).GetColorTable().GetCount() != 1:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ds.GetRasterBand(1).GetColorTable().GetCount() == 1
ds.GetRasterBand(1).SetColorTable(None)
- if ds.GetRasterBand(1).GetColorTable() is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ds.GetRasterBand(1).GetColorTable() is None
###############################################################################
# Check histogram support
-def vrtmisc_histogram():
+def test_vrtmisc_histogram():
tmpfile = '/vsimem/vrtmisc_histogram.vrt'
ds = gdal.Translate(tmpfile, 'data/byte.tif', format='VRT')
@@ -658,49 +492,15 @@ def vrtmisc_histogram():
hist = ds.GetRasterBand(1).GetDefaultHistogram(force=0)
ds = None
- if hist != (1.0, 2.0, 2, [3000000000, 4]):
- print(hist)
- return 'fail'
+ assert hist == (1.0, 2.0, 2, [3000000000, 4])
gdal.Unlink(tmpfile)
- return 'success'
###############################################################################
# Cleanup.
-def vrtmisc_cleanup():
- return 'success'
-
-
-gdaltest_list = [
- vrtmisc_1,
- vrtmisc_2,
- vrtmisc_3,
- vrtmisc_4,
- vrtmisc_5,
- vrtmisc_6,
- vrtmisc_7,
- vrtmisc_8,
- vrtmisc_9,
- vrtmisc_10,
- vrtmisc_11,
- vrtmisc_12,
- vrtmisc_13,
- vrtmisc_14,
- vrtmisc_15,
- vrtmisc_16,
- vrtmisc_17,
- vrtmisc_18,
- vrtmisc_rat,
- vrtmisc_colortable,
- vrtmisc_histogram,
- vrtmisc_cleanup]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('vrtmisc')
-
- gdaltest.run_tests(gdaltest_list)
-
- sys.exit(gdaltest.summarize())
+def test_vrtmisc_cleanup():
+ pass
+
+
diff --git a/autotest/gcore/vsiaz.py b/autotest/gcore/vsiaz.py
index a42b6b7a61a2..1f9499317a96 100755
--- a/autotest/gcore/vsiaz.py
+++ b/autotest/gcore/vsiaz.py
@@ -32,10 +32,10 @@
import sys
from osgeo import gdal
-sys.path.append('../pymod')
import gdaltest
import webserver
+import pytest
def open_for_read(uri):
@@ -47,7 +47,7 @@ def open_for_read(uri):
###############################################################################
-def vsiaz_init():
+def test_vsiaz_init():
gdaltest.az_vars = {}
for var in ('AZURE_STORAGE_CONNECTION_STRING', 'AZURE_STORAGE_ACCOUNT',
@@ -56,46 +56,34 @@ def vsiaz_init():
if gdaltest.az_vars[var] is not None:
gdal.SetConfigOption(var, "")
- if gdal.GetSignedURL('/vsiaz/foo/bar') is not None:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert gdal.GetSignedURL('/vsiaz/foo/bar') is None
###############################################################################
# Error cases
-def vsiaz_real_server_errors():
+def test_vsiaz_real_server_errors():
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
# Missing AZURE_STORAGE_ACCOUNT
gdal.ErrorReset()
with gdaltest.error_handler():
f = open_for_read('/vsiaz/foo/bar')
- if f is not None or gdal.VSIGetLastErrorMsg().find('AZURE_STORAGE_ACCOUNT') < 0:
- gdaltest.post_reason('fail')
- print(gdal.VSIGetLastErrorMsg())
- return 'fail'
+ assert f is None and gdal.VSIGetLastErrorMsg().find('AZURE_STORAGE_ACCOUNT') >= 0
gdal.ErrorReset()
with gdaltest.error_handler():
f = open_for_read('/vsiaz_streaming/foo/bar')
- if f is not None or gdal.VSIGetLastErrorMsg().find('AZURE_STORAGE_ACCOUNT') < 0:
- gdaltest.post_reason('fail')
- print(gdal.VSIGetLastErrorMsg())
- return 'fail'
+ assert f is None and gdal.VSIGetLastErrorMsg().find('AZURE_STORAGE_ACCOUNT') >= 0
# Invalid AZURE_STORAGE_CONNECTION_STRING
gdal.SetConfigOption('AZURE_STORAGE_CONNECTION_STRING', 'invalid')
gdal.ErrorReset()
with gdaltest.error_handler():
f = open_for_read('/vsiaz/foo/bar')
- if f is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is None
gdal.SetConfigOption('AZURE_STORAGE_CONNECTION_STRING', '')
gdal.SetConfigOption('AZURE_STORAGE_ACCOUNT', 'AZURE_STORAGE_ACCOUNT')
@@ -104,10 +92,7 @@ def vsiaz_real_server_errors():
gdal.ErrorReset()
with gdaltest.error_handler():
f = open_for_read('/vsiaz/foo/bar')
- if f is not None or gdal.VSIGetLastErrorMsg().find('AZURE_STORAGE_ACCESS_KEY') < 0:
- gdaltest.post_reason('fail')
- print(gdal.VSIGetLastErrorMsg())
- return 'fail'
+ assert f is None and gdal.VSIGetLastErrorMsg().find('AZURE_STORAGE_ACCESS_KEY') >= 0
gdal.SetConfigOption('AZURE_STORAGE_ACCESS_KEY', 'AZURE_STORAGE_ACCESS_KEY')
@@ -118,35 +103,28 @@ def vsiaz_real_server_errors():
if f is not None:
gdal.VSIFCloseL(f)
if gdal.GetConfigOption('APPVEYOR') is not None:
- return 'success'
- gdaltest.post_reason('fail')
- print(gdal.VSIGetLastErrorMsg())
- return 'fail'
+ return
+ pytest.fail(gdal.VSIGetLastErrorMsg())
gdal.ErrorReset()
with gdaltest.error_handler():
f = open_for_read('/vsiaz_streaming/foo/bar.baz')
- if f is not None:
- gdaltest.post_reason('fail')
- print(gdal.VSIGetLastErrorMsg())
- return 'fail'
-
- return 'success'
+ assert f is None, gdal.VSIGetLastErrorMsg()
###############################################################################
-def vsiaz_start_webserver():
+def test_vsiaz_start_webserver():
gdaltest.webserver_process = None
gdaltest.webserver_port = 0
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
(gdaltest.webserver_process, gdaltest.webserver_port) = webserver.launch(handler=webserver.DispatcherHttpHandler)
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
gdal.SetConfigOption('AZURE_STORAGE_CONNECTION_STRING',
'DefaultEndpointsProtocol=http;AccountName=myaccount;AccountKey=MY_ACCOUNT_KEY;EndpointSuffix=127.0.0.1:%d' % gdaltest.webserver_port)
@@ -154,23 +132,18 @@ def vsiaz_start_webserver():
gdal.SetConfigOption('AZURE_STORAGE_ACCESS_KEY', '')
gdal.SetConfigOption('CPL_AZURE_TIMESTAMP', 'my_timestamp')
- return 'success'
-
###############################################################################
# Test with a fake Azure Blob server
-def vsiaz_fake_basic():
+def test_vsiaz_fake_basic():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
signed_url = gdal.GetSignedURL('/vsiaz/az_fake_bucket/resource', ['START_DATE=20180213T123456'])
- if signed_url not in ('http://127.0.0.1:8080/azure/blob/myaccount/az_fake_bucket/resource?se=2018-02-13T13%3A34%3A56Z&sig=9Jc4yBFlSRZSSxf059OohN6pYRrjuHWJWSEuryczN%2FM%3D&sp=r&sr=c&st=2018-02-13T12%3A34%3A56Z&sv=2012-02-12',
- 'http://127.0.0.1:8081/azure/blob/myaccount/az_fake_bucket/resource?se=2018-02-13T13%3A34%3A56Z&sig=9Jc4yBFlSRZSSxf059OohN6pYRrjuHWJWSEuryczN%2FM%3D&sp=r&sr=c&st=2018-02-13T12%3A34%3A56Z&sv=2012-02-12'):
- gdaltest.post_reason('fail')
- print(signed_url)
- return 'fail'
+ assert (signed_url in ('http://127.0.0.1:8080/azure/blob/myaccount/az_fake_bucket/resource?se=2018-02-13T13%3A34%3A56Z&sig=9Jc4yBFlSRZSSxf059OohN6pYRrjuHWJWSEuryczN%2FM%3D&sp=r&sr=c&st=2018-02-13T12%3A34%3A56Z&sv=2012-02-12',
+ 'http://127.0.0.1:8081/azure/blob/myaccount/az_fake_bucket/resource?se=2018-02-13T13%3A34%3A56Z&sig=9Jc4yBFlSRZSSxf059OohN6pYRrjuHWJWSEuryczN%2FM%3D&sp=r&sr=c&st=2018-02-13T12%3A34%3A56Z&sv=2012-02-12'))
def method(request):
@@ -193,16 +166,11 @@ def method(request):
handler.add('GET', '/azure/blob/myaccount/az_fake_bucket/resource', custom_method=method)
with webserver.install_http_handler(handler):
f = open_for_read('/vsiaz/az_fake_bucket/resource')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
data = gdal.VSIFReadL(1, 4, f).decode('ascii')
gdal.VSIFCloseL(f)
- if data != 'foo':
- gdaltest.post_reason('fail')
- print(data)
- return 'fail'
+ assert data == 'foo'
def method(request):
@@ -226,16 +194,11 @@ def method(request):
handler.add('GET', '/azure/blob/myaccount/az_fake_bucket/resource', custom_method=method)
with webserver.install_http_handler(handler):
f = open_for_read('/vsiaz_streaming/az_fake_bucket/resource')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
data = gdal.VSIFReadL(1, 4, f).decode('ascii')
gdal.VSIFCloseL(f)
- if data != 'foo':
- gdaltest.post_reason('fail')
- print(data)
- return 'fail'
+ assert data == 'foo'
handler = webserver.SequentialHandler()
handler.add('HEAD', '/azure/blob/myaccount/az_fake_bucket/resource2.bin', 200,
@@ -243,12 +206,11 @@ def method(request):
with webserver.install_http_handler(handler):
stat_res = gdal.VSIStatL('/vsiaz/az_fake_bucket/resource2.bin')
if stat_res is None or stat_res.size != 1000000:
- gdaltest.post_reason('fail')
if stat_res is not None:
print(stat_res.size)
else:
print(stat_res)
- return 'fail'
+ pytest.fail()
handler = webserver.SequentialHandler()
handler.add('HEAD', '/azure/blob/myaccount/az_fake_bucket/resource2.bin', 200,
@@ -256,23 +218,21 @@ def method(request):
with webserver.install_http_handler(handler):
stat_res = gdal.VSIStatL('/vsiaz_streaming/az_fake_bucket/resource2.bin')
if stat_res is None or stat_res.size != 1000000:
- gdaltest.post_reason('fail')
if stat_res is not None:
print(stat_res.size)
else:
print(stat_res)
- return 'fail'
-
- return 'success'
+ pytest.fail()
+
###############################################################################
# Test ReadDir() with a fake Azure Blob server
-def vsiaz_fake_readdir():
+def test_vsiaz_fake_readdir():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
handler = webserver.SequentialHandler()
handler.add('GET', '/azure/blob/myaccount/az_fake_bucket2?comp=list&delimiter=%2F&prefix=a_dir%2F&restype=container', 200,
@@ -317,41 +277,26 @@ def vsiaz_fake_readdir():
if f is None:
if gdaltest.is_travis_branch('trusty'):
- print('Skipped on trusty branch, but should be investigated')
- return 'skip'
+ pytest.skip('Skipped on trusty branch, but should be investigated')
- gdaltest.post_reason('fail')
- return 'fail'
+ pytest.fail()
gdal.VSIFCloseL(f)
dir_contents = gdal.ReadDir('/vsiaz/az_fake_bucket2/a_dir')
- if dir_contents != ['resource3.bin', 'resource4.bin', 'subdir']:
- gdaltest.post_reason('fail')
- print(dir_contents)
- return 'fail'
- if gdal.VSIStatL('/vsiaz/az_fake_bucket2/a_dir/resource3.bin').size != 123456:
- gdaltest.post_reason('fail')
- print(gdal.VSIStatL('/vsiaz/az_fake_bucket2/a_dir/resource3.bin').size)
- return 'fail'
- if gdal.VSIStatL('/vsiaz/az_fake_bucket2/a_dir/resource3.bin').mtime != 1:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert dir_contents == ['resource3.bin', 'resource4.bin', 'subdir']
+ assert gdal.VSIStatL('/vsiaz/az_fake_bucket2/a_dir/resource3.bin').size == 123456
+ assert gdal.VSIStatL('/vsiaz/az_fake_bucket2/a_dir/resource3.bin').mtime == 1
# ReadDir on something known to be a file shouldn't cause network access
dir_contents = gdal.ReadDir('/vsiaz/az_fake_bucket2/a_dir/resource3.bin')
- if dir_contents is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert dir_contents is None
# Test error on ReadDir()
handler = webserver.SequentialHandler()
handler.add('GET', '/azure/blob/myaccount/az_fake_bucket2?comp=list&delimiter=%2F&prefix=error_test%2F&restype=container', 500)
with webserver.install_http_handler(handler):
dir_contents = gdal.ReadDir('/vsiaz/az_fake_bucket2/error_test/')
- if dir_contents is not None:
- gdaltest.post_reason('fail')
- print(dir_contents)
- return 'fail'
+ assert dir_contents is None
# List containers (empty result)
handler = webserver.SequentialHandler()
@@ -363,10 +308,7 @@ def vsiaz_fake_readdir():
""")
with webserver.install_http_handler(handler):
dir_contents = gdal.ReadDir('/vsiaz/')
- if dir_contents != ['.']:
- gdaltest.post_reason('fail')
- print(dir_contents)
- return 'fail'
+ assert dir_contents == ['.']
gdal.VSICurlClearCache()
@@ -395,29 +337,22 @@ def vsiaz_fake_readdir():
""")
with webserver.install_http_handler(handler):
dir_contents = gdal.ReadDir('/vsiaz/')
- if dir_contents != ['mycontainer1', 'mycontainer2']:
- gdaltest.post_reason('fail')
- print(dir_contents)
- return 'fail'
-
- return 'success'
+ assert dir_contents == ['mycontainer1', 'mycontainer2']
###############################################################################
# Test write
-def vsiaz_fake_write():
+def test_vsiaz_fake_write():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
gdal.VSICurlClearCache()
# Test creation of BlockBob
f = gdal.VSIFOpenL('/vsiaz/test_copy/file.bin', 'wb')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
handler = webserver.SequentialHandler()
@@ -451,42 +386,29 @@ def method(request):
ret = gdal.VSIFWriteL('x' * 35000, 1, 35000, f)
ret += gdal.VSIFWriteL('x' * 5000, 1, 5000, f)
if ret != 40000:
- gdaltest.post_reason('fail')
- print(ret)
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail(ret)
gdal.VSIFCloseL(f)
# Simulate illegal read
f = gdal.VSIFOpenL('/vsiaz/test_copy/file.bin', 'wb')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
with gdaltest.error_handler():
ret = gdal.VSIFReadL(1, 1, f)
- if ret:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
+ assert not ret
gdal.VSIFCloseL(f)
# Simulate illegal seek
f = gdal.VSIFOpenL('/vsiaz/test_copy/file.bin', 'wb')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
with gdaltest.error_handler():
ret = gdal.VSIFSeekL(f, 1, 0)
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
gdal.VSIFCloseL(f)
# Simulate failure when putting BlockBob
f = gdal.VSIFOpenL('/vsiaz/test_copy/file.bin', 'wb')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
handler = webserver.SequentialHandler()
@@ -499,50 +421,40 @@ def method(request):
handler.add('PUT', '/azure/blob/myaccount/test_copy/file.bin', custom_method=method)
if gdal.VSIFSeekL(f, 0, 0) != 0:
- gdaltest.post_reason('fail')
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail()
gdal.VSIFWriteL('x' * 35000, 1, 35000, f)
if gdal.VSIFTellL(f) != 35000:
- gdaltest.post_reason('fail')
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail()
if gdal.VSIFSeekL(f, 35000, 0) != 0:
- gdaltest.post_reason('fail')
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail()
if gdal.VSIFSeekL(f, 0, 1) != 0:
- gdaltest.post_reason('fail')
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail()
if gdal.VSIFSeekL(f, 0, 2) != 0:
- gdaltest.post_reason('fail')
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail()
if gdal.VSIFEofL(f) != 0:
- gdaltest.post_reason('fail')
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail()
with webserver.install_http_handler(handler):
with gdaltest.error_handler():
ret = gdal.VSIFCloseL(f)
if ret == 0:
- gdaltest.post_reason('fail')
- print(ret)
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail(ret)
# Simulate creation of BlockBob over an existing blob of incompatible type
f = gdal.VSIFOpenL('/vsiaz/test_copy/file.bin', 'wb')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
handler = webserver.SequentialHandler()
handler.add('PUT', '/azure/blob/myaccount/test_copy/file.bin', 409)
@@ -555,9 +467,7 @@ def method(request):
gdal.SetConfigOption('VSIAZ_CHUNK_SIZE_BYTES', '10')
f = gdal.VSIFOpenL('/vsiaz/test_copy/file.bin', 'wb')
gdal.SetConfigOption('VSIAZ_CHUNK_SIZE_BYTES', None)
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
handler = webserver.SequentialHandler()
@@ -628,19 +538,15 @@ def method(request):
with webserver.install_http_handler(handler):
ret = gdal.VSIFWriteL('0123456789abcdef', 1, 16, f)
if ret != 16:
- gdaltest.post_reason('fail')
- print(ret)
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail(ret)
gdal.VSIFCloseL(f)
# Test failed creation of AppendBlob
gdal.SetConfigOption('VSIAZ_CHUNK_SIZE_BYTES', '10')
f = gdal.VSIFOpenL('/vsiaz/test_copy/file.bin', 'wb')
gdal.SetConfigOption('VSIAZ_CHUNK_SIZE_BYTES', None)
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
handler = webserver.SequentialHandler()
@@ -656,19 +562,15 @@ def method(request):
with gdaltest.error_handler():
ret = gdal.VSIFWriteL('0123456789abcdef', 1, 16, f)
if ret != 0:
- gdaltest.post_reason('fail')
- print(ret)
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail(ret)
gdal.VSIFCloseL(f)
# Test failed writing of a block of an AppendBlob
gdal.SetConfigOption('VSIAZ_CHUNK_SIZE_BYTES', '10')
f = gdal.VSIFOpenL('/vsiaz/test_copy/file.bin', 'wb')
gdal.SetConfigOption('VSIAZ_CHUNK_SIZE_BYTES', None)
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
handler = webserver.SequentialHandler()
handler.add('PUT', '/azure/blob/myaccount/test_copy/file.bin', 201)
@@ -677,22 +579,19 @@ def method(request):
with gdaltest.error_handler():
ret = gdal.VSIFWriteL('0123456789abcdef', 1, 16, f)
if ret != 0:
- gdaltest.post_reason('fail')
- print(ret)
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail(ret)
gdal.VSIFCloseL(f)
- return 'success'
-
+
###############################################################################
# Test Unlink()
-def vsiaz_fake_unlink():
+def test_vsiaz_fake_unlink():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
# Success
handler = webserver.SequentialHandler()
@@ -700,9 +599,7 @@ def vsiaz_fake_unlink():
handler.add('DELETE', '/azure/blob/myaccount/az_bucket_test_unlink/myfile', 202, {'Connection': 'close'})
with webserver.install_http_handler(handler):
ret = gdal.Unlink('/vsiaz/az_bucket_test_unlink/myfile')
- if ret != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret == 0
# Failure
handler = webserver.SequentialHandler()
@@ -711,26 +608,20 @@ def vsiaz_fake_unlink():
with webserver.install_http_handler(handler):
with gdaltest.error_handler():
ret = gdal.Unlink('/vsiaz/az_bucket_test_unlink/myfile')
- if ret != -1:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ret == -1
###############################################################################
# Test Mkdir() / Rmdir()
-def vsiaz_fake_mkdir_rmdir():
+def test_vsiaz_fake_mkdir_rmdir():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
# Invalid name
ret = gdal.Mkdir('/vsiaz', 0)
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
handler = webserver.SequentialHandler()
handler.add('HEAD', '/azure/blob/myaccount/az_bucket_test_mkdir/dir/', 404, {'Connection': 'close'})
@@ -738,9 +629,7 @@ def vsiaz_fake_mkdir_rmdir():
handler.add('PUT', '/azure/blob/myaccount/az_bucket_test_mkdir/dir/.gdal_marker_for_dir', 201)
with webserver.install_http_handler(handler):
ret = gdal.Mkdir('/vsiaz/az_bucket_test_mkdir/dir', 0)
- if ret != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret == 0
# Try creating already existing directory
handler = webserver.SequentialHandler()
@@ -760,15 +649,11 @@ def vsiaz_fake_mkdir_rmdir():
""")
with webserver.install_http_handler(handler):
ret = gdal.Mkdir('/vsiaz/az_bucket_test_mkdir/dir', 0)
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
# Invalid name
ret = gdal.Rmdir('/vsiaz')
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
# Not a directory
handler = webserver.SequentialHandler()
@@ -783,9 +668,7 @@ def vsiaz_fake_mkdir_rmdir():
""")
with webserver.install_http_handler(handler):
ret = gdal.Rmdir('/vsiaz/az_bucket_test_mkdir/it_is_a_file')
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
# Valid
handler = webserver.SequentialHandler()
@@ -805,9 +688,7 @@ def vsiaz_fake_mkdir_rmdir():
handler.add('DELETE', '/azure/blob/myaccount/az_bucket_test_mkdir/dir/.gdal_marker_for_dir', 202)
with webserver.install_http_handler(handler):
ret = gdal.Rmdir('/vsiaz/az_bucket_test_mkdir/dir')
- if ret != 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret == 0
# Try deleting already deleted directory
handler = webserver.SequentialHandler()
@@ -815,9 +696,7 @@ def vsiaz_fake_mkdir_rmdir():
handler.add('GET', '/azure/blob/myaccount/az_bucket_test_mkdir?comp=list&delimiter=%2F&maxresults=1&prefix=dir%2F&restype=container', 200)
with webserver.install_http_handler(handler):
ret = gdal.Rmdir('/vsiaz/az_bucket_test_mkdir/dir')
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert ret != 0
# Try deleting non-empty directory
handler = webserver.SequentialHandler()
@@ -850,39 +729,30 @@ def vsiaz_fake_mkdir_rmdir():
""")
with webserver.install_http_handler(handler):
ret = gdal.Rmdir('/vsiaz/az_bucket_test_mkdir/dir_nonempty')
- if ret == 0:
- gdaltest.post_reason('fail')
- return 'fail'
-
- return 'success'
+ assert ret != 0
###############################################################################
-def vsiaz_fake_test_BlobEndpointInConnectionString():
+def test_vsiaz_fake_test_BlobEndpointInConnectionString():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
gdal.SetConfigOption('AZURE_STORAGE_CONNECTION_STRING',
'DefaultEndpointsProtocol=http;AccountName=myaccount;AccountKey=MY_ACCOUNT_KEY;BlobEndpoint=http://127.0.0.1:%d/myaccount' % gdaltest.webserver_port)
signed_url = gdal.GetSignedURL('/vsiaz/az_fake_bucket/resource')
- if signed_url.find('http://127.0.0.1:%d/myaccount/az_fake_bucket/resource' % gdaltest.webserver_port) < 0:
- gdaltest.post_reason('fail')
- print(signed_url)
- return 'fail'
-
- return 'success'
+ assert signed_url.find('http://127.0.0.1:%d/myaccount/az_fake_bucket/resource' % gdaltest.webserver_port) >= 0
###############################################################################
-def vsiaz_stop_webserver():
+def test_vsiaz_stop_webserver():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
# Clearcache needed to close all connections, since the Python server
# can only handle one connection at a time
@@ -890,151 +760,96 @@ def vsiaz_stop_webserver():
webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port)
- return 'success'
-
###############################################################################
# Nominal cases (require valid credentials)
-def vsiaz_extra_1():
+def test_vsiaz_extra_1():
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
az_resource = gdal.GetConfigOption('AZ_RESOURCE')
if az_resource is None:
- print('Missing AZ_RESOURCE for running gdaltest_list_extra')
- return 'skip'
+ pytest.skip('Missing AZ_RESOURCE')
if az_resource.find('/') < 0:
path = '/vsiaz/' + az_resource
statres = gdal.VSIStatL(path)
- if statres is None or not stat.S_ISDIR(statres.mode):
- gdaltest.post_reason('fail')
- print('%s is not a valid bucket' % path)
- return 'fail'
+ assert statres is not None and stat.S_ISDIR(statres.mode), \
+ ('%s is not a valid bucket' % path)
readdir = gdal.ReadDir(path)
- if readdir is None:
- gdaltest.post_reason('fail')
- print('ReadDir() should not return empty list')
- return 'fail'
+ assert readdir is not None, 'ReadDir() should not return empty list'
for filename in readdir:
if filename != '.':
subpath = path + '/' + filename
- if gdal.VSIStatL(subpath) is None:
- gdaltest.post_reason('fail')
- print('Stat(%s) should not return an error' % subpath)
- return 'fail'
+ assert gdal.VSIStatL(subpath) is not None, \
+ ('Stat(%s) should not return an error' % subpath)
unique_id = 'vsiaz_test'
subpath = path + '/' + unique_id
ret = gdal.Mkdir(subpath, 0)
- if ret < 0:
- gdaltest.post_reason('fail')
- print('Mkdir(%s) should not return an error' % subpath)
- return 'fail'
+ assert ret >= 0, ('Mkdir(%s) should not return an error' % subpath)
readdir = gdal.ReadDir(path)
- if unique_id not in readdir:
- gdaltest.post_reason('fail')
- print('ReadDir(%s) should contain %s' % (path, unique_id))
- print(readdir)
- return 'fail'
+ assert unique_id in readdir, \
+ ('ReadDir(%s) should contain %s' % (path, unique_id))
ret = gdal.Mkdir(subpath, 0)
- if ret == 0:
- gdaltest.post_reason('fail')
- print('Mkdir(%s) repeated should return an error' % subpath)
- return 'fail'
+ assert ret != 0, ('Mkdir(%s) repeated should return an error' % subpath)
ret = gdal.Rmdir(subpath)
- if ret < 0:
- gdaltest.post_reason('fail')
- print('Rmdir(%s) should not return an error' % subpath)
- return 'fail'
+ assert ret >= 0, ('Rmdir(%s) should not return an error' % subpath)
readdir = gdal.ReadDir(path)
- if unique_id in readdir:
- gdaltest.post_reason('fail')
- print('ReadDir(%s) should not contain %s' % (path, unique_id))
- print(readdir)
- return 'fail'
+ assert unique_id not in readdir, \
+ ('ReadDir(%s) should not contain %s' % (path, unique_id))
ret = gdal.Rmdir(subpath)
- if ret == 0:
- gdaltest.post_reason('fail')
- print('Rmdir(%s) repeated should return an error' % subpath)
- return 'fail'
+ assert ret != 0, ('Rmdir(%s) repeated should return an error' % subpath)
ret = gdal.Mkdir(subpath, 0)
- if ret < 0:
- gdaltest.post_reason('fail')
- print('Mkdir(%s) should not return an error' % subpath)
- return 'fail'
+ assert ret >= 0, ('Mkdir(%s) should not return an error' % subpath)
f = gdal.VSIFOpenL(subpath + '/test.txt', 'wb')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
gdal.VSIFWriteL('hello', 1, 5, f)
gdal.VSIFCloseL(f)
ret = gdal.Rmdir(subpath)
- if ret == 0:
- gdaltest.post_reason('fail')
- print('Rmdir(%s) on non empty directory should return an error' % subpath)
- return 'fail'
+ assert ret != 0, \
+ ('Rmdir(%s) on non empty directory should return an error' % subpath)
f = gdal.VSIFOpenL(subpath + '/test.txt', 'rb')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
data = gdal.VSIFReadL(1, 5, f).decode('utf-8')
- if data != 'hello':
- gdaltest.post_reason('fail')
- print(data)
- return 'fail'
+ assert data == 'hello'
gdal.VSIFCloseL(f)
ret = gdal.Unlink(subpath + '/test.txt')
- if ret < 0:
- gdaltest.post_reason('fail')
- print('Unlink(%s) should not return an error' % (subpath + '/test.txt'))
- return 'fail'
+ assert ret >= 0, \
+ ('Unlink(%s) should not return an error' % (subpath + '/test.txt'))
ret = gdal.Rmdir(subpath)
- if ret < 0:
- gdaltest.post_reason('fail')
- print('Rmdir(%s) should not return an error' % subpath)
- return 'fail'
+ assert ret >= 0, ('Rmdir(%s) should not return an error' % subpath)
- return 'success'
+ return
f = open_for_read('/vsiaz/' + az_resource)
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
ret = gdal.VSIFReadL(1, 1, f)
gdal.VSIFCloseL(f)
- if len(ret) != 1:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
+ assert len(ret) == 1
# Same with /vsiaz_streaming/
f = open_for_read('/vsiaz_streaming/' + az_resource)
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
ret = gdal.VSIFReadL(1, 1, f)
gdal.VSIFCloseL(f)
- if len(ret) != 1:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
+ assert len(ret) == 1
if False: # pylint: disable=using-constant-test
# we actually try to read at read() time and bSetError = false
@@ -1044,69 +859,26 @@ def vsiaz_extra_1():
with gdaltest.error_handler():
gdal.VSIFReadL(1, 1, f)
gdal.VSIFCloseL(f)
- if gdal.VSIGetLastErrorMsg() == '':
- gdaltest.post_reason('fail')
- print(gdal.VSIGetLastErrorMsg())
- return 'fail'
+ assert gdal.VSIGetLastErrorMsg() != ''
# Invalid resource
gdal.ErrorReset()
f = open_for_read('/vsiaz_streaming/' + az_resource + '/invalid_resource.baz')
- if f is not None:
- gdaltest.post_reason('fail')
- print(gdal.VSIGetLastErrorMsg())
- return 'fail'
+ assert f is None, gdal.VSIGetLastErrorMsg()
# Test GetSignedURL()
signed_url = gdal.GetSignedURL('/vsiaz/' + az_resource)
f = open_for_read('/vsicurl_streaming/' + signed_url)
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
ret = gdal.VSIFReadL(1, 1, f)
gdal.VSIFCloseL(f)
- if len(ret) != 1:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
-
- return 'success'
+ assert len(ret) == 1
###############################################################################
-def vsiaz_cleanup():
+def test_vsiaz_cleanup():
for var in gdaltest.az_vars:
gdal.SetConfigOption(var, gdaltest.az_vars[var])
-
- return 'success'
-
-
-gdaltest_list = [vsiaz_init,
- vsiaz_real_server_errors,
- vsiaz_start_webserver,
- vsiaz_fake_basic,
- vsiaz_fake_readdir,
- vsiaz_fake_write,
- vsiaz_fake_unlink,
- vsiaz_fake_mkdir_rmdir,
- vsiaz_fake_test_BlobEndpointInConnectionString,
- vsiaz_stop_webserver,
- vsiaz_cleanup]
-
-# gdaltest_list = [ vsiaz_init, vsiaz_start_webserver, vsiaz_fake_mkdir_rmdir, vsiaz_stop_webserver, vsiaz_cleanup ]
-
-gdaltest_list_extra = [vsiaz_extra_1]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('vsiaz')
-
- if gdal.GetConfigOption('RUN_MANUAL_ONLY', None):
- gdaltest.run_tests(gdaltest_list_extra)
- else:
- gdaltest.run_tests(gdaltest_list + gdaltest_list_extra + [vsiaz_cleanup])
-
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/vsicrypt.py b/autotest/gcore/vsicrypt.py
index 812ed88de0cd..7bab69755c65 100755
--- a/autotest/gcore/vsicrypt.py
+++ b/autotest/gcore/vsicrypt.py
@@ -30,23 +30,24 @@
###############################################################################
import struct
-import sys
from osgeo import gdal
-sys.path.append('../pymod')
import gdaltest
+import pytest
+
+from gcore.testnonboundtoswig import setup as testnonboundtoswig_setup # noqa
###############################################################################
# Use common test for /vsicrypt
-def vsicrypt_1():
+def test_vsicrypt_1():
gdaltest.has_vsicrypt = False
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file.bin', 'wb+')
if fp is None:
- return 'skip'
+ pytest.skip()
gdal.VSIFCloseL(fp)
gdal.Unlink('/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file.bin')
gdaltest.has_vsicrypt = True
@@ -58,79 +59,60 @@ def vsicrypt_1():
# Test various error cases
-def vsicrypt_2():
+def test_vsicrypt_2():
if not gdaltest.has_vsicrypt:
- return 'skip'
+ pytest.skip()
# Missing key
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt//vsimem/file.bin', 'wb+')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Invalid file
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/not_existing/not_existing', 'wb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Invalid file
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/not_existing/not_existing', 'rb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Invalid file
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/not_existing/not_existing', 'ab')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Invalid access
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/not_existing/not_existing', 'foo')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Key to short
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=a,file=/vsimem/file.bin', 'wb+')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Invalid signature
gdal.FileFromMemBuffer('/vsimem/file.bin', 'foo')
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file.bin', 'rb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Generate empty file
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file.bin', 'wb')
gdal.VSIFCloseL(fp)
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file.bin', 'rb')
- if fp is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is not None
gdal.VSIFCloseL(fp)
fp = gdal.VSIFOpenL('/vsimem/file.bin', 'rb')
header = gdal.VSIFReadL(1, 1000, fp)
gdal.VSIFCloseL(fp)
- if len(header) != 46:
- gdaltest.post_reason('fail')
- print(len(header))
- return 'fail'
+ assert len(header) == 46
# Test shortening header
for i in range(46):
@@ -140,9 +122,7 @@ def vsicrypt_2():
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file.bin', 'rb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Test corrupting all bytes of header
for i in range(46):
@@ -193,9 +173,7 @@ def vsicrypt_2():
with gdaltest.error_handler():
fp = gdal.VSIFOpenL(
'/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file.bin', 'rb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Inconsistent initial vector with key check.
header = struct.pack('B' * 39,
@@ -220,9 +198,7 @@ def vsicrypt_2():
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file.bin', 'rb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Test reading with wrong key
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file.bin', 'wb')
@@ -233,15 +209,11 @@ def vsicrypt_2():
content = gdal.VSIFReadL(1, 5, fp).decode('latin1')
gdal.VSIFCloseL(fp)
- if content == 'hello':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert content != 'hello'
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=short_key,file=/vsimem/file.bin', 'ab')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Test reading with wrong key with add_key_check
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,add_key_check=yes,file=/vsimem/file.bin', 'wb')
@@ -250,21 +222,15 @@ def vsicrypt_2():
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=dont_use_in_prod,file=/vsimem/file.bin', 'rb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=short_key,file=/vsimem/file.bin', 'ab')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=dont_use_in_prod,file=/vsimem/file.bin', 'ab')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Test creating with potentially not build-in alg:
with gdaltest.error_handler():
@@ -275,29 +241,23 @@ def vsicrypt_2():
# Invalid sector_size
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,sector_size=1,file=/vsimem/file.bin', 'wb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Sector size (16) should be at least twice larger than the block size (16) in CBC_CTS
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PROD,sector_size=16,mode=CBC_CTS,file=/vsimem/file.bin', 'wb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
gdal.Unlink('/vsimem/file.bin')
- return 'success'
-
###############################################################################
# Test various options
-def vsicrypt_3():
+def test_vsicrypt_3():
if not gdaltest.has_vsicrypt:
- return 'skip'
+ pytest.skip()
for options in ['sector_size=16', 'alg=AES', 'alg=DES_EDE2', 'alg=DES_EDE3', 'alg=SKIPJACK', 'alg=invalid',
'mode=CBC', 'mode=CFB', 'mode=OFB', 'mode=CTR', 'mode=CBC_CTS', 'mode=invalid',
@@ -311,10 +271,7 @@ def vsicrypt_3():
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PRODDONT_USE_IN_PROD,%s,file=/vsimem/file.bin' % options, 'wb')
else:
fp = gdal.VSIFOpenL('/vsicrypt/key=DONT_USE_IN_PRODDONT_USE_IN_PROD,%s,file=/vsimem/file.bin' % options, 'wb')
- if fp is None:
- gdaltest.post_reason('fail')
- print(options)
- return 'fail'
+ assert fp is not None, options
gdal.VSIFWriteL('hello', 1, 5, fp)
gdal.VSIFCloseL(fp)
@@ -322,10 +279,7 @@ def vsicrypt_3():
content = gdal.VSIFReadL(1, 5, fp).decode('latin1')
gdal.VSIFCloseL(fp)
- if content != 'hello':
- gdaltest.post_reason('fail')
- print(options)
- return 'fail'
+ assert content == 'hello', options
# Some of those algs might be missing
for options in ['alg=Blowfish', 'alg=Camellia', 'alg=CAST256', 'alg=MARS', 'alg=IDEA', 'alg=RC5', 'alg=RC6', 'alg=Serpent', 'alg=SHACAL2', 'alg=Twofish', 'alg=XTEA']:
@@ -342,10 +296,7 @@ def vsicrypt_3():
content = gdal.VSIFReadL(1, 5, fp).decode('latin1')
gdal.VSIFCloseL(fp)
- if content != 'hello':
- gdaltest.post_reason('fail')
- print(options)
- return 'fail'
+ assert content == 'hello', options
# Test key generation
@@ -356,9 +307,7 @@ def vsicrypt_3():
# Get the generated random key
key_b64 = gdal.GetConfigOption('VSICRYPT_KEY_B64')
- if key_b64 is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert key_b64 is not None
gdal.VSIFWriteL('hello', 1, 5, fp)
gdal.VSIFCloseL(fp)
@@ -367,10 +316,7 @@ def vsicrypt_3():
content = gdal.VSIFReadL(1, 5, fp).decode('latin1')
gdal.VSIFCloseL(fp)
- if content != 'hello':
- gdaltest.post_reason('fail')
- print(options)
- return 'fail'
+ assert content == 'hello', options
gdal.SetConfigOption('VSICRYPT_KEY_B64', None)
@@ -378,47 +324,31 @@ def vsicrypt_3():
content = gdal.VSIFReadL(1, 5, fp).decode('latin1')
gdal.VSIFCloseL(fp)
- if content != 'hello':
- gdaltest.post_reason('fail')
- print(options)
- return 'fail'
+ assert content == 'hello', options
with gdaltest.error_handler():
statRes = gdal.VSIStatL('/vsicrypt//vsimem/file.bin')
- if statRes is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert statRes is None
ret = gdal.Rename('/vsicrypt//vsimem/file.bin', '/vsicrypt//vsimem/subdir_crypt/file.bin')
- if ret != 0:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
+ assert ret == 0
ret = gdal.Rename('/vsicrypt//vsimem/subdir_crypt/file.bin', '/vsimem/subdir_crypt/file2.bin')
- if ret != 0:
- gdaltest.post_reason('fail')
- print(ret)
- return 'fail'
+ assert ret == 0
dir_content = gdal.ReadDir('/vsicrypt//vsimem/subdir_crypt')
- if dir_content != ['file2.bin']:
- gdaltest.post_reason('fail')
- print(dir_content)
- return 'fail'
+ assert dir_content == ['file2.bin']
gdal.Unlink('/vsimem/subdir_crypt/file2.bin')
- return 'success'
-
###############################################################################
# Test "random" operations against reference filesystem
-def vsicrypt_4():
+def test_vsicrypt_4():
if not gdaltest.has_vsicrypt:
- return 'skip'
+ pytest.skip()
test_file = '/vsicrypt/key=DONT_USE_IN_PROD,sector_size=32,file=/vsimem/file_enc.bin'
ref_file = '/vsimem/file.bin'
@@ -455,11 +385,8 @@ def vsicrypt_4():
if test_content != ref_content:
print(seed)
print('Test content (%d):' % len(test_content))
- print(test_content)
print('')
- print('Ref content (%d):' % len(ref_content))
- print(ref_content)
- return 'fail'
+ pytest.fail('Ref content (%d):' % len(ref_content))
gdal.VSIFSeekL(test_f, 0, 0)
gdal.VSIFSeekL(ref_f, 0, 0)
@@ -469,25 +396,20 @@ def vsicrypt_4():
if test_content != ref_content:
print(seed)
print('Test content (%d):' % len(test_content))
- print(test_content)
print('')
- print('Ref content (%d):' % len(ref_content))
- print(ref_content)
- return 'fail'
+ pytest.fail('Ref content (%d):' % len(ref_content))
gdal.Unlink(test_file)
gdal.Unlink(ref_file)
- return 'success'
-
###############################################################################
# Test random filling of last sector
-def vsicrypt_5():
+def test_vsicrypt_5():
if not gdaltest.has_vsicrypt:
- return 'skip'
+ pytest.skip()
test_file = '/vsicrypt/key=DONT_USE_IN_PROD,file=/vsimem/file_enc.bin'
@@ -504,10 +426,7 @@ def vsicrypt_5():
content = gdal.VSIFReadL(1, 4, f)
content = struct.unpack('B' * len(content), content)
gdal.VSIFCloseL(f)
- if content != (97, 98, 0, 100):
- gdaltest.post_reason('fail')
- print(content)
- return 'fail'
+ assert content == (97, 98, 0, 100)
f = gdal.VSIFOpenL(test_file, 'rb+')
gdal.VSIFReadL(1, 1, f)
@@ -519,10 +438,7 @@ def vsicrypt_5():
content = gdal.VSIFReadL(1, 6, f)
content = struct.unpack('B' * len(content), content)
gdal.VSIFCloseL(f)
- if content != (97, 98, 0, 100, 0, 102):
- gdaltest.post_reason('fail')
- print(content)
- return 'fail'
+ assert content == (97, 98, 0, 100, 0, 102)
f = gdal.VSIFOpenL(test_file, 'rb+')
gdal.VSIFReadL(1, 1, f)
@@ -536,45 +452,32 @@ def vsicrypt_5():
content = gdal.VSIFReadL(1, 8, f)
content = struct.unpack('B' * len(content), content)
gdal.VSIFCloseL(f)
- if content != (97, 98, 0, 100, 0, 102, 0, 104):
- gdaltest.post_reason('fail')
- print(content)
- return 'fail'
+ assert content == (97, 98, 0, 100, 0, 102, 0, 104)
gdal.Unlink(test_file)
- return 'success'
-
###############################################################################
# Test VSISetCryptKey
-def vsicrypt_6():
+def test_vsicrypt_6(testnonboundtoswig_setup): # noqa
try:
import ctypes
except ImportError:
- return 'skip'
- import testnonboundtoswig
-
- testnonboundtoswig.testnonboundtoswig_init()
+ pytest.skip()
- if testnonboundtoswig.gdal_handle is None:
- return 'skip'
-
- testnonboundtoswig.gdal_handle.VSISetCryptKey.argtypes = [ctypes.c_char_p, ctypes.c_int]
- testnonboundtoswig.gdal_handle.VSISetCryptKey.restype = None
+ testnonboundtoswig_setup.VSISetCryptKey.argtypes = [ctypes.c_char_p, ctypes.c_int]
+ testnonboundtoswig_setup.VSISetCryptKey.restype = None
# Set a valid key
- testnonboundtoswig.gdal_handle.VSISetCryptKey('DONT_USE_IN_PROD'.encode('ASCII'), 16)
+ testnonboundtoswig_setup.VSISetCryptKey('DONT_USE_IN_PROD'.encode('ASCII'), 16)
if not gdaltest.has_vsicrypt:
- return 'skip'
+ pytest.skip()
fp = gdal.VSIFOpenL('/vsicrypt/add_key_check=yes,file=/vsimem/file.bin', 'wb+')
- if fp is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is not None
gdal.VSIFWriteL('hello', 1, 5, fp)
gdal.VSIFCloseL(fp)
@@ -582,14 +485,10 @@ def vsicrypt_6():
content = gdal.VSIFReadL(1, 5, fp).decode('latin1')
gdal.VSIFCloseL(fp)
- if content != 'hello':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert content == 'hello'
fp = gdal.VSIFOpenL('/vsicrypt//vsimem/file.bin', 'wb+')
- if fp is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is not None
gdal.VSIFWriteL('hello', 1, 5, fp)
gdal.VSIFCloseL(fp)
@@ -597,48 +496,25 @@ def vsicrypt_6():
content = gdal.VSIFReadL(1, 5, fp).decode('latin1')
gdal.VSIFCloseL(fp)
- if content != 'hello':
- gdaltest.post_reason('fail')
- return 'fail'
+ assert content == 'hello'
# Set a too short key
- testnonboundtoswig.gdal_handle.VSISetCryptKey('bbc'.encode('ASCII'), 3)
+ testnonboundtoswig_setup.VSISetCryptKey('bbc'.encode('ASCII'), 3)
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt//vsimem/file.bin', 'rb')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt//vsimem/file.bin', 'wb+')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
# Erase key
- testnonboundtoswig.gdal_handle.VSISetCryptKey(None, 0)
+ testnonboundtoswig_setup.VSISetCryptKey(None, 0)
with gdaltest.error_handler():
fp = gdal.VSIFOpenL('/vsicrypt//vsimem/file.bin', 'wb+')
- if fp is not None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert fp is None
gdal.Unlink('/vsimem/file.bin')
- return 'success'
-
-
-gdaltest_list = [vsicrypt_1,
- vsicrypt_2,
- vsicrypt_3,
- vsicrypt_4,
- vsicrypt_5,
- vsicrypt_6]
-
-if __name__ == '__main__':
-
- gdaltest.setup_run('vsicrypt')
- gdaltest.run_tests(gdaltest_list)
- sys.exit(gdaltest.summarize())
diff --git a/autotest/gcore/vsicurl.py b/autotest/gcore/vsicurl.py
index ddb82878fc43..a6abc7174194 100755
--- a/autotest/gcore/vsicurl.py
+++ b/autotest/gcore/vsicurl.py
@@ -28,33 +28,29 @@
# DEALINGS IN THE SOFTWARE.
###############################################################################
-import sys
from sys import version_info
import time
from osgeo import gdal
from osgeo import ogr
-sys.path.append('../pymod')
import gdaltest
import webserver
+import pytest
###############################################################################
#
-def vsicurl_1():
+def test_vsicurl_1():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
ds = ogr.Open('/vsizip/vsicurl/http://publicfiles.dep.state.fl.us/dear/BWR_GIS/2007NWFLULC/NWFWMD2007LULC.zip')
- if ds is None:
- return 'fail'
-
- return 'success'
+ assert ds is not None
###############################################################################
#
@@ -62,16 +58,13 @@ def vsicurl_1():
def vsicurl_2():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
ds = gdal.Open('/vsizip//vsicurl/http://eros.usgs.gov/archive/nslrsda/GeoTowns/HongKong/srtm/n22e113.zip/n22e113.bil')
- if ds is None:
- return 'fail'
-
- return 'success'
+ assert ds is not None
###############################################################################
# This server doesn't support range downloading
@@ -79,50 +72,41 @@ def vsicurl_2():
def vsicurl_3():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
ds = ogr.Open('/vsizip/vsicurl/http://www.iucnredlist.org/spatial-data/MAMMALS_TERRESTRIAL.zip')
- if ds is not None:
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# This server doesn't support range downloading
-def vsicurl_4():
+def test_vsicurl_4():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
ds = ogr.Open('/vsizip/vsicurl/http://lelserver.env.duke.edu:8080/LandscapeTools/export/49/Downloads/1_Habitats.zip')
- if ds is not None:
- return 'fail'
-
- return 'success'
+ assert ds is None
###############################################################################
# Test URL unescaping when reading HTTP file list
-def vsicurl_5():
+def test_vsicurl_5():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
ds = gdal.Open('/vsicurl/http://dds.cr.usgs.gov/srtm/SRTM_image_sample/picture%20examples/N34W119_DEM.tif')
- if ds is None:
- return 'fail'
-
- return 'success'
+ assert ds is not None
###############################################################################
# Test with FTP server that doesn't support EPSV command
@@ -130,33 +114,27 @@ def vsicurl_5():
def vsicurl_6_disabled():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
fl = gdal.ReadDir('/vsicurl/ftp://ftp2.cits.rncan.gc.ca/pub/cantopo/250k_tif')
- if not fl:
- return 'fail'
-
- return 'success'
+ assert fl
###############################################################################
# Test Microsoft-IIS/6.0 listing
-def vsicurl_7():
+def test_vsicurl_7():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
fl = gdal.ReadDir('/vsicurl/http://ortho.linz.govt.nz/tifs/2005_06')
- if not fl:
- return 'fail'
-
- return 'success'
+ assert fl
###############################################################################
# Test interleaved reading between 2 datasets
@@ -164,30 +142,27 @@ def vsicurl_7():
def vsicurl_8():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
ds1 = gdal.Open('/vsigzip//vsicurl/http://dds.cr.usgs.gov/pub/data/DEM/250/notavail/C/chipicoten-w.gz')
gdal.Open('/vsizip//vsicurl/http://edcftp.cr.usgs.gov/pub/data/landcover/files/2009/biso/gokn09b_dnbr.zip/nps-serotnbsp-9001-20090321_rd.tif')
cs = ds1.GetRasterBand(1).Checksum()
- if cs != 61342:
- return 'fail'
-
- return 'success'
+ assert cs == 61342
###############################################################################
# Test reading a file with Chinese characters, but the HTTP file listing
# returns escaped sequences instead of the Chinese characters.
-def vsicurl_9():
+def test_vsicurl_9():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
if version_info >= (3, 0, 0):
filename = 'xx\u4E2D\u6587.\u4E2D\u6587'
@@ -196,80 +171,69 @@ def vsicurl_9():
filename = filename.encode('utf-8')
ds = gdal.Open('/vsicurl/http://download.osgeo.org/gdal/data/gtiff/' + filename)
- if ds is None:
- return 'fail'
-
- return 'success'
+ assert ds is not None
###############################################################################
# Test reading a file with escaped Chinese characters.
-def vsicurl_10():
+def test_vsicurl_10():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
ds = gdal.Open('/vsicurl/http://download.osgeo.org/gdal/data/gtiff/xx%E4%B8%AD%E6%96%87.%E4%B8%AD%E6%96%87')
- if ds is None:
- return 'fail'
-
- return 'success'
+ assert ds is not None
###############################################################################
# Test ReadDir() after reading a file on the same server
-def vsicurl_11():
+def test_vsicurl_11():
if not gdaltest.run_slow_tests():
- return 'skip'
+ pytest.skip()
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
f = gdal.VSIFOpenL('/vsicurl/http://download.osgeo.org/gdal/data/bmp/Bug2236.bmp', 'rb')
if f is None:
- return 'skip'
+ pytest.skip()
gdal.VSIFSeekL(f, 1000000, 0)
gdal.VSIFReadL(1, 1, f)
gdal.VSIFCloseL(f)
filelist = gdal.ReadDir('/vsicurl/http://download.osgeo.org/gdal/data/gtiff')
- if filelist is None or not filelist:
- return 'fail'
-
- return 'success'
+ assert filelist is not None and filelist
###############################################################################
-def vsicurl_start_webserver():
+def test_vsicurl_start_webserver():
gdaltest.webserver_process = None
gdaltest.webserver_port = 0
if not gdaltest.built_against_curl():
- return 'skip'
+ pytest.skip()
(gdaltest.webserver_process, gdaltest.webserver_port) = webserver.launch(handler=webserver.DispatcherHttpHandler)
if gdaltest.webserver_port == 0:
- return 'skip'
-
- return 'success'
+ pytest.skip()
+
###############################################################################
-def vsicurl_test_redirect():
+def test_vsicurl_test_redirect():
if gdaltest.is_travis_branch('trusty'):
- print('Skipped on trusty branch, but should be investigated')
- return 'skip'
+ pytest.skip('Skipped on trusty branch, but should be investigated')
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
gdal.VSICurlClearCache()
@@ -326,16 +290,12 @@ def method(request):
with webserver.install_http_handler(handler):
f = gdal.VSIFOpenL('/vsicurl/http://localhost:%d/test_redirect/test.bin' % gdaltest.webserver_port, 'rb')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
gdal.VSIFSeekL(f, 0, 2)
if gdal.VSIFTellL(f) != 1000000:
- gdaltest.post_reason('fail')
- print(gdal.VSIFTellL(f))
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail(gdal.VSIFTellL(f))
gdal.VSIFSeekL(f, 0, 0)
handler = webserver.SequentialHandler()
@@ -375,39 +335,31 @@ def method(request):
with webserver.install_http_handler(handler):
content = gdal.VSIFReadL(1, 16383, f).decode('ascii')
if len(content) != 16383 or content[0] != 'x':
- gdaltest.post_reason('fail')
- print(content)
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail(content)
content = gdal.VSIFReadL(1, 2, f).decode('ascii')
if content != 'xy':
- gdaltest.post_reason('fail')
- print(content)
gdal.VSIFCloseL(f)
- return 'fail'
+ pytest.fail(content)
gdal.VSIFCloseL(f)
- return 'success'
-
###############################################################################
# TODO: better testing
-def vsicurl_test_clear_cache():
+def test_vsicurl_test_clear_cache():
gdal.VSICurlClearCache()
gdal.VSICurlClearCache()
- return 'success'
-
###############################################################################
-def vsicurl_test_retry():
+def test_vsicurl_test_retry():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
handler = webserver.SequentialHandler()
handler.add('GET', '/test_retry/', 404)
@@ -419,10 +371,7 @@ def vsicurl_test_retry():
if f:
data_len = len(gdal.VSIFReadL(1, 1, f))
gdal.VSIFCloseL(f)
- if data_len != 0:
- gdaltest.post_reason('fail')
- print(data_len)
- return 'fail'
+ assert data_len == 0
gdal.VSICurlClearCache()
@@ -434,32 +383,23 @@ def vsicurl_test_retry():
handler.add('GET', '/test_retry/test.txt', 200, {}, 'foo')
with webserver.install_http_handler(handler):
f = gdal.VSIFOpenL('/vsicurl?max_retry=2&retry_delay=0.01&url=http://localhost:%d/test_retry/test.txt' % gdaltest.webserver_port, 'rb')
- if f is None:
- gdaltest.post_reason('fail')
- return 'fail'
+ assert f is not None
gdal.ErrorReset()
with gdaltest.error_handler():
data = gdal.VSIFReadL(1, 3, f).decode('ascii')
error_msg = gdal.GetLastErrorMsg()
gdal.VSIFCloseL(f)
- if data != 'foo':
- gdaltest.post_reason('fail')
- print(data)
- return 'fail'
- if error_msg.find('429') < 0:
- gdaltest.post_reason('fail')
- print(error_msg)
- return 'fail'
-
- return 'success'
+ assert data == 'foo'
+ assert error_msg.find('429') >= 0
+
###############################################################################
-def vsicurl_test_fallback_from_head_to_get():
+def test_vsicurl_test_fallback_from_head_to_get():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
gdal.VSICurlClearCache()
@@ -468,20 +408,17 @@ def vsicurl_test_fallback_from_head_to_get():
handler.add('GET', '/test_fallback_from_head_to_get', 200, {}, 'foo')
with webserver.install_http_handler(handler):
statres = gdal.VSIStatL('/vsicurl/http://localhost:%d/test_fallback_from_head_to_get' % gdaltest.webserver_port)
- if statres.size != 3:
- return 'fail'
+ assert statres.size == 3
gdal.VSICurlClearCache()
- return 'success'
-
###############################################################################
-def vsicurl_test_parse_html_filelist_apache():
+def test_vsicurl_test_parse_html_filelist_apache():
if gdaltest.webserver_port == 0:
- return 'skip'
+ pytest.skip()
handler = webserver.SequentialHandler()
handler.add('GET', '/mydir/', 200, {}, """
@@ -500,31 +437,23 @@ def vsicurl_test_parse_html_filelist_apache():